<?php
// FILE: /digitalpremium/pages/dashboard.php (Mejorado y Consolidado)

// Habilitar la visualización de errores para depuración (¡COMENTAR O ELIMINAR EN PRODUCCIÓN!)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['id_usuario'])) {
    header("Location: /digitalpremium/login.php");
    exit();
}

require_once '../config/db.php';
require_once '../includes/message_helper.php';

$page_title = "Panel Principal - DigitalPremium";
include_once '../includes/header.php';

// --- OBTENER DATOS DE SESIÓN ---
$id_usuario_sesion = $_SESSION['id_usuario'];
$rol_usuario_sesion = $_SESSION['rol'];
$nombre_usuario_sesion = $_SESSION['nombre_usuario'] ?? 'Usuario';

// --- Carga de Configuraciones (usando la función multiusuario) ---
$nombre_negocio = getConfigValue('nombre_negocio', $id_usuario_sesion, 'DigitalPremium');
$moneda_simbolo = getConfigValue('moneda_simbolo', $id_usuario_sesion, 'S/');
$dias_alerta_clientes = (int)getConfigValue('dias_alerta_clientes', $id_usuario_sesion, 7);
$dias_alerta_maestras = (int)getConfigValue('dias_alerta_maestras', $id_usuario_sesion, 15);

// --- Funciones auxiliares para el diseño (Centralizadas) ---
function getPlatformCardColorClass(string $platform_name): string {
    $platform_name = strtolower($platform_name);
    if (strpos($platform_name, 'netflix') !== false) return 'card-platform-netflix';
    if (strpos($platform_name, 'disney') !== false) return 'card-platform-disney';
    if (strpos($platform_name, 'prime video') !== false) return 'card-platform-prime';
    if (strpos($platform_name, 'hbo') !== false || strpos($platform_name, 'max') !== false) return 'card-platform-hbo';
    if (strpos($platform_name, 'spotify') !== false) return 'card-platform-spotify';
    if (strpos($platform_name, 'youtube') !== false) return 'card-platform-youtube';
    if (strpos($platform_name, 'canva') !== false) return 'card-platform-canva';
    if (strpos($platform_name, 'crunchyroll') !== false) return 'card-platform-crunchyroll';
    if (strpos($platform_name, 'paramount') !== false) return 'card-platform-paramount';
    if (strpos($platform_name, 'iptv') !== false) return 'card-platform-iptv';
    if (strpos($platform_name, 'capcut') !== false) return 'card-platform-capcut';
    if (strpos($platform_name, 'directv') !== false) return 'card-platform-directv';
    if (strpos($platform_name, 'movistar') !== false) return 'card-platform-movistar';
    if (strpos($platform_name, 'flujo tv') !== false) return 'card-platform-flujo';
    if (strpos($platform_name, 'viki') !== false) return 'card-platform-viki';
    return 'card-platform-default';
}

function getPlatformIcon(string $platform_name): string {
    $platform_name = strtolower($platform_name);
    if (strpos($platform_name, 'netflix') !== false) return 'fab fa-netflix';
    if (strpos($platform_name, 'disney') !== false) return 'fas fa-mouse-pointer';
    if (strpos($platform_name, 'prime video') !== false) return 'fab fa-amazon';
    if (strpos($platform_name, 'hbo') !== false || strpos($platform_name, 'max') !== false) return 'fas fa-tv';
    if (strpos($platform_name, 'spotify') !== false) return 'fab fa-spotify';
    if (strpos($platform_name, 'youtube') !== false) return 'fab fa-youtube';
    if (strpos($platform_name, 'crunchyroll') !== false) return 'fas fa-star';
    if (strpos($platform_name, 'canva') !== false) return 'fas fa-paint-brush';
    if (strpos($platform_name, 'paramount') !== false) return 'fas fa-mountain';
    if (strpos($platform_name, 'iptv') !== false) return 'fas fa-satellite-dish';
    if (strpos($platform_name, 'capcut') !== false) return 'fas fa-video';
    if (strpos($platform_name, 'directv') !== false) return 'fas fa-satellite';
    if (strpos($platform_name, 'movistar') !== false) return 'fas fa-wifi';
    if (strpos($platform_name, 'flujo tv') !== false) return 'fas fa-stream';
    if (strpos($platform_name, 'viki') !== false) return 'fas fa-heart';
    return 'fas fa-globe';
}
// --- Fin funciones auxiliares ---

// --- KPI CALCULATIONS ---
// Inicializar parámetros y cláusula WHERE
$params = [];
$user_where_clause_kpi = '';

if ($rol_usuario_sesion !== 'superadmin') {
    $user_where_clause_kpi = " AND id_usuario = :id_usuario";
    $params[':id_usuario'] = $id_usuario_sesion;
}

// Total Clientes Activos
$sql_clientes = "SELECT COUNT(*) FROM clientes WHERE estado_cliente = 1" . $user_where_clause_kpi;
$stmt = $pdo->prepare($sql_clientes);
$stmt->execute($params);
$total_clientes_activos = $stmt->fetchColumn() ?? 0;

// Total Perfiles Activos
$sql_perfiles = "SELECT COUNT(*) FROM perfiles_vendidos WHERE estado_suscripcion = 1 AND fecha_fin_servicio >= CURDATE()" . $user_where_clause_kpi;
$stmt = $pdo->prepare($sql_perfiles);
$stmt->execute($params);
$total_perfiles_activos = $stmt->fetchColumn() ?? 0;

// Total Cuentas Maestras Activas
$sql_cuentas_m_kpi = "SELECT COUNT(*) FROM cuentas_maestras WHERE estado_cuenta = 1 AND fecha_vencimiento_proveedor >= CURDATE()" . $user_where_clause_kpi;
$stmt = $pdo->prepare($sql_cuentas_m_kpi);
$stmt->execute($params);
$total_cuentas_maestras_activas = $stmt->fetchColumn() ?? 0;


// --- KPI CALCULATIONS FOR CURRENT MONTH (FINANCIAL) ---
$current_month_kpi = date('m');
$current_year_kpi = date('Y');

// Permitir selección de mes desde GET, por defecto mes actual
$selected_month = $_GET['mes'] ?? $current_month_kpi;
$selected_year = $_GET['año'] ?? $current_year_kpi;

$monthly_params_kpi = [
    ':current_month' => $selected_month,
    ':current_year' => $selected_year
];
$monthly_user_filter_kpi = '';
if ($rol_usuario_sesion !== 'superadmin') {
    $monthly_user_filter_kpi = " AND id_usuario = :id_usuario_sesion";
    $monthly_params_kpi[':id_usuario_sesion'] = $id_usuario_sesion;
}

// Monthly Revenue
$sql_monthly_revenue_kpi = "
    SELECT COALESCE(SUM(precio_venta), 0)
    FROM perfiles_vendidos
    WHERE MONTH(fecha_inicio_servicio) = :current_month
      AND YEAR(fecha_inicio_servicio) = :current_year
    {$monthly_user_filter_kpi}
";
$stmt_monthly_revenue_kpi = $pdo->prepare($sql_monthly_revenue_kpi);
$stmt_monthly_revenue_kpi->execute($monthly_params_kpi);
$monthly_revenue_kpi = $stmt_monthly_revenue_kpi->fetchColumn();

// Monthly Cost
$sql_monthly_cost_kpi = "
    SELECT COALESCE(SUM(costo_compra), 0)
    FROM cuentas_maestras
    WHERE MONTH(fecha_compra_proveedor) = :current_month
      AND YEAR(fecha_compra_proveedor) = :current_year
    {$monthly_user_filter_kpi}
";
$stmt_monthly_cost_kpi = $pdo->prepare($sql_monthly_cost_kpi);
$stmt_monthly_cost_kpi->execute($monthly_params_kpi);
$monthly_cost_kpi = $stmt_monthly_cost_kpi->fetchColumn();

$monthly_profit_kpi = $monthly_revenue_kpi - $monthly_cost_kpi;

// Calcular también datos del mes anterior para comparación
$previous_month = $selected_month == '01' ? '12' : str_pad($selected_month - 1, 2, '0', STR_PAD_LEFT);
$previous_year = $selected_month == '01' ? $selected_year - 1 : $selected_year;

$previous_params_kpi = [
    ':previous_month' => $previous_month,
    ':previous_year' => $previous_year
];
if ($rol_usuario_sesion !== 'superadmin') {
    $previous_params_kpi[':id_usuario_sesion'] = $id_usuario_sesion;
}

// Previous Month Revenue
$sql_previous_revenue_kpi = "
    SELECT COALESCE(SUM(precio_venta), 0)
    FROM perfiles_vendidos
    WHERE MONTH(fecha_inicio_servicio) = :previous_month
      AND YEAR(fecha_inicio_servicio) = :previous_year
    " . ($rol_usuario_sesion !== 'superadmin' ? " AND id_usuario = :id_usuario_sesion" : "");
$stmt_previous_revenue_kpi = $pdo->prepare($sql_previous_revenue_kpi);
$stmt_previous_revenue_kpi->execute($previous_params_kpi);
$previous_revenue_kpi = $stmt_previous_revenue_kpi->fetchColumn();

// Previous Month Cost
$sql_previous_cost_kpi = "
    SELECT COALESCE(SUM(costo_compra), 0)
    FROM cuentas_maestras
    WHERE MONTH(fecha_compra_proveedor) = :previous_month
      AND YEAR(fecha_compra_proveedor) = :previous_year
    " . ($rol_usuario_sesion !== 'superadmin' ? " AND id_usuario = :id_usuario_sesion" : "");
$stmt_previous_cost_kpi = $pdo->prepare($sql_previous_cost_kpi);
$stmt_previous_cost_kpi->execute($previous_params_kpi);
$previous_cost_kpi = $stmt_previous_cost_kpi->fetchColumn();

$previous_profit_kpi = $previous_revenue_kpi - $previous_cost_kpi;


// --- LÓGICA DE ALERTAS ---
$alerts = [
    'clientes_vencidos' => [],
    'clientes_proximos' => [],
    'maestras_vencidas' => [],
    'maestras_proximas' => []
];

// Alertas de Clientes (Suscripciones)
$params_alertas_clientes = [':dias_alerta_clientes' => $dias_alerta_clientes];
$where_alertas_clientes_sql = "
    WHERE pv.estado_suscripcion = 1 AND (
        DATEDIFF(pv.fecha_fin_servicio, CURDATE()) <= 0 OR
        DATEDIFF(pv.fecha_fin_servicio, CURDATE()) BETWEEN 1 AND :dias_alerta_clientes
    )";

if ($rol_usuario_sesion !== 'superadmin') {
    $where_alertas_clientes_sql .= " AND pv.id_usuario = :id_usuario_sesion";
    $params_alertas_clientes[':id_usuario_sesion'] = $id_usuario_sesion;
}

$sql_client_alerts = "
    SELECT
        pv.id_perfil_vendido, pv.nombre_perfil_cliente, pv.fecha_fin_servicio,
        p.nombre_plataforma, c.nombre_completo AS cliente_nombre, c.telefono AS cliente_telefono,
        DATEDIFF(pv.fecha_fin_servicio, CURDATE()) as dias_restantes
    FROM perfiles_vendidos pv
    JOIN cuentas_maestras cm ON pv.id_cuenta_maestra = cm.id_cuenta_maestra
    JOIN plataformas p ON cm.id_plataforma = p.id_plataforma
    JOIN clientes c ON pv.id_cliente = c.id_cliente
    {$where_alertas_clientes_sql}
    ORDER BY dias_restantes ASC
";

