<?php
namespace kernel\modules\user\controllers;


use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\modules\user\models\forms\CreateUserForm;
use kernel\modules\user\models\User;
use kernel\modules\user\service\UserService;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;

class UserController extends AdminController
{

    private UserService $userService;

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

    public function actionCreate(): void
    {
        $this->cgView->render("form.php");
    }

    #[NoReturn] public function actionAdd(): void
    {
        $userForm = new CreateUserForm();
        $userForm->load($_REQUEST);
        if ($userForm->validate()){
            $user = $this->userService->create($userForm);
            if ($user){
                $this->redirect("/admin/user/view/" . $user->id);
            }
        }
        $this->redirect("/admin/user/create");
    }

    /**
     * @throws \Exception
     */
    public function actionIndex($page_number = 1): void
    {
        $this->cgView->render("index.php", ['page_number' => $page_number]);
    }

    /**
     * @throws Exception
     */
    public function actionView($id): void
    {
        $user = User::find($id);

        if (!$user){
            throw new Exception(message: "The user not found");
        }
        $this->cgView->render("view.php", ['user' => $user]);
    }

    /**
     * @throws RuntimeError
     * @throws SyntaxError
     * @throws LoaderError
     * @throws Exception
     */
    public function actionUpdate($id): void
    {
        $model = User::find($id);
        if (!$model){
            throw new Exception(message: "The user not found");
        }

        $this->cgView->render("form.php", ['model' => $model]);
    }

    /**
     * @throws Exception
     */
    public function actionEdit($id): void
    {
        $user = User::find($id);
        if (!$user){
            throw new Exception(message: "The user not found");
        }
        $userForm = new CreateUserForm();
        $userService = new UserService();
        $userForm->load($_REQUEST);
        if ($userForm->validate()){
            $user = $userService->update($userForm, $user);
            if ($user){
                $this->redirect("/admin/user/view/" . $user->id);
            }
        }
        $this->redirect("/admin/user/update/" . $id);
    }

    #[NoReturn] public function actionDelete($id): void
    {
        User::find($id)->delete();
        $this->redirect("/admin/user/");
    }

}