<?php

namespace kernel\app_modules\tgbot\controllers;

use app\modules\tgbot\models\forms\CreateTgBotForm;
use app\modules\tgbot\models\Tgbot;
use app\modules\tgbot\services\TgBotService;
use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\helpers\Debug;
use kernel\modules\user\models\forms\CreateUserForm;
use kernel\modules\user\service\UserService;
use kernel\services\TokenService;

class TgbotController extends AdminController
{
    protected TgBotService $botService;

    protected function init(): void
    {
        parent::init();
        $this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/tgbot/views/tgbot/";
        $this->botService = new TgBotService();
    }

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

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

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

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

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

    /**
     * @throws Exception
     */
    public function actionEdit($id): void
    {
        $tg = Tgbot::find($id);
        if (!$tg) {
            throw new Exception(message: "The tag not found");
        }
        $tgForm = new CreateTgBotForm();
        $tgService = new TgBotService();
        $tgForm->load($_REQUEST);
        if ($tgForm->validate()) {
            $tg = $tgService->update($tgForm, $tg);
            if ($tg) {
                $this->redirect("/admin/tg-bot/view/" . $tg->id);
            }
        }
        $this->redirect("/admin/tg-bot/update/" . $id);
    }

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

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

    /**
     * @throws Exception
     */
    #[NoReturn] public function actionDelete(int $id): void
    {
        $post = Tgbot::find($id)->first();
        if (!$post){
            throw new Exception(message: "The tg client not found");
        }

        $post->delete();
        $this->redirect("/admin/tg-bot/");
    }

}