$stmt_client_alerts = $pdo->prepare($sql_client_alerts);
$stmt_client_alerts->execute($params_alertas_clientes);
while ($row = $stmt_client_alerts->fetch(PDO::FETCH_ASSOC)) {
    if ($row['dias_restantes'] <= 0) {
        $alerts['clientes_vencidos'][] = $row;
    } else {
        $alerts['clientes_proximos'][] = $row;
    }
}

// Alertas de Cuentas Maestras
$params_alertas_maestras = [':dias_alerta_maestras' => $dias_alerta_maestras];
$where_alertas_maestras_sql = "
    WHERE cm.estado_cuenta = 1 AND (
        DATEDIFF(cm.fecha_vencimiento_proveedor, CURDATE()) < 0 OR
        DATEDIFF(cm.fecha_vencimiento_proveedor, CURDATE()) BETWEEN 0 AND :dias_alerta_maestras
    )";

if ($rol_usuario_sesion !== 'superadmin') {
    $where_alertas_maestras_sql .= " AND cm.id_usuario = :id_usuario_sesion";
    $params_alertas_maestras[':id_usuario_sesion'] = $id_usuario_sesion;
}

$sql_master_alerts = "
    SELECT
        cm.id_cuenta_maestra, cm.email_cuenta, cm.fecha_vencimiento_proveedor, cm.nombre_proveedor,
        p.nombre_plataforma,
        DATEDIFF(cm.fecha_vencimiento_proveedor, CURDATE()) as dias_restantes
    FROM
        cuentas_maestras cm
    JOIN
        plataformas p ON cm.id_plataforma = p.id_plataforma
    {$where_alertas_maestras_sql}
    ORDER BY
        dias_restantes ASC
";

$stmt_master_alerts = $pdo->prepare($sql_master_alerts);
$stmt_master_alerts->execute($params_alertas_maestras);
while ($row = $stmt_master_alerts->fetch(PDO::FETCH_ASSOC)) {
    if ($row['dias_restantes'] < 0) {
        $alerts['maestras_vencidas'][] = $row;
    } else {
        $alerts['maestras_proximas'][] = $row;
    }
}

// Total alerts for the badge
$total_pending_alerts = count($alerts['clientes_vencidos']) + count($alerts['clientes_proximos']) +
                        count($alerts['maestras_vencidas']) + count($alerts['maestras_proximas']);

// --- Data for Platform-grouped Master Account Cards ---
$where_clauses_cm_display = [];
$params_cm_display = [];

if ($rol_usuario_sesion !== 'superadmin') {
    $where_clauses_cm_display[] = "cm.id_usuario = :id_usuario_sesion_cm_display";
    $params_cm_display[':id_usuario_sesion_cm_display'] = $id_usuario_sesion;
}

// Apply GET filters if present
if (!empty($_GET['filtro_plataforma'])) { $where_clauses_cm_display[] = "p.id_plataforma = :id_plataforma"; $params_cm_display[':id_plataforma'] = $_GET['filtro_plataforma']; }
if (isset($_GET['filtro_estado']) && ($_GET['filtro_estado'] !== '')) { $where_clauses_cm_display[] = "cm.estado_cuenta = :estado_cuenta"; $params_cm_display[':estado_cuenta'] = $_GET['filtro_estado']; }
if (($_GET['filtro_perfiles_disponibles'] ?? '') === 'si') { $where_clauses_cm_display[] = "cm.perfiles_disponibles > 0"; }

// LÓGICA DE FILTRADO CORREGIDA para incluir el teléfono del cliente
if (!empty($_GET['search_query'])) {
    $search_query_param = '%' . trim($_GET['search_query']) . '%';
    $where_clauses_cm_display[] = "(cm.email_cuenta LIKE :search_query_email OR cm.nombre_proveedor LIKE :search_query_proveedor OR p.nombre_plataforma LIKE :search_query_plataforma OR pv.nombre_perfil_cliente LIKE :search_query_perfil OR c.nombre_completo LIKE :search_query_cliente OR c.telefono LIKE :search_query_telefono)";
    $params_cm_display[':search_query_email'] = $search_query_param;
    $params_cm_display[':search_query_proveedor'] = $search_query_param;
    $params_cm_display[':search_query_plataforma'] = $search_query_param;
    $params_cm_display[':search_query_perfil'] = $search_query_param;
    $params_cm_display[':search_query_cliente'] = $search_query_param;
    $params_cm_display[':search_query_telefono'] = $search_query_param;
}

$sql_where_cm_display = !empty($where_clauses_cm_display) ? " WHERE " . implode(" AND ", $where_clauses_cm_display) : "";


// Main query for master accounts with grouped profiles
$sql_cuentas_maestras_display = "
    SELECT
        cm.id_cuenta_maestra, cm.id_plataforma, cm.email_cuenta, cm.password_cuenta,
        cm.perfiles_total, cm.perfiles_disponibles, cm.estado_cuenta, cm.fecha_vencimiento_proveedor,
        cm.nombre_proveedor, cm.costo_compra,
        p.nombre_plataforma, p.max_perfiles_cuenta,
        DATEDIFF(cm.fecha_vencimiento_proveedor, CURDATE()) as dias_restantes_cm,
        GROUP_CONCAT(
            DISTINCT CONCAT_WS('|',
                pv.id_perfil_vendido,
                pv.nombre_perfil_cliente,
                COALESCE(pv.pin_perfil_cliente, ''),
                pv.fecha_inicio_servicio,
                pv.fecha_fin_servicio,
                pv.precio_venta,
                pv.estado_suscripcion,
                c.nombre_completo,
                COALESCE(c.telefono, '')
            ) ORDER BY pv.nombre_perfil_cliente ASC SEPARATOR '###'
        ) AS perfiles_vendidos_data
    FROM
        cuentas_maestras cm
    JOIN
        plataformas p ON cm.id_plataforma = p.id_plataforma
    LEFT JOIN
        perfiles_vendidos pv ON cm.id_cuenta_maestra = pv.id_cuenta_maestra
    LEFT JOIN
        clientes c ON pv.id_cliente = c.id_cliente
    {$sql_where_cm_display}
    GROUP BY
        cm.id_cuenta_maestra
    ORDER BY
        p.nombre_plataforma ASC, cm.estado_cuenta DESC, cm.perfiles_disponibles DESC
";

$stmt_cuentas_maestras_display = $pdo->prepare($sql_cuentas_maestras_display);
$stmt_cuentas_maestras_display->execute($params_cm_display);
$cuentas_maestras_data_display = $stmt_cuentas_maestras_display->fetchAll(PDO::FETCH_ASSOC);


// Organize data by platform for visualization and calculate total active platforms
$grouped_data_display = [];
$processed_platforms_display = [];
$total_plataformas_con_activas = 0;

foreach ($cuentas_maestras_data_display as $cm) {
    if (!isset($grouped_data_display[$cm['id_plataforma']])) {
        $grouped_data_display[$cm['id_plataforma']] = [
            'nombre_plataforma' => $cm['nombre_plataforma'],
            'max_perfiles_cuenta' => $cm['max_perfiles_cuenta'],
            'cuentas' => []
        ];
        if (!in_array($cm['id_plataforma'], $processed_platforms_display) && ($cm['estado_cuenta'] == 1)) {
            $processed_platforms_display[] = $cm['id_plataforma'];
            $total_plataformas_con_activas++;
        }
    }

    $current_master_account_sales_price = 0;
    $current_master_account_used_profiles = 0;

    $profiles = [];
    if (!empty($cm['perfiles_vendidos_data'])) {
        $profiles_raw = explode('###', $cm['perfiles_vendidos_data']);
        foreach ($profiles_raw as $p_data) {
            $parts = explode('|', $p_data);
            if (count($parts) === 9) {
                $profile_status = (int)$parts[6];
                $profile_price_sale = (float)$parts[5];

                $profiles[] = [
                    'id_perfil_vendido' => (string)$parts[0],
                    'nombre_perfil_cliente' => (string)$parts[1],
                    'pin_perfil_cliente' => (string)$parts[2],
                    'fecha_inicio_servicio' => (string)$parts[3],
                    'fecha_fin_servicio' => (string)$parts[4],
                    'precio_venta' => $profile_price_sale,
                    'estado_suscripcion' => $profile_status,
                    'nombre_cliente' => (string)$parts[7],
                    'cliente_telefono' => (string)$parts[8]
                ];
                if ($profile_status == 1) {
                    $current_master_account_sales_price += $profile_price_sale;
                    $current_master_account_used_profiles++;
                }
            }
        }
    }
    $cm['perfiles'] = $profiles;
    $cm['total_sales_price'] = $current_master_account_sales_price;
    $cm['current_profit'] = $current_master_account_sales_price - (float)$cm['costo_compra'];

    $grouped_data_display[$cm['id_plataforma']]['cuentas'][] = $cm;
}

// Manejo del mensaje post-compra (si viene de perfiles_vendidos_crear)
$mensaje_para_copiar_al_cliente = null;
if (isset($_SESSION['mensaje_post_compra_para_copiar'])) {
    $mensaje_para_copiar_al_cliente = $_SESSION['mensaje_post_compra_para_copiar'];
    unset($_SESSION['mensaje_post_compra_para_copiar']);
}

