<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/database.php';

header('Content-Type: application/json');

if (!is_logged_in() || !user_can('module.crm')) {
    echo json_encode([]);
    exit;
}

$pdo = db();

$startParam = isset($_GET['start']) ? substr($_GET['start'], 0, 10) : null;
$endParam = isset($_GET['end']) ? substr($_GET['end'], 0, 10) : null;
$filterUserId = isset($_GET['user_id']) && $_GET['user_id'] !== '' ? (int)$_GET['user_id'] : null;
$filterArea = isset($_GET['area']) && $_GET['area'] !== '' ? trim($_GET['area']) : null;

$sql = "
    SELECT 
        e.*, 
        u.name AS user_name, 
        u.role AS user_role,
        o.customer_id
    FROM crm_events e
    INNER JOIN users u ON e.owner_user_id = u.id
    LEFT JOIN crm_opportunities o ON e.opportunity_id = o.id
    WHERE 1=1
";

$params = [];

if ($startParam && $endParam) {
    $sql .= " AND e.start_date >= ? AND e.end_date <= ?";
    $params[] = $startParam . ' 00:00:00';
    $params[] = $endParam . ' 23:59:59';
}

if ($filterUserId) {
    $sql .= " AND e.owner_user_id = ?";
    $params[] = $filterUserId;
}

if ($filterArea) {
    $sql .= " AND u.role = ?";
    $params[] = $filterArea;
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$events = $stmt->fetchAll(PDO::FETCH_ASSOC);

$formattedEvents = [];

// Paleta de colores Gemini-Style homologada
$colors = [
    'accion'      => ['bg' => '#0ea5e9', 'border' => '#0284c7'], // Celeste (Acciones comerciales)
    'cierre'      => ['bg' => '#8b5cf6', 'border' => '#7c3aed'], // Morado (Hitos de cierre)
    'vencimiento' => ['bg' => '#f59e0b', 'border' => '#db2777'], // Naranja (Cobranzas)
    'pago'        => ['bg' => '#10b981', 'border' => '#059669'], // Verde (Pagos)
    'libre'       => ['bg' => '#ec4899', 'border' => '#db2777']  // 🚀 NUEVO: Evento Libre (Magenta)
];

foreach ($events as $activity) {
    $type = $activity['event_type'];
    $cfg = $colors[$type] ?? ['bg' => '#64748b', 'border' => '#475569'];

    $formattedEvents[] = [
        'id' => 'evt_' . $activity['id'],
        'title' => $activity['title'],
        'start' => $activity['start_date'],
        'end' => $activity['end_date'],
        'allDay' => (int)$activity['is_all_day'] === 1,
        'backgroundColor' => $cfg['bg'],
        'borderColor' => $cfg['border'],
        'extendedProps' => [
            'opportunity_id' => $activity['opportunity_id'] > 0 ? $activity['opportunity_id'] : null,
            'event_type' => $type
        ]
    ];
}

echo json_encode($formattedEvents);
exit;