<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\LeadProduct;
use App\Models\Database;

class DashboardService
{
    private LeadProduct $leadProductModel;

    public function __construct()
    {
        $this->leadProductModel = new LeadProduct();
    }

    public function getEventKPIs(int $eventId, ?int $sellerId = null): array
    {
        $db = Database::connect();
        $where = 'event_id = :event_id';
        $params = [':event_id' => $eventId];

        if ($sellerId !== null) {
            $where .= ' AND created_by = :seller_id';
            $params[':seller_id'] = $sellerId;
        }

        $stmt = $db->prepare(
            "SELECT
               SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as hoy,
               SUM(CASE WHEN status IN ('calificado','propuesta','negociacion') THEN 1 ELSE 0 END) as calientes,
               SUM(CASE WHEN status IN ('nuevo','contactado') THEN 1 ELSE 0 END) as pendientes,
               SUM(CASE WHEN status = 'ganado' THEN 1 ELSE 0 END) as ganados,
               SUM(CASE WHEN status = 'perdido' THEN 1 ELSE 0 END) as perdidos
             FROM leads WHERE {$where}"
        );
        $stmt->execute($params);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        $stmt2 = $db->prepare(
            "SELECT status, COUNT(*) as cnt FROM leads WHERE {$where} GROUP BY status"
        );
        $stmt2->execute($params);
        $pipelineRows = $stmt2->fetchAll(\PDO::FETCH_ASSOC);

        $pipeline = array_fill_keys(['nuevo','contactado','calificado','propuesta','negociacion','ganado','perdido'], 0);
        foreach ($pipelineRows as $r) {
            if (isset($pipeline[$r['status']])) {
                $pipeline[$r['status']] = (int) $r['cnt'];
            }
        }

        return [
            'leads_captados_hoy' => (int) ($row['hoy'] ?? 0),
            'leads_calientes' => (int) ($row['calientes'] ?? 0),
            'leads_pendientes' => (int) ($row['pendientes'] ?? 0),
            'leads_ganados' => (int) ($row['ganados'] ?? 0),
            'leads_perdidos' => (int) ($row['perdidos'] ?? 0),
            'pipeline' => $pipeline,
        ];
    }

    public function getKPIs(int $userId, string $role, int $eventId, ?int $filterEventId = null): array
    {
        $db = Database::connect();
        $where = [];
        $params = [];

        if ($role !== 'super_admin') {
            $where[] = 'event_id = :event_id';
            $params[':event_id'] = $eventId;
            $where[] = 'created_by = :user_id';
            $params[':user_id'] = $userId;
        } elseif ($filterEventId !== null) {
            $where[] = 'event_id = :event_id';
            $params[':event_id'] = $filterEventId;
        }

        $baseWhere = !empty($where) ? implode(' AND ', $where) : '1=1';

        $productosTop = $this->leadProductModel->getTopProducts(5);

        $stmt = $db->prepare(
            "SELECT
               SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as hoy,
               SUM(CASE WHEN status IN ('calificado','propuesta','negociacion') THEN 1 ELSE 0 END) as calientes,
               SUM(CASE WHEN status IN ('nuevo','contactado') THEN 1 ELSE 0 END) as pendientes,
               SUM(CASE WHEN status = 'ganado' THEN 1 ELSE 0 END) as ganados,
               SUM(CASE WHEN status = 'perdido' THEN 1 ELSE 0 END) as perdidos
             FROM leads WHERE {$baseWhere}"
        );
        $stmt->execute($params);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        $stmt2 = $db->prepare(
            "SELECT status, COUNT(*) as cnt FROM leads WHERE {$baseWhere} GROUP BY status"
        );
        $stmt2->execute($params);
        $pipelineRows = $stmt2->fetchAll(\PDO::FETCH_ASSOC);

        $pipeline = array_fill_keys(['nuevo','contactado','calificado','propuesta','negociacion','ganado','perdido'], 0);
        foreach ($pipelineRows as $r) {
            if (isset($pipeline[$r['status']])) {
                $pipeline[$r['status']] = (int) $r['cnt'];
            }
        }

        return [
            'leads_captados_hoy' => (int) ($row['hoy'] ?? 0),
            'leads_calientes' => (int) ($row['calientes'] ?? 0),
            'leads_pendientes' => (int) ($row['pendientes'] ?? 0),
            'leads_ganados' => (int) ($row['ganados'] ?? 0),
            'leads_perdidos' => (int) ($row['perdidos'] ?? 0),
            'pipeline' => $pipeline,
            'productos_top' => $productosTop,
        ];
    }
}
