<?php

namespace kernel\modules\notification\controllers;

use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\modules\notification\models\forms\CreateNotificationForm;
use kernel\modules\notification\models\Notification;
use kernel\modules\notification\service\NotificationService;
use kernel\modules\option\models\forms\CreateOptionForm;

class NotificationController extends AdminController
{

    private NotificationService  $optionService;

    public function init(): void
    {
        parent::init();
        $this->cgView->viewPath = KERNEL_MODULES_DIR . '/notification/views/';
        $this->optionService = new NotificationService();
    }

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

    #[NoReturn] public function actionAdd(): void
    {
        $optionForm = new CreateNotificationForm();
        $optionForm->load($_REQUEST);
        if ($optionForm->validate()) {
            $option = $this->optionService->create($optionForm);
            if ($option) {
                Flash::setMessage("success", "notification успешно создана.");
                $this->redirect('/admin/notification');
            }
        }
        Flash::setMessage("error", $optionForm->getErrorsStr());
        $this->redirect('/admin/notification/create');
    }

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

    /**
     * @throws \Exception
     */
    public function actionView(int $id): void
    {
        $option = Notification::find($id);

        if (!$option) {
            throw new \Exception('notification not found');
        }
        $this->cgView->render("view.php", ['option' => $option]);
    }

    /**
     * @throws \Exception
     */
    public function actionUpdate(int $id): void
    {
        $model = Notification::find($id);

        if (!$model) {
            throw new \Exception('notification not found');
        }

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

    /**
     * @throws \Exception
     */
    public function actionEdit(int $id): void
    {
        $option = Notification::find($id);
        if (!$option) {
            throw new \Exception('Option not found');
        }
        $optionForm = new CreateOptionForm();
        $optionForm->load($_REQUEST);
        if ($optionForm->validate()) {
            $option = $this->optionService->update($optionForm, $option);
            if ($option) {
                $this->redirect('/admin/notification/view/' . $option->id);
            }
        }

        $this->redirect('/admin/notification/update/' . $id);
    }

    #[NoReturn] public function actionDelete(int $id): void
    {
        Notification::find($id)->delete();
        Flash::setMessage("success", "notification успешно удалена.");
        $this->redirect('/admin/notification');
    }

}