<?php
// Endpoint: Obtener estadísticas de un lead (reuniones, llamadas, emails, tareas)
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__)));
}
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }

if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

header('Content-Type: application/json; charset=utf-8');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

$lead_id = isset($_GET['lead_id']) ? intval($_GET['lead_id']) : 0;
if ($lead_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'ID de lead inválido']);
    exit;
}

try {
    $db = getDB();
    $stats = $db->selectOne(
        "SELECT 
            COUNT(CASE WHEN la.type = 'call' THEN 1 END) as total_calls,
            COUNT(CASE WHEN la.type = 'email' THEN 1 END) as total_emails,
            COUNT(CASE WHEN la.type = 'meeting' THEN 1 END) as total_meetings,
            COUNT(CASE WHEN la.type = 'task' AND la.status = 'completed' THEN 1 END) as completed_tasks,
            COUNT(CASE WHEN la.type = 'task' AND la.status = 'pending' THEN 1 END) as pending_tasks,
            MAX(la.created_at) as last_activity
         FROM lead_activities la
         WHERE la.lead_id = ?",
        [$lead_id]
    );

    echo json_encode(['success' => true, 'stats' => $stats]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error al obtener estadísticas', 'detail' => $e->getMessage()]);
}
?>