<?php

declare(strict_types=1);

namespace backend\controllers;

use common\forms\LeadForm;
use common\models\Lead;
use common\services\LeadService;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;

/**
 * LeadController — full CRUD for leads + convert-to-customer action.
 */
class LeadController extends Controller
{
    private LeadService $service;

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

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

    public function actionIndex(): string
    {
        $query = Lead::find()->orderBy(['created_at' => SORT_DESC]);

        // Filter by status
        $status = \Yii::$app->request->get('status');
        if ($status) {
            $query->andWhere(['status' => $status]);
        }

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

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

    public function actionView(int $id): string
    {
        return $this->render('view', ['model' => $this->findModel($id)]);
    }

    public function actionCreate(): Response|string
    {
        $form = new LeadForm();

        if ($form->load(\Yii::$app->request->post(), 'LeadForm') && $form->validate()) {
            try {
                $lead = $this->service->createLead($form->getAttributes());
                \Yii::$app->session->setFlash('success', 'Lead created successfully.');
                return $this->redirect(['view', 'id' => $lead->id]);
            } catch (\Throwable $e) {
                \Yii::$app->session->setFlash('error', 'Error: ' . $e->getMessage());
            }
        }

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

    public function actionUpdate(int $id): Response|string
    {
        $model = $this->findModel($id);
        $form  = new LeadForm();
        $form->setAttributes($model->getAttributes(), false);

        if ($form->load(\Yii::$app->request->post(), 'LeadForm') && $form->validate()) {
            $model->setAttributes($form->getAttributes());
            if ($model->save()) {
                \Yii::$app->session->setFlash('success', 'Lead updated.');
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

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

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

    /**
     * Convert a lead to a customer.
     */
    public function actionConvert(int $id): Response
    {
        $lead = $this->findModel($id);

        if ($lead->status === Lead::STATUS_CONVERTED) {
            \Yii::$app->session->setFlash('warning', 'Lead already converted.');
            return $this->redirect(['view', 'id' => $id]);
        }

        try {
            $customer = $this->service->convertToCustomer($lead);
            \Yii::$app->session->setFlash('success', 'Lead converted to customer successfully.');
            return $this->redirect(['/customer/view', 'id' => $customer->id]);
        } catch (\Throwable $e) {
            \Yii::$app->session->setFlash('error', 'Conversion failed: ' . $e->getMessage());
            return $this->redirect(['view', 'id' => $id]);
        }
    }

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