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


use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\EntityRelation;
use kernel\FileUpload;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\modules\user\models\forms\CreateUserForm;
use kernel\modules\user\models\User;
use kernel\modules\user\service\UserService;
use kernel\Request;
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 (isset($_FILES['user_photo']) && $_FILES['user_photo']['error'] === UPLOAD_ERR_OK) {
            $file = new FileUpload($_FILES['user_photo'], ['jpg', 'jpeg', 'png']);
            $file->upload();
            $userForm->setItem('user_photo', $file->getUploadFile());
        }

        if ($userForm->validate()){
            $user = $this->userService->create($userForm);

            $entityRelation = new EntityRelation();
            $entityRelation->saveEntityRelation(entity: "user", model: $user, request: new Request());

            if ($user){
                $this->redirect("/admin/user/view/" . $user->id);
            }
        }
        Flash::setMessage("error", $userForm->getErrorsStr());
        $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 (isset($_FILES['user_photo']) && $_FILES['user_photo']['error'] === UPLOAD_ERR_OK) {
            $file = new FileUpload($_FILES['user_photo'], ['jpg', 'jpeg', 'png']);
            $file->upload();
            $userForm->setItem('user_photo', $file->getUploadFile());
        }

        if ($userForm->validateForUpdate()){
            $user = $userService->update($userForm, $user);

            $entityRelation = new EntityRelation();
            $entityRelation->saveEntityRelation(entity: "user", model: $user, request: new Request());

            if ($user){
                $this->redirect("/admin/user/view/" . $user->id);
            }
        }
        $this->redirect("/admin/user/update/" . $id);
    }

    /**
     * @throws Exception
     */
    #[NoReturn] public function actionDelete($id): void
    {
        $user = User::find($id)->first();
        if (!$user){
            throw new Exception(message: "The user not found");
        }

        $entityRelation = new EntityRelation();
        $entityRelation->deleteEntityRelation(entity: "user", model: $user);

        $user->delete();
        $this->redirect("/admin/user/");
    }

    public function actionProfile(): void
    {
        $user = UserService::getAuthUser();
        if (!$user){
            throw new Exception(message: "The user not found");
        }
        $this->cgView->render("view_profile.php", ['user' => $user]);
    }

    public function actionProfileUpdate(): void
    {
        $model = UserService::getAuthUser();
        if (!$model){
            throw new Exception(message: "The user not found");
        }

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

    public function actionProfileEdit(): void
    {
        $user = UserService::getAuthUser();
        if (!$user){
            throw new Exception(message: "The user not found");
        }

        $userForm = new CreateUserForm();
        $userService = new UserService();
        $userForm->load($_REQUEST);

        if (isset($_FILES['user_photo']) && $_FILES['user_photo']['error'] === UPLOAD_ERR_OK) {
            $file = new FileUpload($_FILES['user_photo'], ['jpg', 'jpeg', 'png']);
            $file->upload();
            $userForm->setItem('user_photo', $file->getUploadFile());
        }

        if ($userForm->validateForUpdate()){
            $user = $userService->update($userForm, $user);

            $entityRelation = new EntityRelation();
            $entityRelation->saveEntityRelation(entity: "user", model: $user, request: new Request());

            if ($user){
                $this->redirect("/admin/user/profile");
            }
        }
        $this->redirect("/admin/user/profile/update");
    }

}