<?php

declare(strict_types=1);

namespace frontend\controllers;

use common\models\Plan;
use common\models\SiteContent;
use common\models\Testimonial;
use common\services\LeadService;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Response;

/**
 * SiteController — public marketing website for SJ Nutrizione.
 */
class SiteController extends Controller
{
    public $layout = 'main';

    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only'  => ['logout'],
                'rules' => [
                    ['actions' => ['logout'], 'allow' => true, 'roles' => ['@']],
                ],
            ],
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => ['logout' => ['post'], 'lead' => ['get', 'post']],
            ],
        ];
    }

    public function actions(): array
    {
        return [
            'error' => ['class' => \yii\web\ErrorAction::class],
        ];
    }

    /**
     * Landing page — loads active plans for the preview section.
     */
    public function actionIndex(): string
    {
        SiteContent::preload();

        $plans = Plan::find()
            ->where(['is_active' => 1])
            ->orderBy(['sort_order' => SORT_ASC, 'id' => SORT_ASC])
            ->limit(6)
            ->all();

        $testimonials = Testimonial::getActive();

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

    /**
     * Plans & Pricing page.
     */
    public function actionPlans(): string
    {
        $plans = Plan::find()
            ->where(['is_active' => 1])
            ->orderBy(['sort_order' => SORT_ASC, 'plan_type' => SORT_ASC, 'id' => SORT_ASC])
            ->all();

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

    /**
     * Get Started / Lead capture page.
     */
    public function actionLead(): Response|string
    {
        $selectedPlan = Yii::$app->request->get('plan', '');

        if (Yii::$app->request->isPost) {
            $post  = Yii::$app->request->post();
            $name  = trim($post['name'] ?? '');
            $phone = trim($post['phone'] ?? '');
            $email = trim($post['email'] ?? '');
            $goal  = trim($post['goal'] ?? '');
            $notes = trim($post['notes'] ?? '');
            $planInterest = trim($post['plan_interest'] ?? '');

            if (empty($name) || empty($phone)) {
                Yii::$app->session->setFlash('danger', 'Please provide your name and phone number.');
                return $this->render('lead', ['selectedPlan' => $selectedPlan]);
            }

            // Combine goal + plan interest into notes for the lead record
            $fullNotes = '';
            if ($goal) {
                $fullNotes .= 'Goal: ' . $goal . '. ';
            }
            if ($planInterest) {
                $fullNotes .= 'Interested in: ' . $planInterest . '. ';
            }
            if ($notes) {
                $fullNotes .= $notes;
            }

            try {
                $service = new LeadService();
                $service->createLead([
                    'name'   => $name,
                    'phone'  => $phone,
                    'email'  => $email ?: null,
                    'source' => 'website',
                    'notes'  => $fullNotes ?: null,
                ]);

                Yii::$app->session->setFlash('success',
                    "Thank you, {$name}! We've received your request and will contact you within a few hours to schedule your free consultation."
                );
                return $this->redirect(['site/lead']);
            } catch (\Throwable $e) {
                Yii::$app->session->setFlash('danger', 'Something went wrong. Please try again or WhatsApp us directly.');
            }
        }

        return $this->render('lead', ['selectedPlan' => $selectedPlan]);
    }

    /**
     * Contact page — re-uses lead capture for simplicity.
     */
    public function actionContact(): Response|string
    {
        return $this->redirect(['site/lead']);
    }

    public function actionAbout(): string
    {
        SiteContent::preload();
        $testimonials = Testimonial::getActive();
        return $this->render('about', ['testimonials' => $testimonials]);
    }

    public function actionError(): string
    {
        $exception = Yii::$app->errorHandler->exception;
        $code      = $exception ? $exception->statusCode ?? 500 : 500;

        return $this->render('error', ['code' => $code, 'message' => $exception?->getMessage() ?? 'An error occurred.']);
    }

    public function actionLogout(): Response
    {
        Yii::$app->user->logout();
        return $this->goHome();
    }
}
