<?php

declare(strict_types=1);

namespace frontend\modules\webcms\controllers;

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

class PlanController 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;
    }

    public function actionIndex(): string
    {
        $plans = Plan::find()
            ->orderBy(['plan_type' => SORT_ASC, 'price' => SORT_ASC])
            ->all();
        return $this->render('index', ['plans' => $plans]);
    }

    public function actionCreate(): Response|string
    {
        $model = new Plan();

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

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

    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', 'Plan updated successfully!');
            return $this->redirect(['plan/index']);
        }

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

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

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

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