<?php
/**
 * Módulo Dashboard - Página Principal
 */

// Iniciar sesión si no está iniciada
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Definir constantes si no están definidas
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__)));
}

// Incluir configuración de base de datos
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Función para verificar login si no existe
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

// Endpoint JSON de estadísticas para updateStats()
if (isset($_GET['action']) && $_GET['action'] === 'stats') {
    header('Content-Type: application/json; charset=utf-8');
    if (!isLoggedIn()) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'No autorizado']);
        exit;
    }
    $db = getDB();
    $pdo = $db->getConnection();
    $current_user_id = $_SESSION['user_id'] ?? 0;
    if (!function_exists('userHasPermissionByName')) {
        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();
        }
    }
    $restrictLeads = !userHasPermissionByName($pdo, 'leads.view_all', $current_user_id);
    try {
        $stats = [
            'total_leads' => $restrictLeads
                ? (int)$db->count("SELECT COUNT(*) FROM leads WHERE assigned_to = ?", [$current_user_id])
                : (int)$db->count("SELECT COUNT(*) FROM leads"),
            'leads_today' => $restrictLeads
                ? (int)$db->count("SELECT COUNT(*) FROM leads WHERE DATE(created_at) = CURDATE() AND assigned_to = ?", [$current_user_id])
                : (int)$db->count("SELECT COUNT(*) FROM leads WHERE DATE(created_at) = CURDATE()"),
            'active_traders' => $restrictLeads
                ? (int)$db->count("SELECT COUNT(*) FROM leads WHERE status = 'active_trader' AND assigned_to = ?", [$current_user_id])
                : (int)$db->count("SELECT COUNT(*) FROM leads WHERE status = 'active_trader'"),
            'total_desks' => (int)$db->count("SELECT COUNT(*) FROM desks WHERE status = 'active'")
        ];
        echo json_encode(['success' => true, 'stats' => $stats]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Error calculando estadísticas']);
    }
    exit;
}

if (!isLoggedIn()) {
    header('Location: /index.php?module=auth&action=login');
    exit;
}

// Configurar variables para el layout
$page_title = 'Dashboard';
$content_file = BASE_PATH . '/modules/dashboard/dashboard_content.php';

// Incluir el layout principal
include BASE_PATH . '/modules/shared/layout.php';