// Formato de fecha
$fecha_actual_formateada = 'Fecha no disponible';
if (class_exists('IntlDateFormatter')) {
    $fmt = new IntlDateFormatter('es_PE', IntlDateFormatter::FULL, IntlDateFormatter::NONE, 'America/Lima', IntlDateFormatter::GREGORIAN, "EEEE, dd 'de' MMMM 'de'yyyy");
    if ($fmt) {
        $fecha_actual_formateada = ucfirst($fmt->format(new DateTime()));
    } else {
        $fecha_actual_formateada = date('d/m/Y');
        error_log("IntlDateFormatter falló al inicializar: " . intl_get_error_message());
    }
} else {
    $fecha_actual_formateada = date('d/m/Y');
    error_log("La extensión intl de PHP no está habilitada.");
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&family=Roboto+Mono:wght@400;700&display=swap" rel="stylesheet">
    <style>
        /* --- Root Variables for Consistent Design --- */
        :root {
            --primary-color: #6a1b9a; /* Un morado más profundo para la marca */
            --primary-hover: #4a148c;
            --secondary-color: #6c757d; /* Gris estándar */
            --success-color: #28a745; /* Verde */
            --warning-color: #ffc107; /* Naranja */
            --danger-color: #dc3545; /* Rojo */
            --info-color: #17a2b8; /* Azul claro */
            --dark-color: #343a40; /* Gris oscuro casi negro */
            
            --light-bg: #f8f9fa; /* Un gris muy claro */
            --card-bg: #ffffff; /* Blanco para tarjetas */
            --body-bg: #e9ecef; /* Fondo general del dashboard, un gris muy suave */

            --text-dark: #212529; /* Casi negro para textos principales */
            --text-muted: #6c757d; /* Gris para textos secundarios/muted */
            --border-color: #dee2e6; /* Gris claro para bordes */
            
            --shadow-sm: 0 .125rem .25rem rgba(0,0,0,.075);
            --shadow-md: 0 .5rem 1rem rgba(0,0,0,.15);
            --shadow-lg: 0 1rem 3rem rgba(0,0,0,.175);
            
            --font-family-base: 'Poppins', sans-serif;
            --font-family-mono: 'Roboto Mono', monospace;
            
            /* Enhanced Gradients for Cards */
            --gradient-card-light: linear-gradient(135deg, #fefefe, #f0f4f8);
            --gradient-header-dark: linear-gradient(90deg, var(--primary-color), var(--primary-hover));
            --gradient-button: linear-gradient(90deg, var(--primary-color), #8a2be2); /* Slightly lighter purple for buttons */

            /* Soft colors for badges and backgrounds - use Bootstrap's own theme colors for consistency */
            --bs-success-soft: #d4edda;
            --bs-warning-soft: #fff3cd;
            --bs-danger-soft: #f8d7da;
            --bs-info-soft: #d1ecf1;
            --bs-dark-soft: #e2e6ea;

            /* Emphasis colors for text */
            --bs-success-emphasis: #155724;
            --bs-warning-emphasis: #856404;
            --bs-danger-emphasis: #721c24;
            --bs-info-emphasis: #0c5460;
            --bs-dark-emphasis: #1d2124;

            --border-radius-sm: 0.25rem;
            --border-radius-md: 0.5rem;
            --border-radius-lg: 0.75rem; /* Standard large border radius */
            --border-radius-xl: 1rem; /* Even larger for main cards */

            --transition-base: all 0.3s ease-in-out;
        }

        body {
            background-color: var(--body-bg);
            font-family: var(--font-family-base);
            color: var(--text-dark);
            line-height: 1.6;
        }

        /* --- General Layout and Typography --- */
        .container-fluid {
            padding: 1.5rem 1rem;
        }

        .page-header {
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 1.5rem;
            margin-bottom: 2rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
        }

        .page-title {
            font-weight: 700;
            font-size: 2rem;
            color: var(--primary-color);
            margin-bottom: 0.5rem;
        }

        .page-title i {
            color: var(--primary-color);
            font-size: 1.1em;
        }

        .page-header p {
            font-size: 0.95rem;
            color: var(--text-muted);
        }

        .section-title {
            font-size: 1.4rem;
            font-weight: 600;
            color: var(--text-dark);
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
        }
        .section-title i {
            color: var(--primary-color);
            font-size: 1.1em;
            margin-right: 0.75rem;
        }

        /* --- Buttons --- */
        .btn {
            font-weight: 600;
            border-radius: var(--border-radius-lg);
            padding: 0.65rem 1.1rem;
            transition: var(--transition-base);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
        .btn-sm {
            padding: 0.4rem 0.8rem;
            font-size: 0.8rem;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-sm);
        }

        .btn-primary { background-color: var(--primary-color); border-color: var(--primary-color); color: white; }
        .btn-primary:hover { background-color: var(--primary-hover); border-color: var(--primary-hover); }

        .btn-warning { background-color: var(--warning-color); border-color: var(--warning-color); color: var(--bs-warning-emphasis); }
        .btn-warning:hover { background-color: #e0a800; border-color: #e0a800; }

        .btn-outline-secondary { color: var(--secondary-color); border-color: var(--secondary-color); }
        .btn-outline-secondary:hover { background-color: var(--secondary-color); color: white; }
        
        .btn-info { background-color: var(--info-color); border-color: var(--info-color); color: white; }
        .btn-info:hover { background-color: #117a8b; border-color: #117a8b; }

        /* Alert button in header */
        .alert-button-header {
            position: relative;
            background-color: var(--warning-color);
            border-color: var(--warning-color);
            color: var(--bs-warning-emphasis);
            padding: 0.6rem 1rem;
            border-radius: var(--border-radius-lg);
            font-size: 0.9rem;
            font-weight: 600;
            transition: var(--transition-base);
            box-shadow: var(--shadow-sm);
        }
        .alert-button-header:hover {
            filter: brightness(0.9);
        }
        .alert-badge-count {
            position: absolute;
            top: -8px;
            right: -8px;
            padding: 0.2em 0.6em;
            border-radius: 50%;
            background-color: var(--danger-color);
            color: white;
            font-size: 0.75em;
            font-weight: 700;
            line-height: 1;
            min-width: 20px;
            text-align: center;
        }

        /* --- Cards - General Styles --- */
        .card {
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius-xl);
            box-shadow: var(--shadow-sm);
            transition: var(--transition-base);
            background: var(--gradient-card-light);
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .card:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-md);
        }
        
        .card-header {
            background-color: var(--primary-color);
            color: white;
            font-weight: 600;
            font-size: 1.05rem;
            border-top-left-radius: calc(var(--border-radius-xl) - 1px);
            border-top-right-radius: calc(var(--border-radius-xl) - 1px);
            padding: 0.9rem 1.25rem;
            background: var(--gradient-header-dark);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .card-body {
            padding: 1.25rem;
            flex-grow: 1;
        }
        .card-footer {
            background-color: var(--light-bg);
            border-top: 1px solid var(--border-color);
            padding: 0.75rem 1.25rem;
            border-bottom-left-radius: var(--border-radius-xl);
            border-bottom-right-radius: var(--border-radius-xl);
            transition: background-color 0.2s ease;
        }
        .card-footer:hover {
            background-color: var(--border-color);
        }

        /* --- KPI Cards - Elevated Design --- */
        .kpi-card {
            border: none;
            position: relative;
            overflow: hidden;
            background: var(--primary-color); /* Default solid background */
            color: white; /* Text color for KPI cards */
        }
        .kpi-card::before { /* Subtle overlay for depth */
            content: '';
            position: absolute;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(255, 255, 255, 0.05);
            pointer-events: none;
            z-index: 0;
        }

        .kpi-card .card-body {
            padding: 1.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: row; /* Layout change for horizontal alignment */
            text-align: left;
            position: relative; /* For z-index to be above pseudo-element */
            z-index: 1;
        }

        .kpi-card .kpi-icon-wrapper {
            width: 60px;
            height: 60px;
            background-color: rgba(255, 255, 255, 0.15); /* More transparent */
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1.2rem; /* Space to the right of icon */
            margin-bottom: 0; /* No bottom margin in horizontal layout */
            flex-shrink: 0;
            box-shadow: var(--shadow-sm);
        }

        .kpi-card .kpi-icon-wrapper i {
            font-size: 1.8rem;
            color: white;
        }

        .kpi-card .kpi-value {
            font-size: 2rem;
            font-weight: 800;
            line-height: 1.2;
            margin-bottom: 0.2rem;
            color: white;
        }

        .kpi-card .kpi-title {
            font-size: 0.8rem;
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 0.04em;
            font-weight: 500;
            color: white;
        }

        /* KPI Card Colors - Solid gradients or specific colors */
        .kpi-card.kpi-primary { background: var(--primary-color); }
        .kpi-card.kpi-success { background: var(--success-color); }
        .kpi-card.kpi-info { background: var(--info-color); }
        .kpi-card.kpi-secondary { background: var(--secondary-color); }


        /* --- Financial Cards - Clean with Left Border --- */
        .financial-card {
            border-left: 6px solid;
            border-radius: var(--border-radius-lg);
            background-color: var(--card-bg);
            box-shadow: var(--shadow-sm);
        }

        .financial-card:hover {
            box-shadow: var(--shadow-md);
        }

        .financial-card .card-body {
            padding: 1.2rem;
        }

        .financial-card .small.fw-bold {
            font-size: 0.85rem;
            letter-spacing: 0.03em;
        }

        .financial-card .h4 {
            font-size: 1.6rem;
            font-weight: 700;
            color: var(--text-dark);
        }

        .financial-card i.fas {
            opacity: 0.15;
            font-size: 2.2rem;
        }

        /* Border colors for Financial Cards */
        .financial-card.border-success { border-left-color: var(--success-color) !important; }
        .financial-card.border-danger { border-left-color: var(--danger-color) !important; }
        .financial-card.border-primary { border-left-color: var(--primary-color) !important; }
        .financial-card.border-warning { border-left-color: var(--warning-color) !important; }

        /* --- Alert Modals Styling --- */
        .modal-content {
            border-radius: var(--border-radius-xl);
            box-shadow: var(--shadow-lg);
        }
        .modal-header {
            border-bottom: none;
            padding: 1.5rem;
        }
        .modal-title {
            font-weight: 700;
            font-size: 1.3rem;
        }
        .modal-footer {
            border-top: 1px solid var(--border-color);
            padding: 1.5rem;
        }
        .btn-close-white { filter: invert(1); }

        .alert-section .alert {
            border-radius: var(--border-radius-lg);
            border-width: 1px;
            border-left-width: 8px;
            margin-bottom: 1.5rem;
            padding: 1.2rem 1.5rem;
            box-shadow: var(--shadow-sm);
            background-color: var(--card-bg);
            position: relative;
            overflow: hidden;
            transition: var(--transition-base);
        }
        .alert-section .alert:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }
        .alert-section .alert-danger { border-color: var(--danger-color); background-color: var(--bs-danger-soft); color: var(--bs-danger-emphasis); }
        .alert-section .alert-warning { border-color: var(--warning-color); background-color: var(--bs-warning-soft); color: var(--bs-warning-emphasis); }
        .alert-section .alert-info { border-color: var(--info-color); background-color: var(--bs-info-soft); color: var(--bs-info-emphasis); }
        .alert-section .alert-success { border-color: var(--success-color); background-color: var(--bs-success-soft); color: var(--bs-success-emphasis); }

        .alert-section .alert:last-child { margin-bottom: 0; }
        .alert-section .alert-title {
            font-weight: 700;
            font-size: 1.15rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            color: var(--text-dark);
        }
        .alert-section .alert-title .icon {
            font-size: 1.5em;
            margin-right: 1rem;
            color: inherit;
        }
        .alert-section ul { list-style: none; padding-left: 0; margin-bottom: 0; }
        .alert-section li {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
            padding: 0.8rem 0;
            border-bottom: 1px dashed var(--border-color);
            color: var(--text-dark);
            position: relative;
            z-index: 1;
        }
        .alert-section li:last-child { border-bottom: none; padding-bottom: 0; }
        
        .alert-item-text { flex-grow: 1; padding-right: 1rem; font-size: 0.9rem; }
        .alert-item-text strong { color: var(--text-dark); display: block; }
        .alert-item-text small { color: var(--text-muted); font-size: 0.8rem; display: block; }

        .action-buttons { display: flex; gap: 0.6rem; flex-shrink: 0; margin-top: 0.5rem; }
        .btn-action {
            font-size: 0.8rem !important;
            font-weight: 600;
            padding: 0.4rem 0.8rem !important;
            border-radius: var(--border-radius-lg);
            display: inline-flex;
            align-items: center;
            gap: 0.4rem;
            transition: var(--transition-base);
            box-shadow: var(--shadow-sm);
        }
        .btn-action-whatsapp { background-color: #25d366; border-color: #25d366; color: white; }
        .btn-action-whatsapp:hover { background-color: #1ea14d; border-color: #1ea14d; color: white; transform: translateY(-1px); }
        .btn-outline-danger { color: var(--danger-color); border-color: var(--danger-color); }
        .btn-outline-danger:hover { background-color: var(--danger-color); color: white; }
        .btn-outline-warning { color: var(--warning-color); border-color: var(--warning-color); }
        .btn-outline-warning:hover { background-color: var(--warning-color); color: var(--bs-warning-emphasis); }
        .btn-outline-dark { color: var(--dark-color); border-color: var(--dark-color); }
        .btn-outline-dark:hover { background-color: var(--dark-color); color: white; }


        /* Alert background icons */
        .alert::before {
            font-family: "Font Awesome 6 Free";
            font-weight: 900;
            position: absolute;
            top: 50%;
            right: 15px;
            transform: translateY(-50%);
            font-size: 3rem; /* Slightly smaller */
            color: rgba(0,0,0,0.02); /* Even more subtle */
            z-index: 0;
            pointer-events: none;
        }
        .alert-danger::before { content: "\f06a"; }
        .alert-warning::before { content: "\f06a"; }
        .alert-info::before { content: "\f05a"; }
        .alert-success::before { content: "\f058"; }


        /* --- Filter & Search Section --- */
        .filter-search-section {
            background: var(--gradient-card-light);
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius-xl);
            padding: 1.5rem;
            box-shadow: var(--shadow-md);
            margin-bottom: 2.5rem;
        }
        .filter-search-section .form-label {
            font-weight: 600;
            color: var(--text-dark);
            font-size: 0.9rem;
            margin-bottom: 0.4rem;
        }
        .filter-search-section .form-control,
        .filter-search-section .form-select {
            border-radius: var(--border-radius-md);
            border-color: #ced4da;
            padding: 0.6rem 0.75rem;
            font-size: 0.9rem;
        }
        .filter-search-section .form-check-label {
            font-size: 0.9rem;
        }

        .filter-actions {
            margin-top: 1.5rem;
        }
        .filter-actions .btn {
            font-size: 0.9rem;
            padding-top: 0.6rem;
            padding-bottom: 0.6rem;
        }
        
        /* --- Platform Groups and Headers (New Design) --- */
        .platform-group {
            position: relative;
            margin-bottom: 3rem;
        }
        .platform-header {
            display: flex;
            align-items: center;
            gap: 1.25rem;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
            border-bottom: 3px solid var(--primary-color);
            position: -webkit-sticky;
            position: sticky;
            top: 0;
            z-index: 100;
            background-color: var(--body-bg);
            padding-top: 1rem;
            padding-bottom: 1rem;
            box-shadow: 0 2px 4px -1px rgba(0,0,0,0.05);
            transition: var(--transition-base);
            border-radius: var(--border-radius-md);
        }
        .platform-header.scrolled {
            background-color: rgba(233, 236, 239, 0.95);
            box-shadow: var(--shadow-md);
            padding-top: 0.6rem;
            padding-bottom: 0.6rem;
        }

        .platform-icon {
            width: 56px; height: 56px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            background: var(--gradient-header-dark);
            color: white;
            font-size: 2rem;
            box-shadow: var(--shadow-sm);
            flex-shrink: 0;
        }
        .platform-header h2 {
            font-size: 2.5rem;
            font-weight: 800;
            color: var(--primary-color);
            margin-bottom: 0;
        }
        .platform-header h2 small {
            font-size: 0.9rem;
            font-weight: 500;
            color: var(--text-muted);
        }

        /* --- Master Account Card (Redesigned with Platform Colors) --- */
        .account-card {
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius-xl);
            box-shadow: var(--shadow-sm);
            transition: all 0.3s ease-in-out;
            display: flex; flex-direction: column;
            height: 100%;
            overflow: hidden;
            position: relative;
            background: var(--gradient-card-light);
            padding-top: 2.5rem; /* Space for the status badge */
        }
        .account-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--shadow-lg);
        }
        
        /* Platform-specific card background and border */
        .account-card.card-platform-netflix { border-color: #E50914; }
        .account-card.card-platform-disney { border-color: #011e59; }
        .account-card.card-platform-prime { border-color: #00A8E1; }
        .account-card.card-platform-hbo { border-color: #6C2B80; }
        .account-card.card-platform-spotify { border-color: #1DB954; }
        .account-card.card-platform-youtube { border-color: #FF0000; }
        .account-card.card-platform-crunchyroll { border-color: #F47521; }
        .account-card.card-platform-canva { border-color: #00C4CC; }
        .account-card.card-platform-paramount { border-color: #0066FF; }
        .account-card.card-platform-iptv { border-color: #6a1b9a; }
        .account-card.card-platform-capcut { border-color: #000000; }
        .account-card.card-platform-directv { border-color: #006097; }
        .account-card.card-platform-movistar { border-color: #79c000; }
        .account-card.card-platform-flujo { border-color: #007bff; }
        .account-card.card-platform-viki { border-color: #FF0077; }

        /* Master account card header - uses platform color */
        .account-card .card-header {
            background: linear-gradient(90deg, var(--primary-color), var(--primary-hover));
            color: white;
            padding: 1rem 1.5rem;
            font-size: 1.15rem;
            font-weight: 700;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-top-left-radius: calc(var(--border-radius-xl) - 1px);
            border-top-right-radius: calc(var(--border-radius-xl) - 1px);
        }
        /* Override for platform-specific headers - keeping yours, just ensuring consistency */
        .account-card.card-platform-netflix .card-header { background: linear-gradient(90deg, #E50914, #B20710); }
        .account-card.card-platform-disney .card-header { background: linear-gradient(90deg, #011e59, #283769); }
        .account-card.card-platform-prime .card-header { background: linear-gradient(90deg, #00A8E1, #0077B5); }
        .account-card.card-platform-hbo .card-header { background: linear-gradient(90deg, #6C2B80, #8A2BE2); }
        .account-card.card-platform-spotify .card-header { background: linear-gradient(90deg, #1DB954, #1ED760); }
        .account-card.card-platform-youtube .card-header { background: linear-gradient(90deg, #FF0000, #CC0000); }
        .account-card.card-platform-crunchyroll .card-header { background: linear-gradient(90deg, #F47521, #CC631B); }
        .account-card.card-platform-canva .card-header { background: linear-gradient(90deg, #00C4CC, #008D94); }
        .account-card.card-platform-paramount .card-header { background: linear-gradient(90deg, #0066FF, #004CB2); }
        .account-card.card-platform-iptv .card-header { background: linear-gradient(90deg, #6a1b9a, #4a148c); }
        .account-card.card-platform-capcut .card-header { background: linear-gradient(90deg, #000000, #333333); }
        .account-card.card-platform-directv .card-header { background: linear-gradient(90deg, #006097, #003050); }
        .account-card.card-platform-movistar .card-header { background: linear-gradient(90deg, #79c000, #5a8d00); }
        .account-card.card-platform-flujo .card-header { background: linear-gradient(90deg, #007bff, #0056b3); }
        .account-card.card-platform-viki .card-header { background: linear-gradient(90deg, #FF0077, #CC0060); }


        /* Account Status Badge - Positioned outside and prominently */
        .account-status-badge {
            position: absolute;
            top: -1px; /* Aligns to the top edge */
            left: 50%;
            transform: translateX(-50%);
            font-size: 0.8rem;
            font-weight: 700;
            padding: 0.35em 0.8em;
            border-radius: 0 0 var(--border-radius-md) var(--border-radius-md); /* Rounded bottom only */
            z-index: 3; /* Ensure it's on top */
            box-shadow: var(--shadow-sm);
            text-transform: uppercase;
            letter-spacing: 0.03em;
        }
        .account-status-active { background-color: var(--success-color); color: white; }
        .account-status-inactive { background-color: var(--secondary-color); color: white; }
        .account-status-problem { background-color: var(--danger-color); color: white; }

        .account-card .card-body {
            padding: 1.25rem 1.5rem;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        .account-details {
            font-size: 0.95rem;
            margin-bottom: 1.5rem;
        }
        .account-details .detail-item {
            display: flex; justify-content: space-between;
            margin-bottom: 0.75rem;
            color: var(--text-muted);
            align-items: center;
        }
        .account-details .detail-item span:first-child { font-weight: 500; color: var(--text-dark); }
        .account-details .detail-item strong {
            color: var(--text-dark);
            font-weight: 600;
        }
        .password-wrapper {
            display: flex; align-items: center; gap: 0.5rem;
            font-family: var(--font-family-mono);
            background-color: var(--light-bg);
            padding: 0.3rem 0.75rem;
            border-radius: var(--border-radius-md);
            border: 1px solid var(--border-color);
            flex-grow: 1;
            justify-content: space-between;
            cursor: pointer;
            word-break: break-all;
            max-width: 170px; /* Adjusted width */
            font-size: 0.85rem;
        }
        .btn-copy, .toggle-password-btn {
            background: none; border: none; color: var(--text-muted); padding: 0.1rem;
            font-size: 0.9rem;
            transition: color 0.2s ease;
            flex-shrink: 0;
            cursor: pointer;
        }
        .btn-copy:hover, .toggle-password-btn:hover { color: var(--primary-color); }
        
        .profit-display {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--success-color);
            text-align: right;
        }
        .profit-display.negative { color: var(--danger-color); }

        /* Account Expiry Progress Bar */
        .account-expiry-bar-container {
            margin-top: 1.25rem;
            padding-top: 1.25rem;
            border-top: 1px dashed var(--border-color); /* Dashed separator */
        }
        .account-expiry-bar-container .progress {
            height: 10px; /* Thinner progress bar */
            background-color: #e9ecef; /* Lighter background for progress track */
            border-radius: 999px;
            margin-top: 5px;
        }
        .account-expiry-bar-container .progress-bar {
            font-weight: 600;
            font-size: 0.75rem;
            line-height: 10px;
        }

        /* --- Client Profile Cards within Master Account Cards --- */
        .profiles-list-wrapper { margin-top: 1.75rem; flex-grow: 1; }
        .profiles-list { max-height: 280px; overflow-y: auto; padding-right: 8px; }
        .profiles-list::-webkit-scrollbar { width: 6px; } /* Thinner scrollbar */
        .profiles-list::-webkit-scrollbar-track { background: transparent; }
        .profiles-list::-webkit-scrollbar-thumb { background: #c2c8d0; border-radius: 10px; }
        .profiles-list::-webkit-scrollbar-thumb:hover { background: #9da5b0; }

        .profile-item {
            display: flex; align-items: center; gap: 0.8rem; /* Reduced gap */
            padding: 0.8rem 1rem; /* Reduced padding */
            border-radius: var(--border-radius-md);
            margin-bottom: 0.6rem; /* Reduced margin */
            background-color: var(--light-bg); /* Lighter background for profile items */
            border: 1px solid var(--border-color);
            box-shadow: var(--shadow-sm);
            transition: var(--transition-base);
            position: relative;
        }
        .profile-item:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
            border-color: var(--info-color);
        }
        .profile-status {
            width: 10px; height: 10px; /* Smaller status dot */
            border-radius: 50%;
            flex-shrink: 0;
            border: 1px solid white; /* Thinner border */
            box-shadow: 0 0 0 1px rgba(0,0,0,0.05);
        }
        .profile-status-active { background-color: var(--success-color); }
        .profile-status-expiring { background-color: var(--warning-color); }
        .profile-status-expired { background-color: var(--danger-color); }
        .profile-status-inactive { background-color: var(--secondary-color); }

        .profile-info { flex-grow: 1; min-width: 0; }
        .profile-info strong {
            font-size: 0.95rem; /* Slightly smaller font */
            font-weight: 600;
            color: var(--primary-color);
            display: block;
            margin-bottom: 0.1rem;
        }
        .profile-info small {
            font-size: 0.8rem;
            color: var(--text-muted);
            display: block;
            line-height: 1.2;
        }
        .status-badge-profile {
            padding: 0.2em 0.6em; /* Smaller padding */
            font-size: 0.7em; /* Smaller font */
            font-weight: 600;
            border-radius: 50px;
            text-transform: uppercase;
            display: inline-block; /* To be next to text */
            margin-left: 0.4rem;
        }
        .status-badge-profile.active { background-color: var(--bs-success-soft); color: var(--bs-success-emphasis); }
        .status-badge-profile.expiring { background-color: var(--bs-warning-soft); color: var(--bs-warning-emphasis); }
        .status-badge-profile.expired { background-color: var(--bs-danger-soft); color: var(--bs-danger-emphasis); }
        .status-badge-profile.inactive { background-color: var(--bs-dark-soft); color: var(--bs-dark-emphasis); }


        .profile-actions { display: flex; gap: 0.5rem; margin-left: auto; flex-shrink: 0; }
        .btn-icon {
            background-color: var(--body-bg); /* Use body-bg for icon buttons for subtle look */
            border: 1px solid var(--border-color);
            color: var(--text-muted);
            width: 36px; height: 36px; /* Smaller icon buttons */
            border-radius: 50%;
            display: inline-flex; align-items: center; justify-content: center;
            transition: var(--transition-base);
            font-size: 1.1rem;
            box-shadow: var(--shadow-sm);
        }
        .btn-icon:hover {
            color: var(--primary-color);
            background-color: var(--primary-color); /* Changed to use primary color for hover */
            color: white; /* Changed text color to white on hover */
            border-color: var(--primary-color);
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }
        .btn-icon .fa-whatsapp { color: #25d366; }
        .btn-icon .fa-whatsapp:hover { color: white; } /* White on hover for WhatsApp */
        
        /* --- Renovar Cuenta Modal Specifics --- */
        #modalRenovarCuenta .modal-body .form-label {
            color: var(--text-dark);
            font-size: 0.95rem;
        }
        #modalRenovarCuenta .modal-body .form-control {
            font-size: 0.9rem;
        }
        #modalRenovarCuenta .modal-footer .btn {
            font-size: 0.9rem;
        }

        /* --- Responsive Adjustments --- */
        @media (max-width: 1199.98px) {
            .platform-header h2 { font-size: 2rem; }
            .platform-icon { width: 50px; height: 50px; font-size: 1.6rem; }
            .account-card .card-header { font-size: 1.05rem; padding: 0.8rem 1.2rem; }
            .account-details, .profiles-list-wrapper { margin-bottom: 1rem; }
            .account-card .card-body { padding: 1rem 1.2rem; }
            .password-wrapper { max-width: 150px; }
            .profile-item { padding: 0.7rem 0.9rem; margin-bottom: 0.5rem; }
            .profile-info strong { font-size: 0.9rem; }
            .profile-info small { font-size: 0.75rem; }
            .btn-icon { width: 32px; height: 32px; font-size: 1rem; }
        }

        @media (max-width: 991.98px) {
            .page-header { flex-direction: column; align-items: flex-start; text-align: left; }
            .page-header .text-end {
                width: 100%;
                text-align: left !important;
                margin-top: 1rem;
                flex-direction: row;
                justify-content: flex-start;
                flex-wrap: wrap;
                gap: 0.75rem; /* Adjust gap for buttons */
            }
            .page-header .btn { width: auto; margin-right: 0; margin-bottom: 0; }
            .alert-button-header { margin-right: 0; }
            
            .page-title { font-size: 1.8rem; }
            .page-header p { font-size: 0.9rem; }

            .kpi-card .card-body { padding: 1rem; flex-direction: column; text-align: center; }
            .kpi-card .kpi-icon-wrapper { margin-right: 0; margin-bottom: 0.8rem; width: 50px; height: 50px; }
            .kpi-card .kpi-icon-wrapper i { font-size: 1.6rem; }
            .kpi-card .kpi-value { font-size: 1.8rem; }
            .kpi-card .kpi-title { font-size: 0.75rem; }

            .section-title { font-size: 1.2rem; margin-bottom: 1rem; }
            .financial-card .card-body { padding: 1rem; }
            .financial-card .h4 { font-size: 1.4rem; }
            .financial-card i.fas { font-size: 1.8rem; }

            .alert-section .alert-title { font-size: 1rem; margin-bottom: 0.8rem; }
            .alert-section .alert-title .icon { font-size: 1.3em; margin-right: 0.8rem; }
            .alert-item-text { width: 100%; margin-bottom: 0.4rem; padding-right: 0; }
            .action-buttons { flex-direction: column; align-items: stretch; gap: 0.4rem; margin-top: 0.4rem; }
            .btn-action { width: 100%; max-width: none; }

            .platform-header { flex-direction: column; align-items: center; text-align: center; gap: 0.8rem; margin-bottom: 1.2rem; padding-bottom: 0.8rem; }
            .platform-icon { width: 45px; height: 45px; font-size: 1.5rem; }
            .platform-header h2 { font-size: 1.8rem; }
            .platform-header h2 small { font-size: 0.8rem; }
            
            .account-card .card-header { font-size: 1rem; padding: 0.75rem 1rem; }
            .account-card .card-body { padding: 1rem; }
            .account-details { font-size: 0.85rem; margin-bottom: 1rem; }
            .account-details .detail-item { margin-bottom: 0.6rem; }
            .profit-display { font-size: 1rem; }
            .password-wrapper { max-width: none; font-size: 0.8rem; }
            .profiles-list-wrapper { margin-top: 1rem; }
            .profiles-list { max-height: 200px; }
            .profile-item { flex-wrap: wrap; padding: 0.6rem 0.8rem; margin-bottom: 0.4rem; }
            .profile-info { flex-basis: 100%; margin-bottom: 0.3rem; }
            .profile-info strong { font-size: 0.85rem; }
            .profile-info small { font-size: 0.7rem; }
            .profile-actions { justify-content: flex-end; gap: 0.4rem; margin-top: 0.3rem; }
            .btn-icon { width: 30px; height: 30px; font-size: 0.9rem; }
        }

        @media (max-width: 767.98px) {
            .page-header .text-end {
                flex-direction: column;
                align-items: stretch;
            }
            .page-header .btn { margin-bottom: 0.5rem; width: 100%; }
            .alert-button-header { margin-bottom: 0.5rem; width: 100%; }
            
            .filter-search-section { padding: 1rem; margin-bottom: 1.5rem; }
            .filter-actions {
                flex-direction: column;
                align-items: stretch;
                gap: 0.5rem;
            }
            .filter-actions .btn {
                width: 100%;
            }
            
            .account-status-badge { font-size: 0.75rem; padding: 0.3em 0.7em; }
        }

        @media (max-width: 575.98px) {
            .container-fluid { padding: 1rem 0.75rem; }
            .page-title { font-size: 1.6rem; }
            .kpi-card .kpi-value { font-size: 1.6rem; }
            .financial-card .h4 { font-size: 1.2rem; }
            .financial-card i.fas { font-size: 1.5rem; }
            .alert-section .alert { padding: 0.8rem; }
            .alert-section .alert-title { font-size: 0.95rem; }
            .alert-section .alert-title .icon { font-size: 1.1em; }
            .alert-item-text strong { font-size: 0.85rem; }
            .alert-item-text small { font-size: 0.7rem; }
            .platform-header h2 { font-size: 1.5rem; }
            .platform-icon { width: 40px; height: 40px; font-size: 1.3rem; }
            .account-card .card-header { font-size: 0.9rem; padding: 0.6rem 0.8rem; }
            .account-card .card-body { padding: 0.8rem; }
            .account-details .detail-item { font-size: 0.8rem; margin-bottom: 0.5rem; }
            .profit-display { font-size: 0.9rem; }
            .profiles-list { max-height: 180px; }
            .profile-item { padding: 0.5rem 0.7rem; margin-bottom: 0.3rem; }
            .profile-info { flex-basis: 100%; margin-bottom: 0.3rem; }
            .profile-info strong { font-size: 0.85rem; }
            .profile-info small { font-size: 0.7rem; }
            .profile-actions { justify-content: flex-end; gap: 0.4rem; margin-top: 0.3rem; }
            .btn-icon { width: 30px; height: 30px; font-size: 0.9rem; }
        }
    </style>
</head>
<body class="dashboard-page">

<div class="container-fluid px-lg-4 px-3 py-4">
    <header class="page-header mb-4">
        <div>
            <h1 class="page-title">
                <i class="fas fa-tachometer-alt me-2"></i>Panel Principal
            </h1>
            <p class="mb-0 text-muted d-none d-md-block">Bienvenido de nuevo, <span class="fw-semibold text-dark"><?php echo htmlspecialchars($nombre_usuario_sesion); ?></span>.</p>
        </div>
        <div class="text-end d-flex align-items-center gap-3">
            <span class="text-muted small d-none d-md-block">Hoy: <?php echo $fecha_actual_formateada; ?></span>
            <button type="button" class="btn alert-button-header position-relative" data-bs-toggle="modal" data-bs-target="#alertsModal">
                <i class="fas fa-bell me-2"></i> Alertas
                <?php if ($total_pending_alerts > 0): ?>
                    <span class="alert-badge-count"><?php echo $total_pending_alerts; ?></span>
                <?php endif; ?>
            </button>
            <a href="/digitalpremium/pages/perfiles_vendidos_crear.php" class="btn btn-primary">
                <i class="fas fa-plus-circle me-2"></i> Nueva Venta
            </a>
            <a href="#" class="btn btn-sm btn-outline-secondary shadow-sm disabled" aria-disabled="true" title="Próximamente">
                <i class="fas fa-print fa-sm me-1"></i> PDF
            </a>
        </div>
    </header>

    <div class="row g-3">
        <?php
        $kpi_cards_list = [
            ['titulo' => 'Clientes Activos', 'valor' => $total_clientes_activos, 'icono' => 'fas fa-users', 'color_class' => 'kpi-primary', 'link' => '/digitalpremium/pages/clientes.php'],
            ['titulo' => 'Suscrip. Activas', 'valor' => $total_perfiles_activos, 'icono' => 'fas fa-user-check', 'color_class' => 'kpi-success', 'link' => '/digitalpremium/pages/perfiles_vendidos.php'],
            ['titulo' => 'Ctas. Maestras Act.', 'valor' => $total_cuentas_maestras_activas, 'icono' => 'fas fa-key', 'color_class' => 'kpi-info', 'link' => '/digitalpremium/pages/cuentas_maestras.php'],
            ['titulo' => 'Plataformas Activas', 'valor' => $total_plataformas_con_activas, 'icono' => 'fas fa-tv', 'color_class' => 'kpi-secondary', 'link' => '/digitalpremium/pages/plataformas.php']
        ];
        ?>
        <?php foreach($kpi_cards_list as $kpi): ?>
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="<?php echo $kpi['link']; ?>" class="card kpi-card <?php echo $kpi['color_class']; ?> h-100 shadow-sm lift text-decoration-none">
                <div class="card-body d-flex align-items-center">
                    <div class="kpi-icon-wrapper">
                        <i class="<?php echo $kpi['icono']; ?>"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <div class="kpi-value"><?php echo $kpi['valor']; ?></div>
                        <div class="kpi-title"><?php echo $kpi['titulo']; ?></div>
                    </div>
                </div>
            </a>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="row g-3 mt-4">
        <div class="col-lg-12">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0 text-muted fw-light section-title"><i class="fas fa-coins me-2"></i>Finanzas</h5>
                <div class="d-flex align-items-center gap-2">
                    <label for="mesSelector" class="form-label mb-0 small text-muted">Seleccionar Mes:</label>
                    <select id="mesSelector" class="form-select form-select-sm" style="width: auto;">
                        <?php
                        // Generar opciones para los últimos 12 meses
                        for ($i = 0; $i < 12; $i++) {
                            $month = date('m', strtotime("-$i months"));
                            $year = date('Y', strtotime("-$i months"));
                            $month_name = date('F Y', strtotime("$year-$month-01"));
                            $selected = ($month == $selected_month && $year == $selected_year) ? 'selected' : '';
                            echo "<option value='$month' data-year='$year' $selected>" . ucfirst($month_name) . "</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>
        </div>
        <?php
        $financial_cards_data = [
            ['titulo' => 'Ingresos', 'valor' => $monthly_revenue_kpi, 'icono' => 'fas fa-arrow-up', 'text_color' => 'text-success-emphasis', 'border_color' => 'border-success', 'link' => '/digitalpremium/pages/ingresos.php'],
            ['titulo' => 'Gastos', 'valor' => $monthly_cost_kpi, 'icono' => 'fas fa-arrow-down', 'text_color' => 'text-danger-emphasis', 'border_color' => 'border-danger', 'link' => '/digitalpremium/pages/egresos.php'],
            ['titulo' => 'Ganancia Neta', 'valor' => $monthly_profit_kpi, 'icono' => 'fas fa-dollar-sign', 'text_color' => ($monthly_profit_kpi >=0 ? 'text-primary-emphasis' : 'text-warning-emphasis'), 'border_color' => ($monthly_profit_kpi >=0 ? 'border-primary' : 'border-warning'), 'link' => '/digitalpremium/pages/reporte_ganancias.php']
        ];
        ?>
        <?php foreach($financial_cards_data as $card): ?>
        <div class="col-lg-4 col-md-6 mb-3">
            <a href="<?php echo $card['link']; ?>" class="card financial-card <?php echo $card['border_color']; ?> h-100 shadow-sm lift text-decoration-none">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <div class="small fw-bold <?php echo $card['text_color']; ?> text-uppercase mb-1"><?php echo $card['titulo']; ?></div>
                            <div class="h4 mb-0 fw-bolder text-dark">
                                <?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($card['valor'], 2); ?>
                            </div>
                        </div>
                        <i class="fas <?php echo $card['icono']; ?> fa-2x <?php echo $card['text_color']; ?> opacity-25"></i>
                    </div>
                </div>
            </a>
        </div>
        <?php endforeach; ?>
    </div>

    <?php if ($previous_revenue_kpi > 0 || $previous_cost_kpi > 0): ?>
    <div class="row g-3 mt-3">
        <div class="col-lg-12">
            <h6 class="mb-3 text-muted fw-light"><i class="fas fa-chart-line me-2"></i>Comparación con Mes Anterior</h6>
        </div>
        <div class="col-lg-4 col-md-6 mb-3">
            <div class="card border-light h-100 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <div class="small fw-bold text-muted text-uppercase mb-1">Mes Anterior</div>
                            <div class="h5 mb-0 fw-bolder text-dark">
                                <?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($previous_revenue_kpi, 2); ?>
                            </div>
                            <small class="text-muted">Ingresos</small>
                        </div>
                        <i class="fas fa-history fa-2x text-muted opacity-25"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6 mb-3">
            <div class="card border-light h-100 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <div class="small fw-bold text-muted text-uppercase mb-1">Mes Anterior</div>
                            <div class="h5 mb-0 fw-bolder text-dark">
                                <?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($previous_cost_kpi, 2); ?>
                            </div>
                            <small class="text-muted">Gastos</small>
                        </div>
                        <i class="fas fa-history fa-2x text-muted opacity-25"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6 mb-3">
            <div class="card border-light h-100 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <div class="small fw-bold text-muted text-uppercase mb-1">Mes Anterior</div>
                            <div class="h5 mb-0 fw-bolder text-dark">
                                <?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($previous_profit_kpi, 2); ?>
                            </div>
                            <small class="text-muted">Ganancia Neta</small>
                        </div>
                        <i class="fas fa-history fa-2x text-muted opacity-25"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($mensaje_para_copiar_al_cliente): ?>
    <div class="modal fade" id="modalMensajePostCompra" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content rounded-4 shadow-lg">
                <div class="modal-header bg-success text-white rounded-top-4">
                    <h5 class="modal-title"><i class="fas fa-check-circle me-2"></i>¡Venta Exitosa!</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body p-4">
                    <p class="lead mb-3 text-dark">Copia el siguiente mensaje para tu cliente:</p>
                    <textarea class="form-control mb-3 rounded-3" id="textoMensajeCliente" rows="10" readonly><?php echo htmlspecialchars($mensaje_para_copiar_al_cliente); ?></textarea>
                    <div class="d-flex justify-content-end align-items-center">
                        <button type="button" class="btn btn-primary me-3" id="btnCopiarMensajeCliente">
                            <i class="fas fa-copy me-2"></i> Copiar Mensaje
                        </button>
                        <small id="mensajeCopiadoFeedback" class="text-success d-none fw-bold"><i class="fas fa-check me-1"></i>¡Copiado!</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if (isset($_GET['mensaje'])): ?>
    <div class="alert alert-<?php echo htmlspecialchars($_GET['tipo'] ?? 'info'); ?> alert-dismissible fade show mt-4" role="alert">
        <?php echo htmlspecialchars(urldecode($_GET['mensaje'])); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
    </div>
    <?php endif; ?>

    <div class="modal fade" id="alertsModal" tabindex="-1" aria-labelledby="alertsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content rounded-4 shadow-lg">
                <div class="modal-header bg-warning text-dark rounded-top-4">
                    <h5 class="modal-title" id="alertsModalLabel"><i class="fas fa-bell me-2"></i> Panel de Alertas Importantes</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <?php if (empty($alerts['clientes_vencidos']) && empty($alerts['clientes_proximos']) && empty($alerts['maestras_vencidas']) && empty($alerts['maestras_proximas'])): ?>
                        <div class="alert alert-success text-center shadow-sm" role="alert">
                            <i class="fas fa-check-circle fa-lg me-2"></i>¡Excelente! No tienes alertas pendientes en este momento.
                        </div>
                    <?php else: ?>
                        <div class="alert-section">
                            <?php if (!empty($alerts['clientes_vencidos'])): ?>
                                <div class="alert alert-danger fade show" role="alert">
                                    <h5 class="alert-title"><i class="icon fas fa-user-times"></i>Clientes Vencidos</h5>
                                    <ul>
                                        <?php foreach ($alerts['clientes_vencidos'] as $alert): ?>
                                            <li>
                                                <div class="alert-item-text">
                                                    <strong><?php echo htmlspecialchars($alert['cliente_nombre']); ?></strong> (<span class="text-muted"><?php echo htmlspecialchars($alert['nombre_plataforma']); ?></span>)
                                                    <br><small>Venció hace <span class="fw-bold"><?php echo abs($alert['dias_restantes']); ?> día(s)</span>.</small>
                                                </div>
                                                <div class="action-buttons">
                                                    <a href="/digitalpremium/pages/perfiles_vendidos_crear.php?editar_id=<?php echo htmlspecialchars($alert['id_perfil_vendido']); ?>" class="btn btn-action btn-outline-danger"><i class="fas fa-edit"></i> Gestionar</a>
                                                    <?php if (!empty($alert['cliente_telefono'])): ?>
                                                    <a href="https://wa.me/<?php echo htmlspecialchars(limpiarNumeroWhatsApp($alert['cliente_telefono'])); ?>?text=<?php echo urlencode(generarMensajeParaCliente($pdo, $alert['id_perfil_vendido'], $id_usuario_sesion, "recordatorio_vencimiento") ?? ''); ?>" target="_blank" class="btn btn-action btn-action-whatsapp"><i class="fab fa-whatsapp"></i> Avisar</a>
                                                    <?php endif; ?>
                                                </div>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($alerts['clientes_proximos'])): ?>
                                <div class="alert alert-warning fade show" role="alert">
                                    <h5 class="alert-title"><i class="icon fas fa-user-clock"></i>Clientes por Vencer</h5>
                                    <ul>
                                        <?php foreach ($alerts['clientes_proximos'] as $alert): ?>
                                            <li>
                                                <div class="alert-item-text">
                                                    <strong><?php echo htmlspecialchars($alert['cliente_nombre']); ?></strong> (<span class="text-muted"><?php echo htmlspecialchars($alert['nombre_plataforma']); ?></span>)
                                                    <br><small>Vence en <span class="fw-bold"><?php echo htmlspecialchars($alert['dias_restantes']); ?> día(s)</span> (<?php echo htmlspecialchars(date("d/m", strtotime($alert['fecha_fin_servicio']))); ?>).</small>
                                                </div>
                                                <div class="action-buttons">
                                                    <a href="/digitalpremium/pages/perfiles_vendidos_crear.php?editar_id=<?php echo htmlspecialchars($alert['id_perfil_vendido']); ?>" class="btn btn-action btn-outline-warning"><i class="fas fa-edit"></i> Gestionar</a>
                                                    <?php if (!empty($alert['cliente_telefono'])): ?>
                                                    <a href="https://wa.me/<?php echo htmlspecialchars(limpiarNumeroWhatsApp($alert['cliente_telefono'])); ?>?text=<?php echo urlencode(generarMensajeParaCliente($pdo, $alert['id_perfil_vendido'], $id_usuario_sesion, "recordatorio_vencimiento") ?? ''); ?>" target="_blank" class="btn btn-action btn-action-whatsapp"><i class="fab fa-whatsapp"></i> Avisar</a>
                                                    <?php endif; ?>
                                                </div>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($alerts['maestras_vencidas'])): ?>
                                <div class="alert alert-danger fade show" role="alert">
                                    <h5 class="alert-title"><i class="icon fas fa-server"></i>Cuentas Maestras Vencidas</h5>
                                    <ul>
                                        <?php foreach ($alerts['maestras_vencidas'] as $alert): ?>
                                            <li>
                                                <div class="alert-item-text">
                                                    <strong><?php echo htmlspecialchars($alert['email_cuenta']); ?></strong> (<span class="text-muted"><?php echo htmlspecialchars($alert['nombre_plataforma']); ?></span>)
                                                    <br><small>Venció hace <span class="fw-bold"><?php echo abs($alert['dias_restantes']); ?> día(s)</span>. Proveedor: <?php echo htmlspecialchars($alert['nombre_proveedor'] ?? 'N/A'); ?></small>
                                                </div>
                                                <div class="action-buttons">
                                                    <a href="/digitalpremium/pages/cuentas_maestras.php?editar_id=<?php echo htmlspecialchars($alert['id_cuenta_maestra']); ?>" class="btn btn-action btn-outline-dark"><i class="fas fa-cog"></i> Revisar</a>
                                                </div>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($alerts['maestras_proximas'])): ?>
                                <div class="alert alert-info fade show" role="alert">
                                    <h5 class="alert-title"><i class="icon fas fa-exclamation-triangle"></i>Cuentas Maestras por Vencer</h5>
                                    <ul>
                                        <?php foreach ($alerts['maestras_proximas'] as $alert): ?>
                                            <li>
                                                <div class="alert-item-text">
                                                    <strong><?php echo htmlspecialchars($alert['email_cuenta']); ?></strong> (<span class="text-muted"><?php echo htmlspecialchars($alert['nombre_plataforma']); ?></span>)
                                                    <br><small>Vence en <span class="fw-bold"><?php echo htmlspecialchars($alert['dias_restantes']); ?> día(s)</span>. Proveedor: <?php echo htmlspecialchars($alert['nombre_proveedor'] ?? 'N/A'); ?></small>
                                                </div>
                                                <div class="action-buttons">
                                                    <a href="/digitalpremium/pages/cuentas_maestras.php?editar_id=<?php echo htmlspecialchars($alert['id_cuenta_maestra']); ?>" class="btn btn-action btn-outline-dark"><i class="fas fa-cog"></i> Revisar</a>
                                                </div>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>


    <section class="filter-search-section mt-5">
        <h4 class="mb-4 fw-bold text-secondary"><i class="fas fa-filter me-2"></i>Opciones de Filtrado y Búsqueda</h4>
        <form action="" method="GET" class="row g-3 align-items-end">
            <div class="col-lg-4 col-md-6">
                <label for="search_query" class="form-label">Buscar (Email, Proveedor, Cliente, Perfil, Teléfono):</label>
                <input type="text" name="search_query" id="search_query" class="form-control" value="<?php echo htmlspecialchars($_GET['search_query'] ?? ''); ?>" placeholder="Buscar en cuentas, perfiles o clientes...">
            </div>
            <div class="col-lg-3 col-md-6">
                <label for="filtro_plataforma" class="form-label">Plataforma:</label>
                <select name="filtro_plataforma" id="filtro_plataforma" class="form-select">
                    <option value="">Todas</option>
                    <?php
                    // Fetch active platforms for the filter dropdown
                    $stmt_plataformas_filter = $pdo->query("SELECT id_plataforma, nombre_plataforma FROM plataformas WHERE estado = 1 ORDER BY nombre_plataforma ASC");
                    $plataformas_activas_filter = $stmt_plataformas_filter->fetchAll(PDO::FETCH_ASSOC);
                    ?>
                    <?php foreach ($plataformas_activas_filter as $plataforma_f): ?>
                        <option value="<?php echo htmlspecialchars($plataforma_f['id_plataforma']); ?>" <?php echo (($_GET['filtro_plataforma'] ?? '') == $plataforma_f['id_plataforma']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($plataforma_f['nombre_plataforma']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-lg-3 col-md-6">
                <label for="filtro_estado" class="form-label">Estado de Cuenta Maestra:</label>
                <select name="filtro_estado" id="filtro_estado" class="form-select">
                    <option value="">Todas</option>
                    <option value="1" <?php echo (isset($_GET['filtro_estado']) && $_GET['filtro_estado'] === '1') ? 'selected' : ''; ?>>Activa</option>
                    <option value="0" <?php echo (isset($_GET['filtro_estado']) && $_GET['filtro_estado'] === '0') ? 'selected' : ''; ?>>Inactiva/Vencida</option>
                    <option value="2" <?php echo (isset($_GET['filtro_estado']) && $_GET['filtro_estado'] === '2') ? 'selected' : ''; ?>>Con Problemas</option>
                </select>
            </div>
            <div class="col-lg-2 col-md-6">
                <div class="form-check pt-lg-4 mt-lg-1">
                    <input class="form-check-input" type="checkbox" name="filtro_perfiles_disponibles" value="si" id="filtro_perfiles_disponibles" <?php echo (($_GET['filtro_perfiles_disponibles'] ?? '') === 'si') ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="filtro_perfiles_disponibles">Solo Perfiles Disponibles</label>
                </div>
            </div>
            <div class="col-12 d-flex align-items-end gap-2 mt-3 filter-actions">
                <button type="submit" class="btn btn-info w-100"><i class="fas fa-search me-1"></i> Aplicar Filtros</button>
                <a href="/digitalpremium/pages/dashboard.php" class="btn btn-outline-secondary w-100"><i class="fas fa-eraser me-1"></i> Limpiar Filtros</a>
            </div>
        </form>
    </section>

    <?php if (empty($grouped_data_display)): ?>
        <div class="alert alert-light text-center mt-4 border shadow-sm"><i class="fas fa-info-circle me-2"></i>No se encontraron cuentas maestras con los filtros aplicados.</div>
    <?php else: ?>
        <?php foreach ($grouped_data_display as $platform_id => $platform_data): ?>
            <section class="platform-group" id="platform-<?php echo htmlspecialchars($platform_id); ?>">
                <div class="platform-header">
                    <span class="platform-icon"><i class="fas <?php echo htmlspecialchars(getPlatformIcon($platform_data['nombre_plataforma'])); ?>"></i></span>
                    <h2><?php echo htmlspecialchars($platform_data['nombre_plataforma']); ?>
                    <?php if (!empty($platform_data['max_perfiles_cuenta'])): ?>
                        <small class="text-muted ms-3">(Máx. <?php echo htmlspecialchars($platform_data['max_perfiles_cuenta']); ?> Perfiles)</small>
                    <?php endif; ?>
                    </h2>
                </div>
                <div class="row g-4">
                    <?php foreach ($platform_data['cuentas'] as $cuenta): ?>
                        <div class="col-xl-4 col-lg-6 col-md-6">
                            <div class="account-card <?php echo getPlatformCardColorClass($cuenta['nombre_plataforma']); ?>">
                                <?php
                                    $account_status_class = 'account-status-active';
                                    $account_status_text = 'Activa';
                                    if ($cuenta['estado_cuenta'] == 0) {
                                        $account_status_class = 'account-status-inactive';
                                        $account_status_text = 'Inactiva/Vencida';
                                    } elseif ($cuenta['estado_cuenta'] == 2) {
                                        $account_status_class = 'account-status-problem';
                                        $account_status_text = 'Con Problemas';
                                    }
                                ?>
                                <span class="account-status-badge <?php echo $account_status_class; ?>"><?php echo $account_status_text; ?></span>

                                <div class="card-header">
                                    <span class="text-truncate" title="<?php echo htmlspecialchars($cuenta['email_cuenta']); ?>"><?php echo htmlspecialchars($cuenta['email_cuenta']); ?></span>
                                    <div class="d-flex align-items-center gap-2">
                                        <a href="/digitalpremium/pages/cuentas_maestras.php?editar_id=<?php echo htmlspecialchars($cuenta['id_cuenta_maestra']); ?>" class="btn-icon" data-bs-toggle="tooltip" title="Configurar Cuenta"><i class="fas fa-cog"></i></a>
                                        <?php if ($rol_usuario_sesion !== 'cortes'): ?>
                                        <button type="button" class="btn btn-sm btn-light text-success rounded-pill"
                                            data-bs-toggle="modal" data-bs-target="#modalRenovarCuenta"
                                            data-id="<?php echo $cuenta['id_cuenta_maestra']; ?>"
                                            data-info="<?php echo htmlspecialchars($cuenta['email_cuenta']); ?>"
                                            title="Renovar Cuenta Maestra">
                                            <i class="fas fa-sync-alt"></i> Renovar
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="account-details">
                                        <div class="detail-item">
                                            <span>Vencimiento:</span> 
                                            <strong>
                                                <?php echo !empty($cuenta['fecha_vencimiento_proveedor']) ? date("d/m/Y", strtotime($cuenta['fecha_vencimiento_proveedor'])) : 'N/A'; ?>
                                            </strong>
                                        </div>
                                        <div class="account-expiry-bar-container">
                                            <?php
                                                $dias_vencimiento_cuenta = $cuenta['dias_restantes_cm'];
                                                $expiry_progress_value = 100;
                                                $expiry_progress_class = 'bg-success';
                                                $expiry_text_status = '';

                                                if ($cuenta['estado_cuenta'] == 1) { // Only calculate for active accounts
                                                    if ($dias_vencimiento_cuenta < 0) {
                                                        $expiry_text_status = 'Vencida hace ' . abs($dias_vencimiento_cuenta) . ' día(s)';
                                                        $expiry_progress_class = 'bg-danger';
                                                        $expiry_progress_value = 0;
                                                    } elseif ($dias_vencimiento_cuenta == 0) {
                                                        $expiry_text_status = 'Vence HOY';
                                                        $expiry_progress_class = 'bg-danger';
                                                        $expiry_progress_value = 5;
                                                    } elseif ($dias_vencimiento_cuenta <= $dias_alerta_maestras) {
                                                        $expiry_text_status = 'Vence en ' . $dias_vencimiento_cuenta . ' día(s)';
                                                        $expiry_progress_class = 'bg-warning';
                                                        $expiry_progress_value = max(5, ($dias_vencimiento_cuenta / $dias_alerta_maestras) * 100);
                                                    } else {
                                                        $expiry_text_status = 'Activa';
                                                        $expiry_progress_class = 'bg-success';
                                                        $max_days_for_full_bar = 30;
                                                        $expiry_progress_value = min(100, ($dias_vencimiento_cuenta / $max_days_for_full_bar) * 100);
                                                    }
                                                } else { // Inactive or Problem state
                                                    $expiry_text_status = $cuenta['estado_cuenta'] == 0 ? 'Inactiva' : 'Con Problemas';
                                                    $expiry_progress_class = 'bg-secondary';
                                                    $expiry_progress_value = 100;
                                                }
                                            ?>
                                            <div class="d-flex justify-content-between small text-muted mb-1">
                                                <span>Estado Vencimiento:</span>
                                                <span class="fw-bold <?php echo ($expiry_progress_class == 'bg-danger' ? 'text-danger' : ($expiry_progress_class == 'bg-warning' ? 'text-warning' : 'text-success')); ?>"><?php echo $expiry_text_status; ?></span>
                                            </div>
                                            <div class="progress" title="<?php echo $expiry_text_status; ?>" data-bs-toggle="tooltip">
                                                <div class="progress-bar <?php echo $expiry_progress_class; ?>" role="progressbar" style="width: <?php echo $expiry_progress_value; ?>%;" aria-valuenow="<?php echo $expiry_progress_value; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                            </div>
                                        </div>
                                        <div class="detail-item mt-3">
                                            <span>Contraseña:</span>
                                            <div class="password-wrapper">
                                                <input type="password" readonly class="form-control-plaintext p-0 border-0 fw-bold text-dark" id="password-display-<?php echo $cuenta['id_cuenta_maestra']; ?>" value="<?php echo htmlspecialchars($cuenta['password_cuenta']); ?>" style="width: 100%;">
                                                <i class="fas fa-eye toggle-password-btn" title="Mostrar/Ocultar Contraseña" data-bs-toggle="tooltip" onclick="togglePasswordVisibility('password-display-<?php echo $cuenta['id_cuenta_maestra']; ?>', this)"></i>
                                                <i class="fas fa-copy copy-btn" title="Copiar Contraseña" data-bs-toggle="tooltip" onclick="copyToClipboard('#password-display-<?php echo $cuenta['id_cuenta_maestra']; ?>', this)"></i>
                                            </div>
                                        </div>
                                        <div class="detail-item"><span>Proveedor:</span> <strong><?php echo htmlspecialchars($cuenta['nombre_proveedor'] ?? 'N/A'); ?></strong></div>
                                        <div class="detail-item"><span>Costo Compra:</span> <strong><?php echo htmlspecialchars($moneda_simbolo) . number_format((float)$cuenta['costo_compra'], 2); ?></strong></div>
                                        <div class="detail-item"><span>Ingresos Generados:</span> <strong><?php echo htmlspecialchars($moneda_simbolo) . number_format($cuenta['total_sales_price'], 2); ?></strong></div>
                                        <div class="detail-item">
                                            <span>Ganancia Actual:</span>
                                            <strong class="profit-display <?php echo ($cuenta['current_profit'] < 0) ? 'negative' : ''; ?>">
                                                <?php echo htmlspecialchars($moneda_simbolo) . number_format($cuenta['current_profit'], 2); ?>
                                            </strong>
                                        </div>
                                    </div>

                                    <div class="profiles-list-wrapper">
                                        <h6 class="small fw-bold text-uppercase text-muted mb-3"><i class="fas fa-user-tag me-2"></i>Perfiles Asignados (<span class="text-primary"><?php echo $cuenta['perfiles_total'] - $cuenta['perfiles_disponibles']; ?></span> / <?php echo $cuenta['perfiles_total']; ?>)</h6>
                                        <?php if (empty($cuenta['perfiles'])): ?>
                                            <div class="text-center text-muted py-3 px-2 border rounded-3 bg-light"><small>No hay perfiles asignados a esta cuenta.</small></div>
                                        <?php else: ?>
                                            <div class="profiles-list">
                                            <?php foreach ($cuenta['perfiles'] as $perfil): ?>
                                                <?php
                                                    $today = new DateTime();
                                                    $finish_dt = !empty($perfil['fecha_fin_servicio']) ? new DateTime($perfil['fecha_fin_servicio']) : null;
                                                    $dias_restantes_val = ($finish_dt) ? (int)$today->diff($finish_dt)->format('%r%a') : null;

                                                    $status_badge_class_profile = 'status-badge-profile active';
                                                    $status_text_profile = 'Activa';
                                                    $profile_status_dot_class = 'profile-status-active';

                                                    if ($perfil['estado_suscripcion'] != 1) {
                                                        $status_badge_class_profile = 'status-badge-profile inactive';
                                                        $status_text_profile = 'Inactiva';
                                                        $profile_status_dot_class = 'profile-status-inactive';
                                                    } elseif ($dias_restantes_val !== null && $dias_restantes_val <= 0) {
                                                        $status_badge_class_profile = 'status-badge-profile expired';
                                                        $status_text_profile = 'Vencida';
                                                        $profile_status_dot_class = 'profile-status-expired';
                                                    } elseif ($dias_restantes_val !== null && $dias_restantes_val <= $dias_alerta_clientes) {
                                                        $status_badge_class_profile = 'status-badge-profile expiring';
                                                        $status_text_profile = 'Por Vencer';
                                                        $profile_status_dot_class = 'profile-status-expiring';
                                                    }
                                                ?>
                                                <div class="profile-item">
                                                    <div class="profile-status <?php echo $profile_status_dot_class; ?>"></div>
                                                    <div class="profile-info">
                                                        <strong class="text-truncate" title="<?php echo htmlspecialchars($perfil['nombre_perfil_cliente']); ?>"><?php echo htmlspecialchars($perfil['nombre_perfil_cliente']); ?> <span class="<?php echo $status_badge_class_profile; ?>"><?php echo $status_text_profile; ?></span></strong>
                                                        <small class="text-truncate">
                                                            Cliente: <?php echo htmlspecialchars($perfil['nombre_cliente']); ?>
                                                            <?php if (!empty($perfil['cliente_telefono'])): ?>
                                                                | Tel: <?php echo htmlspecialchars($perfil['cliente_telefono']); ?>
                                                            <?php endif; ?>
                                                            <?php if (!empty($perfil['pin_perfil_cliente'])): ?>
                                                                | PIN: <?php echo htmlspecialchars($perfil['pin_perfil_cliente']); ?>
                                                            <?php endif; ?>
                                                            <br>Vence: <?php echo htmlspecialchars(date("d/m/Y", strtotime($perfil['fecha_fin_servicio']))); ?>  </small>
                                                    </div>
                                                    <div class="profile-actions">
                                                        <a href="/digitalpremium/pages/perfiles_vendidos_crear.php?editar_id=<?php echo htmlspecialchars($perfil['id_perfil_vendido']); ?>" class="btn-icon" data-bs-toggle="tooltip" title="Editar Perfil"><i class="fas fa-edit"></i></a>
                                                        <?php if (!empty($perfil['cliente_telefono']) && $perfil['estado_suscripcion'] == 1 && ($dias_restantes_val <= 0 || $dias_restantes_val <= $dias_alerta_clientes)): ?>
                                                        <a href="https://wa.me/<?php echo htmlspecialchars(limpiarNumeroWhatsApp($perfil['cliente_telefono'])); ?>?text=<?php echo urlencode(generarMensajeParaCliente($pdo, $perfil['id_perfil_vendido'], $id_usuario_sesion, "recordatorio_vencimiento") ?? ''); ?>" target="_blank" class="btn-icon" data-bs-toggle="tooltip" title="Contactar por WhatsApp (Cobro)"><i class="fab fa-whatsapp"></i></a>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <div class="progress-bar-container pt-3 border-top mt-auto"> <?php
                                            $perfiles_usados = $cuenta['perfiles_total'] - $cuenta['perfiles_disponibles'];
                                            $porcentaje_uso = $cuenta['perfiles_total'] > 0 ? ($perfiles_usados / $cuenta['perfiles_total']) * 100 : 0;
                                            $progress_color_class = 'bg-info';
                                            if ($porcentaje_uso >= 80) $progress_color_class = 'bg-warning';
                                            if ($porcentaje_uso >= 100) $progress_color_class = 'bg-danger';
                                        ?>
                                        <div class="d-flex justify-content-between small text-muted mb-1">
                                            <span>Uso de Perfiles</span>
                                            <span><?php echo $perfiles_usados; ?> de <?php echo $cuenta['perfiles_total']; ?></span>
                                        </div>
                                        <div class="progress"><div class="progress-bar <?php echo $progress_color_class; ?>" role="progressbar" style="width: <?php echo $porcentaje_uso; ?>%;" aria-valuenow="<?php echo $porcentaje_uso; ?>" aria-valuemin="0" aria-valuemax="100"></div></div>
                                    </div>
                                </div>
                                <div class="card-footer">
                                    <div class="d-grid">
                                        <a href="/digitalpremium/pages/perfiles_vendidos_crear.php?id_cuenta_maestra=<?php echo htmlspecialchars($cuenta['id_cuenta_maestra']); ?>" class="btn btn-sm btn-outline-primary <?php echo ($cuenta['perfiles_disponibles'] > 0 && $cuenta['estado_cuenta'] == 1) ? '' : 'disabled'; ?>">
                                            <i class="fas fa-plus me-1"></i> Vender/Asignar Nuevo Perfil
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </section>
        <?php endforeach; ?>
    <?php endif; ?>

    <div class="modal fade" id="modalRenovarCuenta" tabindex="-1" aria-labelledby="modalRenovarCuentaLabel" aria-hidden="true" data-bs-backdrop="static">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content rounded-4 shadow-lg">
                <div class="modal-header bg-success text-white border-0 rounded-top-4">
                    <h5 class="modal-title" id="modalRenovarCuentaLabel"><i class="fas fa-sync-alt me-2"></i>Renovar Cuenta Maestra</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="/digitalpremium/actions/cuentas_maestras_controlador.php" method="POST">
                    <div class="modal-body p-4">
                        <input type="hidden" name="accion" value="renovar">
                        <input type="hidden" name="id_cuenta_maestra" id="id_cuenta_maestra_renew">
                        <p class="mb-3 text-dark">Vas a renovar la cuenta: <strong id="info_cuenta_renew" class="text-primary"></strong>.</p>
                        <p class="mb-3 text-muted">Esto la marcará como 'Activa' y actualizará su fecha de vencimiento.</p>
                        <div class="mb-3">
                            <label for="fecha_vencimiento_renew" class="form-label fw-semibold">Nueva Fecha de Vencimiento <span class="text-danger">*</span></label>
                            <input type="date" class="form-control rounded-3" id="fecha_vencimiento_renew" name="fecha_vencimiento_proveedor" required>
                        </div>
                        <div class="mb-3">
                            <label for="costo_compra_renew" class="form-label fw-semibold">Nuevo Costo (<?php echo htmlspecialchars($moneda_simbolo); ?>)</label>
                            <input type="number" step="0.01" class="form-control rounded-3" id="costo_compra_renew" name="costo_compra" placeholder="0.00">
                            <small class="form-text text-muted">Deja en blanco si el costo no cambia.</small>
                        </div>
                    </div>
                    <div class="modal-footer d-flex justify-content-between p-3 border-top-0">
                        <button type="button" class="btn btn-outline-secondary rounded-pill" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-success rounded-pill"><i class="fas fa-check-circle me-2"></i>Confirmar Renovación</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</div> <?php include_once '../includes/footer.php'; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Initialize Tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });

        // Logic for the post-purchase modal
        var modalEl = document.getElementById('modalMensajePostCompra');
        if (modalEl) {
            var modal = new bootstrap.Modal(modalEl);
            modal.show();
            var btnCopiar = document.getElementById('btnCopiarMensajeCliente');
            var textarea = document.getElementById('textoMensajeCliente');
            var feedback = document.getElementById('mensajeCopiadoFeedback');
            if (btnCopiar && textarea) {
                btnCopiar.addEventListener('click', function() {
                    navigator.clipboard.writeText(textarea.value).then(() => {
                        feedback.classList.remove('d-none');
                        setTimeout(() => feedback.classList.add('d-none'), 2000);
                    }).catch(err => console.error('Error al copiar: ', err));
                });
            }
        }

        // Logic for the Renew Master Account modal
        const modalRenovarCuenta = document.getElementById('modalRenovarCuenta');
        if(modalRenovarCuenta) {
            modalRenovarCuenta.addEventListener('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const idCuentaMaestra = button.getAttribute('data-id');
                const infoCuenta = button.getAttribute('data-info');
                
                document.getElementById('id_cuenta_maestra_renew').value = idCuentaMaestra;
                document.getElementById('info_cuenta_renew').textContent = infoCuenta;

                let today = new Date();
                let futureDate = new Date();
                futureDate.setMonth(today.getMonth() + 1);
                document.getElementById('fecha_vencimiento_renew').value = futureDate.toISOString().split('T')[0];
            });
        }

        // Remove URL parameters after some time
        if (window.location.search.includes('mensaje=')) {
            setTimeout(() => {
                const url = new URL(window.location.href);
                url.searchParams.delete('mensaje');
                url.searchParams.delete('tipo');
                window.history.replaceState({}, '', url);
            }, 5000);
        }

        // Sticky Platform Headers
        const platformHeaders = document.querySelectorAll('.platform-header');
        const observerOptions = {
            rootMargin: '-10px 0px 0px 0px',
            threshold: [0, 0.5, 1]
        };

        const headerObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.boundingClientRect.top <= 10 && entry.intersectionRatio < 1) {
                    entry.target.classList.add('scrolled');
                } else {
                    entry.target.classList.remove('scrolled');
                }
            });
        }, observerOptions);

        platformHeaders.forEach(header => {
            headerObserver.observe(header);
        });
    });

    // Universal copyToClipboard function
    function copyToClipboard(selectorOrText, element) {
        let textToCopy;
        let targetInput = null;

        if (typeof selectorOrText === 'string' && selectorOrText.startsWith('#')) {
            targetInput = document.querySelector(selectorOrText);
            if (targetInput) {
                if (targetInput.tagName === 'INPUT' || targetInput.tagName === 'TEXTAREA') {
                    textToCopy = targetInput.value;
                } else {
                    textToCopy = targetInput.innerText;
                }
            } else {
                console.error('Elemento no encontrado para copiar:', selectorOrText);
                return;
            }
        } else {
            textToCopy = selectorOrText;
        }

        if (!textToCopy) return;

        navigator.clipboard.writeText(textToCopy).then(() => {
            const tooltip = bootstrap.Tooltip.getInstance(element);
            const originalTitle = element.getAttribute('data-bs-original-title');
            
            if (tooltip) {
                element.setAttribute('data-bs-original-title', '¡Copiado!');
                tooltip.show();
                setTimeout(() => {
                    tooltip.hide();
                    setTimeout(() => { element.setAttribute('data-bs-original-title', originalTitle); }, 150);
                }, 1000);
            } else {
                const originalIconClass = element.className;
                element.className = 'fas fa-check text-success';
                setTimeout(() => {
                    element.className = originalIconClass;
                }, 1000);
            }
        }).catch(err => console.error('Error al copiar: ', err));
    }

    // Universal togglePasswordVisibility function
    function togglePasswordVisibility(inputId, iconElement) {
        const input = document.getElementById(inputId);
        if (!input) return;

        if (input.type === 'password') {
            input.type = 'text';
            iconElement.classList.remove('fa-eye');
            iconElement.classList.add('fa-eye-slash');
            iconElement.setAttribute('data-bs-original-title', 'Ocultar Contraseña');
        } else {
            input.type = 'password';
            iconElement.classList.remove('fa-eye-slash');
            iconElement.classList.add('fa-eye');
            iconElement.setAttribute('data-bs-original-title', 'Mostrar Contraseña');
        }
        const tooltip = bootstrap.Tooltip.getInstance(iconElement);
        if (tooltip) {
            tooltip.update();
        } else {
            new bootstrap.Tooltip(iconElement);
        }
    }

    // Selector de mes para finanzas
    document.addEventListener('DOMContentLoaded', function() {
        const mesSelector = document.getElementById('mesSelector');
        if (mesSelector) {
            mesSelector.addEventListener('change', function() {
                const selectedMonth = this.value;
                const selectedYear = this.options[this.selectedIndex].getAttribute('data-year');
                
                const url = new URL(window.location);
                url.searchParams.set('mes', selectedMonth);
                url.searchParams.set('año', selectedYear);
                
                window.location.href = url.toString();
            });
        }
    });
</script>
</body>
</html>