<?php

namespace app\controllers;


use app\helpers\Debug;
use app\models\forms\CreatePostForm;
use app\models\Post;
use app\models\User;
use app\services\PostService;
use app\services\UserService;
use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\Controller;

class PostController extends Controller
{
    protected function init(): void
    {
        $this->cgView->viewPath = ROOT_DIR . "/views/admin/";
        $this->cgView->layout = "layouts/main.php";
    }
    public function actionCreate(): void
    {
        $this->cgView->render("post/form.php");
    }

    #[NoReturn] public function actionAdd(): void
    {
        $postForm = new CreatePostForm();
        $postService = new PostService();
        $postForm->load($_REQUEST);
//        Debug::dd($_REQUEST);
        if(UserService::check($_REQUEST['user_id'])) {
//            Debug::dd(123);
            if ($postForm->validate()) {

//                Debug::dd($postForm);
                $post = $postService->create($postForm);
                if ($post) {
                    $this->redirect("/admin/post/" . $post->id);
                }
            }
        }
        $this->redirect("/admin/post/create");
    }

    /**
     * @throws Exception
     */

    public function actionIndex(): void
    {
        $contents = Post::all();

        $this->cgView->render("post/index.php", ['contents' => $contents]);
    }

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

        if (!$content){
            throw new Exception(message: "The post not found");
        }
        $this->cgView->render("post/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("post/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((new UserService)->check($_REQUEST['user_id'])) {
            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/");
    }
}