<?php

namespace kernel\modules\secure\controllers;

use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\modules\secure\models\forms\LoginForm;
use kernel\modules\secure\models\forms\RegisterForm;
use kernel\modules\user\service\UserService;

class SecureController extends AdminController
{
    protected UserService $userService;

    protected function init(): void
    {
        parent::init();
        $this->cgView->viewPath = KERNEL_MODULES_DIR. "/secure/views/";
        $this->cgView->layout = "/login.php";
        $this->userService = new UserService();
    }

    public function actionLogin(): void
    {
        $this->cgView->render('login.php');
    }

    #[NoReturn] public function actionAuth(): void
    {
        $loginForm = new LoginForm();
        $loginForm->load($_REQUEST);

        if(filter_var($loginForm->getItem("username"), FILTER_VALIDATE_EMAIL)) {
            $field = "email";
        }
        else {
            $field = "username";
        }

        $user = $this->userService->getByField($field, $loginForm->getItem("username"));
        if (!$user){
            Flash::setMessage("error", "User not found.");
            $this->redirect("/admin/login", code: 302);
        }

        if (password_verify($loginForm->getItem("password"), $user->password_hash)) {
            setcookie('user_id', $user->id, time()+60*60*24, '/', $_SERVER['SERVER_NAME'], false);
            $this->redirect("/admin", code: 302);
        } else {
            Flash::setMessage("error", "Username or password incorrect.");
            $this->redirect("/admin/login", code: 302);
        }
    }

    #[NoReturn] public function actionLogout(): void
    {
        unset($_COOKIE['user_id']);
        setcookie('user_id', "", -1, '/', ".".$_SERVER['SERVER_NAME'], false);
        $this->redirect("/", code: 302);
    }

    public function actionRegister()
    {
        $this->cgView->render('register.php');
    }

    public function actionRegistration(): void
    {
        $regForm = new RegisterForm();
        $regForm->load($_REQUEST);

        if ($this->userService->getByField('username', $regForm->getItem("username"))) {
            Flash::setMessage("error", "Username already exists.");
            $this->redirect("/admin/register", code: 302);
        }

        if ($this->userService->getByField('email', $regForm->getItem("email"))) {
            Flash::setMessage("error", "Email already exists.");
            $this->redirect("/admin/register", code: 302);
        }

        $user = $this->userService->create($regForm);
        if ($user){
            setcookie('user_id', $user->id, time()+60*60*24, '/', $_SERVER['SERVER_NAME'], false);
            $this->redirect("/admin", code: 302);
        }
    }

}