<?php
use function _\find;
use ReallySimpleJWT\Token;

class Session
{
  private static $file = "../content/.session";
  private static $data = [
    "member" => "",
    "token" => "",
    "form_token" => "",
  ];
  public static function start()
  {
    if (!is_file(self::$file)) {
      file_put_contents(self::$file, json_encode(self::$data));
    } else {
      ($new = fopen(self::$file, "w")) or die("Unable to open file!");
      fwrite($new, json_encode(self::$data));
      fclose($new);
    }
  }

  public static function active()
  {
    if (!is_file(self::$file)) {
      return false;
    } else {
      $data = json_decode(file_get_contents(self::$file), true);
      if ($data["member"] != null) {
        $secret = (new Settings())->getFolks("secret");
        if ($secret == null) {
          return false;
        } else {
          if (
            Token::validate($data["token"], $secret) &&
            Token::validateExpiration($data["token"], $secret)
          ) {
            return true;
          } else {
            return false;
          }
        }
      } else {
        return false;
      }
    }
  }

  public static function verifyToken($token)
  {
    $data = json_decode(file_get_contents(self::$file), true);
    if ($data["member"] != null) {
      $secret = (new Settings())->getFolks("secret");
      if (
        Token::validate($token, $secret) &&
        Token::validateExpiration($token, $secret)
      ) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  public static function set($key, $value)
  {
    $data = json_decode(file_get_contents(self::$file), true);
    $data[$key] = $value;
    ($fresh = fopen(self::$file, "w")) or die("Unable to open file!");
    fwrite($fresh, json_encode($data));
    fclose($fresh);
  }

  public static function get($key)
  {
    $data = json_decode(file_get_contents(self::$file), true);

    return $data[$key];
  }

  public static function kill()
  {
    ($fresh = fopen(self::$file, "w")) or die("Unable to open file!");
    fwrite($fresh, json_encode(self::$data));
    fclose($fresh);
  }
}
