<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Models\Lead;
use App\Models\Database;

class PublicFormController extends BaseController
{
    public function create(): void
    {
        $data = $this->request->body();

        $validation = $this->validate($data, function ($v) use ($data) {
            $v->required('first_name', 'Nombres');
            $v->required('last_name', 'Apellidos');
            $v->required('phone', 'Celular');
            $v->required('email', 'Correo');
            if (!empty($data['email'] ?? null)) {
                $v->email('email', 'Correo electrónico');
            }
        });

        if ($validation->fails()) {
            Response::error($validation->firstError(), 422);
            return;
        }

        try {
            $db = Database::connect();

            $stmt = $db->query("SELECT id FROM users WHERE role = 'super_admin' ORDER BY id ASC LIMIT 1");
            $admin = $stmt->fetch();
            $createdBy = $admin ? (int) $admin['id'] : 1;

            $stmtEvent = $db->query("SELECT id FROM events ORDER BY id DESC LIMIT 1");
            $event = $stmtEvent->fetch();
            $eventId = $event ? (int) $event['id'] : null;

            $leadData = [
                'first_name' => trim($data['first_name']),
                'last_name'  => trim($data['last_name']),
                'phone'      => trim($data['phone']),
                'email'      => trim($data['email']),
                'company'    => trim($data['company']),
                'position'   => !empty($data['position'] ?? null) ? trim($data['position']) : null,
                'source'     => 'qr',
                'status'     => 'nuevo',
                'event_id'   => $eventId,
                'created_by' => $createdBy,
            ];

            $leadModel = new Lead();
            $leadId = $leadModel->create($leadData);

            Response::created(['id' => $leadId], 'Formulario enviado correctamente');
        } catch (\Throwable $e) {
            Response::error('Error al procesar el formulario', 500);
        }
    }
}
