<?php

namespace kernel\app_modules\tag\controllers;

use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\app_modules\tag\models\forms\CreateTagForm;
use kernel\app_modules\tag\models\Tag;
use kernel\app_modules\tag\services\TagService;
use kernel\helpers\Debug;
use kernel\modules\menu\service\MenuService;

class TagController extends AdminController
{
    private TagService $tagService;
    protected function init(): void
    {
        parent::init();
        $this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/tag/views/";
        $this->tagService = new TagService();
    }

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

    #[NoReturn] public function actionAdd(): void
    {
        $tagForm = new CreateTagForm();
        $tagForm->load($_REQUEST);
        if ($tagForm->validate()){
            $tag = $this->tagService->create($tagForm);
            if ($tag){
                $this->redirect("/admin/tag/" . $tag->id);
            }
        }
        $this->redirect("/admin/tag/create");
    }

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

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

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

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

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

    /**
     * @throws Exception
     */
    public function actionEdit($id): void
    {
        $tag = Tag::find($id);
        if (!$tag){
            throw new Exception(message: "The tag not found");
        }
        $tagForm = new CreateTagForm();
        $tagService = new TagService();
        $tagForm->load($_REQUEST);
        if ($tagForm->validate()) {
            $tag = $tagService->update($tagForm, $tag);
            if ($tag) {
                $this->redirect("/admin/tag/" . $tag->id);
            }
        }
        $this->redirect("/admin/tag/update/" . $id);
    }

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

    public function actionSettings(): void
    {
        echo "tag settings";
    }

}