<?php

namespace kernel\app_modules\view\controllers;

use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\app_modules\view\models\forms\CreateViewForm;
use kernel\app_modules\view\models\View;
use kernel\app_modules\view\services\ViewService;

class ViewController extends AdminController
{
    private ViewService $viewService;
    protected function init(): void
    {
        parent::init();
        $this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/view/views/";
        $this->viewService = new ViewService();
    }

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

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

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

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

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

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

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

    /**
     * @throws Exception
     */
    public function actionEdit($id): void
    {
        $view = View::find($id);
        if (!$view){
            throw new Exception(message: "The view not found");
        }
        $viewForm = new CreateViewForm();
        $viewService = new ViewService();
        $viewForm->load($_REQUEST);
        if ($viewForm->validate()) {
            $view = $viewService->update($viewForm, $view);
            if ($view) {
                $this->redirect("/admin/view/view/" . $view->id);
            }
        }
        $this->redirect("/admin/view/update/" . $id);
    }

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