<?php

declare(strict_types=1);

namespace backend\controllers;

use common\models\Plan;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;

/**
 * PlanController — manage nutrition subscription and one-time plans.
 */
class PlanController extends Controller
{
    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [['allow' => true, 'roles' => ['@']]],
            ],
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => ['delete' => ['POST']],
            ],
        ];
    }

    public function actionIndex(): string
    {
        $dataProvider = new ActiveDataProvider([
            'query'      => Plan::find()->orderBy(['created_at' => SORT_DESC]),
            'pagination' => ['pageSize' => 25],
        ]);

        return $this->render('index', ['dataProvider' => $dataProvider]);
    }

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

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

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

    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.');
            return $this->redirect(['index']);
        }

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

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

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