<?php

declare(strict_types=1);

namespace frontend\modules\webcms\controllers;

use common\models\Testimonial;
use frontend\modules\webcms\Module;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class TestimonialController extends Controller
{
    public $layout = '@webcms/views/layouts/main';

    public function beforeAction($action): bool
    {
        if (!parent::beforeAction($action)) {
            return false;
        }
        if (!Module::isLoggedIn()) {
            $this->redirect(['default/login'])->send();
            return false;
        }
        return true;
    }

    /** List all testimonials */
    public function actionIndex(): string
    {
        $testimonials = Testimonial::find()
            ->orderBy(['sort_order' => SORT_ASC, 'id' => SORT_ASC])
            ->all();
        return $this->render('index', ['testimonials' => $testimonials]);
    }

    /** Create */
    public function actionCreate(): Response|string
    {
        $model = new Testimonial();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', 'Testimonial added!');
            return $this->redirect(['testimonial/index']);
        }

        return $this->render('_form', ['model' => $model, 'isNew' => true]);
    }

    /** Update */
    public function actionUpdate(int $id): Response|string
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', 'Testimonial updated!');
            return $this->redirect(['testimonial/index']);
        }

        return $this->render('_form', ['model' => $model, 'isNew' => false]);
    }

    /** Toggle active/inactive */
    public function actionToggle(int $id): Response
    {
        $model = $this->findModel($id);
        $model->is_active = $model->is_active ? 0 : 1;
        $model->save(false);
        return $this->redirect(['testimonial/index']);
    }

    /** Delete */
    public function actionDelete(int $id): Response
    {
        $this->findModel($id)->delete();
        Yii::$app->session->setFlash('success', 'Testimonial deleted.');
        return $this->redirect(['testimonial/index']);
    }

    private function findModel(int $id): Testimonial
    {
        $model = Testimonial::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException('Testimonial not found.');
        }
        return $model;
    }
}
