<?php

namespace kernel\app_modules\{slug}\controllers;

use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\app_modules\{slug}\models\forms\Create{model}Form;
use kernel\app_modules\{slug}\models\{model};
use kernel\app_modules\{slug}\services\{model}Service;

class {model}Controller extends AdminController
{
    private {model}Service ${slug}Service;
    protected function init(): void
    {
        parent::init();
        $this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/{slug}/views/";
        $this->{slug}Service = new {model}Service();
    }

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

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

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

    /**
     * @throws Exception
     */
    public function actionView($id): void
    {
        ${slug} = {model}::find($id);

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

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

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

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

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