<?php

namespace kernel\modules\post\controllers;


use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\modules\post\models\forms\CreatePostForm;
use kernel\modules\post\models\Post;
use kernel\modules\post\service\PostService;

class PostController extends AdminController
{
    private PostService $postService;

    protected function init(): void
    {
        parent::init();
        $this->cgView->viewPath = KERNEL_MODULES_DIR . "/post/views/";
        $this->postService = new PostService();
    }
    public function actionCreate(): void
    {
        $this->cgView->render("form.php");
    }

    #[NoReturn] public function actionAdd(): void
    {
        $postForm = new CreatePostForm();
        $postForm->load($_REQUEST);
        if ($postForm->validate()) {
            $post = $this->postService->create($postForm);
            if ($post) {
                $this->redirect("/admin/post/" . $post->id);
            }
        }
        $this->redirect("/admin/post/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
    {
        $content = Post::find($id);

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

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

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

    /**
     * @throws Exception
     */
    public function actionEdit($id): void
    {
        $post = Post::find($id);
        if (!$post){
            throw new Exception(message: "The post not found");
        }
        $postForm = new CreatePostForm();
        $postService = new PostService();
        $postForm->load($_REQUEST);
        if ($postForm->validate()) {
            $post = $postService->update($postForm, $post);
            if ($post) {
                $this->redirect("/admin/post/" . $post->id);
            }
        }
        $this->redirect("/admin/post/update/" . $id);
    }

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