<?php

declare(strict_types=1);

namespace backend\controllers;

use common\models\Customer;
use common\models\DietPlan;
use common\services\DietPlanService;
use common\services\PdfService;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;

/**
 * DietPlanController — build, copy, and manage diet plans.
 */
class DietPlanController extends Controller
{
    private DietPlanService $service;

    public function init(): void
    {
        parent::init();
        $this->service = new DietPlanService();
    }

    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [['allow' => true, 'roles' => ['@']]],
            ],
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => ['delete' => ['POST'], 'copy' => ['POST']],
            ],
        ];
    }

    public function actionIndex(): string
    {
        $query = DietPlan::find()
            ->with(['customer'])
            ->where(['is_template' => 0])
            ->orderBy(['created_at' => SORT_DESC]);

        $dataProvider = new ActiveDataProvider([
            'query'      => $query,
            'pagination' => ['pageSize' => 20],
        ]);

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

    public function actionView(int $id): string
    {
        $model = $this->findModel($id);
        $model->populateRelation('meals', $model->meals);

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

    public function actionCreate(): Response|string
    {
        if (\Yii::$app->request->isPost) {
            $post      = \Yii::$app->request->post();
            $planData  = $post['DietPlan'] ?? [];
            $mealsData = $post['meals'] ?? [];

            try {
                $plan = $this->service->createPlan($planData, $mealsData);
                \Yii::$app->session->setFlash('success', 'Diet plan created.');
                return $this->redirect(['view', 'id' => $plan->id]);
            } catch (\Throwable $e) {
                \Yii::$app->session->setFlash('error', $e->getMessage());
            }
        }

        $customers = Customer::find()->where(['is_active' => 1])->orderBy('name')->all();
        $templates = DietPlan::find()->where(['is_template' => 1, 'status' => DietPlan::STATUS_ACTIVE])->all();

        return $this->render('create', [
            'customers' => $customers,
            'templates' => $templates,
        ]);
    }

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

        if (\Yii::$app->request->isPost) {
            $post      = \Yii::$app->request->post();
            $planData  = $post['DietPlan'] ?? [];
            $mealsData = $post['meals'] ?? [];

            try {
                $this->service->updatePlan($model, $planData, $mealsData);
                \Yii::$app->session->setFlash('success', 'Diet plan updated.');
                return $this->redirect(['view', 'id' => $model->id]);
            } catch (\Throwable $e) {
                \Yii::$app->session->setFlash('error', $e->getMessage());
            }
        }

        $model->populateRelation('meals', $model->meals);
        $customers = Customer::find()->where(['is_active' => 1])->orderBy('name')->all();

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

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

    /**
     * Copy an existing plan to the same or a different customer.
     */
    public function actionCopy(int $id): Response
    {
        $source     = $this->findModel($id);
        $customerId = (int)\Yii::$app->request->post('customer_id', $source->customer_id);
        $newTitle   = 'Copy of ' . $source->title;

        try {
            $copy = $this->service->copyPlan($source, $customerId, $newTitle);
            \Yii::$app->session->setFlash('success', 'Plan copied successfully.');
            return $this->redirect(['update', 'id' => $copy->id]);
        } catch (\Throwable $e) {
            \Yii::$app->session->setFlash('error', 'Copy failed: ' . $e->getMessage());
            return $this->redirect(['view', 'id' => $id]);
        }
    }

    /**
     * Download Diet Plan as PDF.
     */
    public function actionPdf(int $id): void
    {
        $plan = $this->findModel($id);
        $plan->populateRelation('customer', $plan->customer);
        $plan->populateRelation('meals', $plan->meals);

        $pdf = new PdfService();
        $pdf->generateDietPlanPdf($plan);
        exit;
    }

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