<?php
// Endpoint JSON para obtener estadísticas de Leads en tiempo real
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__))); // .../simple_crm
}

require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

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

function userHasPermissionByName($pdo, $permName, $userId) {
    if (empty($userId)) return false;
    $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
    $stmt->execute([$userId, $permName]);
    return (bool)$stmt->fetchColumn();
}

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

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

try {
    $db = getDB();
    $pdo = $db->getConnection();
    $userId = (int)($_SESSION['user_id'] ?? 0);

    if (userHasPermissionByName($pdo, 'leads.view_all', $userId)) {
        $stats = [
            'total' => $db->count("SELECT COUNT(*) FROM leads"),
            'new' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'new'"),
            'qualified' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'qualified'"),
            'deposited' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'deposited'"),
            'active_traders' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'active_trader'")
        ];
    } else {
        $stats = [
            'total' => $db->count("SELECT COUNT(*) FROM leads WHERE assigned_to = ?", [$userId]),
            'new' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'new' AND assigned_to = ?", [$userId]),
            'qualified' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'qualified' AND assigned_to = ?", [$userId]),
            'deposited' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'deposited' AND assigned_to = ?", [$userId]),
            'active_traders' => $db->count("SELECT COUNT(*) FROM leads WHERE status = 'active_trader' AND assigned_to = ?", [$userId])
        ];
    }

    echo json_encode(['success' => true, 'data' => $stats]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error obteniendo estadísticas', 'error' => $e->getMessage()]);
}
?>