<?php

declare(strict_types=1);

namespace backend\modules\api\controllers;

use common\forms\LeadForm;
use common\services\LeadService;
use yii\filters\ContentNegotiator;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Response;

/**
 * API LeadController — POST /api/create-lead
 */
class LeadController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors(): array
    {
        return [
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => ['create' => ['POST']],
            ],
            'contentNegotiator' => [
                'class'   => ContentNegotiator::class,
                'formats' => ['application/json' => Response::FORMAT_JSON],
            ],
        ];
    }

    /**
     * POST /api/create-lead
     * Body: { name, phone, email?, source?, interest?, message? }
     */
    public function actionCreate(): array
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;

        $body = \Yii::$app->request->bodyParams;

        $form = new LeadForm();
        $form->setAttributes($body, false);

        if (!$form->validate()) {
            \Yii::$app->response->statusCode = 422;
            return [
                'status'  => 'error',
                'message' => 'Validation failed.',
                'errors'  => $form->errors,
            ];
        }

        try {
            $service = new LeadService();
            $lead = $service->createLead($form->getAttributes());

            return [
                'status'  => 'success',
                'message' => 'Lead created',
                'data'    => ['id' => $lead->id],
            ];
        } catch (\Throwable $e) {
            \Yii::error($e->getMessage(), __METHOD__);
            \Yii::$app->response->statusCode = 500;
            return [
                'status'  => 'error',
                'message' => 'Server error. Please try again.',
            ];
        }
    }
}
