<?php
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

include "../brain/api/v1/AuthAPI.inc.php";
include "../brain/api/v1/ImagesAPI.inc.php";
include "../brain/api/v1/PagesAPI.inc.php";
include "../brain/api/v1/SettingsAPI.inc.php";
include "../brain/api/v1/InitAPI.inc.php";
include "../brain/api/v1/MailerAPI.inc.php";

class APIControl
{
  public static function get(
    ServerRequestInterface $request,
    ResponseInterface $response,
    array $args
  ): ResponseInterface {
    $filename = "";
    switch (isset($args["third"]) ? $args["third"] : "none") {
      case "status":
        $result = AuthAPI::status();

        break;
      case "page":
        //echo
        if (Member::verifyKey($_GET["key"])) {
          $result = PagesAPI::getPageContent($request, $args);
        } else {
          $result = [
            "message" => "API access denied, homie",
            "type" => "API_ERROR",
          ];
        }
        break;
      case "settings":
        $token = $request->getHeader("fipamo-access-token");
        //Verify token to get site info
        if (isset($token[0])) {
          if (Session::verifyToken($token[0])) {
            $result = SettingsAPI::getInfo($request, $args);
          } else {
            $result = [
              "message" => "Invalid token, API access denied, homie",
              "type" => "API_ERROR",
            ];
          }
        } else {
          $result = [
            "message" => "No token, API access denied, homie",
            "type" => "API_ERROR",
          ];
        }
        break;
      case "files":
        if (Session::active()) {
          if ($args["third"] == "backup") {
            $filename = "../config/backups/latest_backup.zip";
            if (file_exists($filename)) {
              header("Content-Type: application/zip");
              header(
                'Content-Disposition: attachment; filename="' .
                  basename($filename) .
                  '"'
              );
              header("Content-Length: " . filesize($filename));

              flush();
              // return readfile($filename);
              //readfile($filename);
              // delete file
              //unlink($filename);
            }
          }
        } else {
          $result = [
            "message" => "API access denied, homie",
            "type" => "API_ERROR",
          ];
        }
      default:
        break;
    }

    $freshResponse = $response;

    if ($args["third"] == "files") {
      $freshResponse
        ->getBody()
        ->write(file_get_contents("../config/backups/latest_back.zip"));

      $freshResponse->withHeader("Content-Type", "application/zip");
      return $freshResponse->withAddedHeader(
        "Content-Disposition",
        "attachment; filename=latest_backup.zip"
      );
    } else {
      $response->getBody()->write(json_encode($result));
      return $response->withHeader("Content-Type", "application/json");
    }
  }
  public static function post(
    ServerRequestInterface $request,
    ResponseInterface $response,
    array $args
  ): ResponseInterface {
    $contentType = $request->getHeader("Content-Type");
    switch ($contentType[0]) {
      case "application/json":
        $body = json_decode(file_get_contents("php://input"), true);
        break;
      default:
        break;
    }

    switch (isset($args["third"]) ? $args["third"] : "none") {
      case "restore": //move to 'api/auth'
      case "init": //move to 'api/auth'
        $task = $args["third"];
        $result = InitApi::handleInitTasks(
          $task,
          $task == "init" ? $body : $request
        );
        break;
      case "backup": //move to 'api/auth'
        $token = $request->getHeader("fipamo-access-token");
        //Verify token for admin tasks
        $result = SettingsAPI::createBackup();
        /*
                
                if (Session::verifyToken($token[0])) {
                    $result = SettingsAPI::createBackup();
                } else {
                    $result = [
                        "message" => "API access denied, homie",
                        "type" => "API_ERROR",
                    ];
                }
                */
        break;
      case "login": //move to 'api/auth'
        //check if request is remote and if so, verify token
        if ($body["remote"] || $body["remote"] == "true") {
          if (Member::verifyKey($body["key"])) {
            $result = AuthAPI::login($body);
          } else {
            $result = [
              "message" => "API access denied, homie",
              "type" => "API_ERROR",
            ];
          }
        } else {
          //request is local, so it's cool
          $result = AuthAPI::login($body);
        }

        break;
      case "logout": //move to 'api/auth'
        $result = AuthAPI::logout($body);
        break;
      case "get-secret": //move to 'api/auth'
        $result = AuthAPI::requestSecret($body);
        break;
      case "reset-password": //move to 'api/auth'
        $result = AuthAPI::resetPassword($body);
        break;
      case "page":
        $token = $request->getHeader("fipamo-access-token");
        //Verify token for admin tasks
        if (isset($token[0])) {
          if (Session::verifyToken($token[0])) {
            $result = PagesAPI::handlePageTask($request, $args);
          } else {
            $result = [
              "message" => "Invalid token, API access denied, homie",
              "type" => "API_ERROR",
            ];
          }
        } else {
          $result = [
            "message" => "No token, API access denied, homie",
            "type" => "API_ERROR",
          ];
        }

        break;
      case "settings":
        if (isset($body)) {
          $postBody = $body;
        } else {
          $postBody = null;
        }
        $task = $args["fourth"];
        if ($task == "add-feature-background" || $task == "add-avatar") {
          $result = SettingsAPI::handleSettingsTask($request, $args, $postBody);
        } else {
          $token = $request->getHeader("fipamo-access-token");
          if (Session::verifyToken($token[0])) {
            $result = SettingsAPI::handleSettingsTask(
              $request,
              $args,
              $postBody
            );
          } else {
            $result = [
              "message" => "API access denied, homie",
              "type" => "API_ERROR",
            ];
          }
        }

        break;
      case "mailer":
        $result = MailerAPI::handleMail($request, $body, $response);
        break;
      default:
        $result = [
          "message" => "Oh, nothing to do. That's unfortunate",
          "type" => "TASK_NONE",
        ];
        break;
    }

    $response->getBody()->write(json_encode($result));
    return $response->withHeader("Content-Type", "application/json");
  }
}
