<?php
namespace Site\Controller;

use Site\Controller\Mods;
use Site\Lib\Auth;
use Site\Lib\Template;

class User {
  use Mods;

  public function login(array $params): void {
    try {
      $auth = new Auth;
      $user = $auth->getLoggedInUser();
      if ($user) {
        header('Location: /');
        exit();
      }

      $doLogin = count($_POST) > 0;
      $error = '';

      if ($doLogin) {
        $a = [];
        if (count($_POST) === 2) {
          $i = 0;
          foreach ($_POST as $p) {
            $a[(int)$i] = $p;
            $i++;
          }
        }
        $auth = new Auth($a[0]);
        $res = $auth->isUserExist($a[0]);
        kys($res);
        if (!$res->isSuccess) {
          $error = $res->message;
        } else {
          $auth->setToken($a[0], $a[1]);
          header('Location: /');
          exit();
        }
      }
      $tmpl = new Template('/');
      $pagetit = 'サインイン';
      $description = 'サイトにサインイン';

      $tmpl->assign('pagetit', $pagetit);
      $tmpl->assign('curPage', 'about');
      $tmpl->assign('custCss', false);
      $tmpl->assign('menu', $this->getMenu());
      $tmpl->assign('description', $description);
      $tmpl->assign('error', $error);

      $tmpl->render('login');
    } catch (\Exception $e) {
      throw new \Exception($e->getMessage());
    }
  }

  public function logout(array $params): void {
    try {
      $auth = new Auth();
      $user = $auth->getLoggedInUser();
      if (!$user) {
        header('Location: /');
        exit();
      }

      $auth->logout();
      header('Location: /');
      exit();
    } catch (\Exception $e) {
      throw new \Exception($e->getMessage());
    }
  }
}