<?php
include "../brain/data/Settings.inc.php";
use function _\find;
use ReallySimpleJWT\Token;

class Auth
{
  public function __construct()
  {
  }

  public static function sessionStatus()
  {
    if (isset($_SESSION["member"])) {
      return true;
    } else {
      return false;
    }
    //return $this->secret;
  }

  public static function status()
  {
    $result = [];
    if (Session::active()) {
      $result = [
        "message" => "Authorized",
        "type" => "apiUseAuthorized",
        "token" => Session::get("token"),
      ];
    } else {
      $result = [
        "message" => "Not Authorized",
        "type" => "apiUseNotAuthorized",
      ];
    }

    return $result;
  }

  public static function login($who)
  {
    //grab member list
    $folks = (new Settings())->getFolks();
    $found = find($folks, ["handle" => $who["handle"]]);

    if ($found) {
      //name is found, verify password
      if (password_verify($who["password"], $found["password"])) {
        $member = [
          "handle" => $found["handle"],
          "email" => $found["email"],
          "role" => $found["role"],
          "avatar" => $found["avi"],
        ];

        $token = Token::create(
          $found["id"],
          $found["secret"],
          time() + 3600,
          "localhost"
        ); //expires in an hour
        Session::start();
        Session::set("member", $member);
        Session::set("token", $token);

        $result = [
          "message" => "Welcome back",
          "type" => "requestGood",
        ];
      } else {
        $result = [
          "message" => "Check your password, sport",
          "type" => "requestLame",
        ];
      }
    } else {
      //if name is not found
      $result = [
        "message" => "Need to see some id, champ",
        "type" => "requestLame",
      ];
    }
    return $result;
  }

  public static function logout()
  {
    Session::kill();
    $result = [
      "message" => "Till next time, g.",
      "type" => "TASK_LOGOUT",
    ];
    return $result;
  }
}