<?php
use function _\find;
class SetUp
{
  public static function status()
  {
    if (file_exists("../config/settings.json")) {
      return true;
    } else {
      return false;
    }
  }

  public static function init($body)
  {
    //grab template files
    $newFolks = json_decode(
      file_get_contents("../config/init/folks-template.json"),
      true
    );
    $newSettings = json_decode(
      file_get_contents("../config/init/settings-template.json"),
      true
    );
    //get form values
    //$body = $request->getParsedBody();
    $handle = $body["new_member_handle"];
    $email = $body["new_member_email"];
    $pass = $body["new_member_pass"];
    $title = $body["new_member_title"];

    $now = new \Moment\Moment();
    //setup folks config
    $hash = password_hash($pass, PASSWORD_DEFAULT);
    $newFolks[0]["id"] = 0;
    $newFolks[0]["handle"] = $handle;
    $newFolks[0]["email"] = $email;
    $newFolks[0]["password"] = $hash;
    $newFolks[0]["key"] = password_hash($email, PASSWORD_DEFAULT);
    $newFolks[0]["secret"] = StringTools::randomString(12);
    $newFolks[0]["role"] = "hnic";
    $newFolks[0]["created"] = $now->format("Y-m-d\TH:i:sP");
    $newFolks[0]["updated"] = $now->format("Y-m-d\TH:i:sP");
    //set up settings config
    $newSettings["global"]["title"] = $title;

    //create index file
    //$rightNow = $now->format("Y-m-d\TH:i:sP");
    //var_dump($now->format("Y-m-d\TH:i:sP"));
    $index = [
      "id" => 1,
      "uuid" => StringTools::createUUID(),
      "title" => "FIRST!",
      "feature" => "/assets/images/global/default-bg.jpg",
      "path" => "content/pages/start",
      "layout" => "index",
      "tags" => "start, welcome",
      "author" => $handle,
      "created" => $now->format("Y-m-d\TH:i:sP"),
      "updated" => $now->format("Y-m-d\TH:i:sP"),
      "deleted" => "false",
      "slug" => "first",
      "menu" => "false",
      "featured" => "false",
      "published" => "true",
      "content" =>
        "# F**k Yes \n\nIf you're seeing this, you're up and running. NICE WORK!\n\nFrom here, feel free to start dropping pages to your heart's content.\n\nFor some tips about using Fipamo, check out the ![docs](https://code.playvicio.us/Are0h/Fipamo/wiki/02-Usage)\n\nAll good? Feel free to edit this page to whatever you want!\n\nYOU'RE THE CAPTAIN NOW.",
    ];

    $freshIndex = DocTools::objectToMD($index);

    //once all files created, write down

    DocTools::writeSettings("../config/settings.json", $newSettings);
    DocTools::writeSettings("../config/folks.json", $newFolks);
    DocTools::writeSettings("../config/tags.json", []);
    DocTools::writePages(
      "create",
      "start",
      "../content/pages/start/index.md",
      $freshIndex
    );

    //if there is an older session file, get rid of it
    if (is_file("../content/.session")) {
      unlink("../content/.session");
    }

    $result = ["type" => "blogInitGood", "message" => "Site Created"];

    return $result;
  }

  public static function restore($request)
  {
    $result = [
      "type" => "requestLame",
      "message" => "Still working on it.",
    ];
    $body = $request->getParsedBody();

    $backup = $request->getUploadedFiles();
    $file = $backup["backup-upload"];
    $size = $file->getSize();
    $name = $file->getClientFileName();

    //park it so it can be read
    $file->moveTo("../content" . "/" . $name);

    //open it and get files to verify user
    $zip = new ZipArchive();
    if ($zip->open("../content" . "/" . $name) === true) {
      $folks = json_decode($zip->getFromName("settings/folks.json"), true);
      $found = find($folks, ["handle" => $body["restore_member_handle"]]);

      //if member is found in back up, check pass
      if ($found) {
        if (password_verify($body["restore_member_pass"], $found["password"])) {
          //backup verified, restore site

          //set new secret key for older folks configs
          $newFolks = [];
          if (!isset($found["secret"])) {
            $found["secret"] = StringTools::randomString(12);
          }
          array_push($newFolks, $found);
          //dump files in folder
          $zip->extractTo("../content");

          //move to appropriate spots
          /*
                    rename(
                        "../content/settings/settings.json",
                        "../config/settings.json"
                    );
                    */

          //load up old config file
          $newConfig = json_decode(
            file_get_contents("../content/settings/settings.json"),
            true
          );
          //check for key, add if not there
          if (!isset($newConfig["global"]["externalAPI"])) {
            $newConfig["global"]["externalAPI"] = "false";
          }
          //write new config file
          DocTools::writeSettings("../config/settings.json", $newConfig);

          //rename("../content/settings/folks.json", "../config/folks.json");
          DocTools::writeSettings("../config/folks.json", $newFolks);

          rename("../content/settings/tags.json", "../config/tags.json");

          //images path for blog and user
          $blogImagePath = "../public/assets/images/blog";
          $userImagePath = "../public/assets/images/user";

          //check to see if image dirs are empty, if not chill
          if ($globs = glob($blogImagePath . "/*")) {
            //directory not empty, relax
          } else {
            rename("../content/public/assets/images/blog", $blogImagePath);
          }

          if ($globs = glob($userImagePath . "/*")) {
            //directory not empty, relax
          } else {
            rename("../content/public/assets/images/user", $userImagePath);
          }

          rename("../content/content/pages/", "../content/pages");

          //legacy check for old file structure
          if (is_file("../content/pages/index.md")) {
            if (!is_dir("../content/pages/start")) {
              //Directory does not exist, so lets create it.
              mkdir("../content/pages/start", 0755, true);
              //move start page to appropriate spot
              rename(
                "../content/pages/index.md",
                "../content/pages/start/index.md"
              );
            }
          } else {
            //chill
          }

          //clean up

          DocTools::deleteFolder("../content/settings");
          DocTools::deleteFolder("../content/public");
          DocTools::deleteFolder("../content/content");
          $result = [
            "type" => "requestGood",
            "message" => "Site Restored! Redirecting",
          ];
        } else {
          $result = [
            "type" => "requestLame",
            "message" => "Check that password, champ.",
          ];
        }
      } else {
        $result = [
          "type" => "requestLame",
          "message" => "No member found by that name, hoss",
        ];
      }

      $zip->close();
      $zipPath = "../content/" . $name;
      //trash zip when done
      unlink($zipPath);
    } else {
      $result = [
        "type" => "requestLame",
        "message" => "Could not open backup. RATS!",
      ];
    }
    return $result;
  }
}