<?php

namespace kernel\app_modules\photo\controllers;

use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\app_modules\photo\models\form\CreatePhotoForm;
use kernel\app_modules\photo\models\Photo;
use kernel\app_modules\photo\service\PhotoService;
use kernel\EntityRelation;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\Request;

class PhotoController extends AdminController
{
    private PhotoService $photoService;
    protected function init(): void
    {
        parent::init();
        $this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/photo/views/";
        $this->photoService = new PhotoService();
    }

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

    #[NoReturn] public function actionAdd(): void
    {
        $photoForm = new CreatePhotoForm();
        $photoForm->load($_REQUEST);
        if ($photoForm->validate()){
            $photo = $this->photoService->create($photoForm);
            if ($photo){
                $this->redirect("/admin/photo/view/" . $photo->id);
            }
        }
        $this->redirect("/admin/photo/create");
    }

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

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

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

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

    #[NoReturn] public function actionSaveSettings(): void
    {
        $request = new Request();
        $entities = $request->post('entity');
        EntityRelation::configurationEntitiesByProperty($entities, 'photo');

        Flash::setMessage("success", "Настройка прошла успешно");
        $this->redirect("/admin/settings/photo", 302);
    }

}