<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\EventService;
use App\Services\DashboardService;
use App\Middlewares\AuditMiddleware;

class EventController extends BaseController
{
    private EventService $eventService;

    public function __construct($request)
    {
        parent::__construct($request);
        $this->eventService = new EventService();
    }

    public function index(): void
    {
        $filters = [
            'search' => $this->request->query('search'),
            'status' => $this->request->query('status'),
            'sort_by' => $this->request->query('sort_by', 'created_at'),
            'sort_order' => $this->request->query('sort_order', 'desc'),
        ];

        $page = (int) ($this->request->query('page', 1));
        $perPage = (int) ($this->request->query('per_page', 15));

        $result = $this->eventService->getEvents($filters, $page, $perPage);

        Response::paginated(
            $result['items'],
            $result['total'],
            $result['page'],
            $result['per_page'],
            'Eventos consultados correctamente'
        );
    }

    public function show(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $event = $this->eventService->getEvent($id);
            Response::success($event, 'Evento consultado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function dashboard(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $sellerId = $this->request->query('seller_id');
            if ($sellerId !== null) {
                $sellerId = (int) $sellerId;
            }

            $event = $this->eventService->getEvent($id);
            $dashboardService = new DashboardService();
            $kpis = $dashboardService->getEventKPIs($id, $sellerId);

            $leadModel = new \App\Models\Lead();
            $leadParams = [];
            if ($sellerId !== null) {
                $leadParams['created_by'] = $sellerId;
            }
            $recentLeads = $leadModel->findByEvent($id, $leadParams, 1, 10);

            $eventUserModel = new \App\Models\EventUser();
            $sellers = $eventUserModel->getEventUsers($id);

            Response::success([
                'event' => $event,
                'kpis' => $kpis,
                'recent_leads' => $recentLeads['items'] ?? [],
                'sellers' => $sellers,
            ], 'Dashboard del evento');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function store(): void
    {
        $data = $this->request->body();

        $validation = $this->validate($data, function ($v) {
            $v->required('name', 'Nombre');
            if (isset($data['start_date'])) {
                $v->date('start_date', 'Fecha de inicio');
            }
            if (isset($data['end_date'])) {
                $v->date('end_date', 'Fecha de fin');
            }
        });

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

        try {
            $event = $this->eventService->createEvent($data);
            AuditMiddleware::log($this->getAuthUserId(), 'create', 'event', isset($event['id']) ? (int) $event['id'] : null);
            Response::created($event, 'Evento creado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function update(): void
    {
        $id = (int) $this->getRouteParam('id');
        $data = $this->request->body();

        try {
            $event = $this->eventService->updateEvent($id, $data);
            Response::success($event, 'Evento actualizado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function toggleStatus(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $event = $this->eventService->toggleStatus($id);
            $statusLabel = $event['status'] === 'active' ? 'activado' : 'desactivado';
            Response::success($event, "Evento {$statusLabel} correctamente");
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function myEvents(): void
    {
        $events = $this->eventService->getUserEvents($this->getAuthUserId());
        Response::success($events, 'Eventos del usuario consultados correctamente');
    }

    public function select(): void
    {
        $eventId = (int) $this->getRouteParam('id');

        try {
            $event = $this->eventService->selectEvent($this->getAuthUserId(), $eventId);
            Response::success($event, 'Evento seleccionado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function deselect(): void
    {
        $this->eventService->deselectEvent($this->getAuthUserId());
        Response::success(null, 'Evento deseleccionado');
    }

    public function destroy(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $this->eventService->deleteEvent($id);
            Response::success(null, 'Evento eliminado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }
}
