<?php
// FILE: /digitalpremium/pages/dashboard3.php

// Enable error display for debugging (COMMENT OUT OR REMOVE IN PRODUCTION!)
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 = "Dashboard de Cobranza y Rentabilidad - DigitalPremium";
include_once '../includes/header.php';

// --- SESSION DATA ---
$id_usuario_sesion = $_SESSION['id_usuario'];
$rol_usuario_sesion = $_SESSION['rol'];
$nombre_usuario_sesion = $_SESSION['nombre_usuario'] ?? 'Usuario';

// --- CONFIGURATION LOADING ---
$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);

// --- Helper Functions ---
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';
}

// --- Dynamic user filter clause for SQL queries ---
$user_filter_params = ($rol_usuario_sesion !== 'superadmin') ? [':id_usuario_sesion' => $id_usuario_sesion] : [];

function getUserFilterClause(string $alias, string $rol_usuario_sesion): string {
    return ($rol_usuario_sesion !== 'superadmin') ? " AND {$alias}.id_usuario = :id_usuario_sesion" : "";
}


// --- KPI Calculations ---
$sql_clientes = "SELECT COUNT(*) FROM clientes c WHERE c.estado_cliente = 1" . getUserFilterClause('c', $rol_usuario_sesion);
$stmt = $pdo->prepare($sql_clientes);
$stmt->execute($user_filter_params);
$total_clientes_activos = $stmt->fetchColumn() ?? 0;

$sql_perfiles = "SELECT COUNT(*) FROM perfiles_vendidos pv WHERE pv.estado_suscripcion = 1 AND pv.fecha_fin_servicio >= CURDATE()" . getUserFilterClause('pv', $rol_usuario_sesion);
$stmt = $pdo->prepare($sql_perfiles);
$stmt->execute($user_filter_params);
$total_perfiles_activos = $stmt->fetchColumn() ?? 0;

$sql_cuentas_m_kpi = "SELECT COUNT(*) FROM cuentas_maestras cm WHERE cm.estado_cuenta = 1 AND cm.fecha_vencimiento_proveedor >= CURDATE()" . getUserFilterClause('cm', $rol_usuario_sesion);
$stmt = $pdo->prepare($sql_cuentas_m_kpi);
$stmt->execute($user_filter_params);
$total_cuentas_maestras_activas = $stmt->fetchColumn() ?? 0;

$sql_total_adeudado = "
    SELECT COALESCE(SUM(pv.precio_venta), 0)
    FROM perfiles_vendidos pv
    WHERE pv.estado_suscripcion = 1
      AND pv.fecha_fin_servicio < CURDATE()
      AND pv.precio_venta > 0
    " . getUserFilterClause('pv', $rol_usuario_sesion);
$stmt_total_adeudado = $pdo->prepare($sql_total_adeudado);
$stmt_total_adeudado->execute($user_filter_params);
$total_monto_adeudado = $stmt_total_adeudado->fetchColumn() ?? 0;


// --- KPI CALCULATIONS FOR CURRENT MONTH (FINANCIAL) ---
$current_month_kpi = date('m');
$current_year_kpi = date('Y');
$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
];
if ($rol_usuario_sesion !== 'superadmin') {
    $monthly_params_kpi[':id_usuario_sesion'] = $id_usuario_sesion;
}

$sql_monthly_revenue_kpi = "
    SELECT COALESCE(SUM(pv.precio_venta), 0)
    FROM perfiles_vendidos pv
    WHERE MONTH(pv.fecha_inicio_servicio) = :current_month
      AND YEAR(pv.fecha_inicio_servicio) = :current_year
    " . getUserFilterClause('pv', $rol_usuario_sesion);
$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();

$sql_monthly_cost_kpi = "
    SELECT COALESCE(SUM(cm.costo_compra), 0)
    FROM cuentas_maestras cm
    WHERE MONTH(cm.fecha_compra_proveedor) = :current_month
      AND YEAR(cm.fecha_compra_proveedor) = :current_year
    " . getUserFilterClause('cm', $rol_usuario_sesion);
$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;

$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;
}

$sql_previous_revenue_kpi = "
    SELECT COALESCE(SUM(pv.precio_venta), 0)
    FROM perfiles_vendidos pv
    WHERE MONTH(pv.fecha_inicio_servicio) = :previous_month
      AND YEAR(pv.fecha_inicio_servicio) = :previous_year
    " . getUserFilterClause('pv', $rol_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();

$sql_previous_cost_kpi = "
    SELECT COALESCE(SUM(cm.costo_compra), 0)
    FROM cuentas_maestras cm
    WHERE MONTH(cm.fecha_compra_proveedor) = :previous_month
      AND YEAR(cm.fecha_compra_proveedor) = :previous_year
    " . getUserFilterClause('cm', $rol_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;


// --- Data for "Cuentas por Cobrar" list ---
$sql_overdue_clients = "
    SELECT
        pv.id_perfil_vendido, pv.nombre_perfil_cliente, pv.fecha_fin_servicio, pv.precio_venta,
        p.nombre_plataforma, c.nombre_completo AS cliente_nombre, c.telefono AS cliente_telefono,
        DATEDIFF(CURDATE(), pv.fecha_fin_servicio) as dias_atrasados
    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 pv.estado_suscripcion = 1
      AND pv.fecha_fin_servicio < CURDATE()
    " . getUserFilterClause('pv', $rol_usuario_sesion) . "
    ORDER BY dias_atrasados DESC
";
$stmt_overdue_clients = $pdo->prepare($sql_overdue_clients);
$stmt_overdue_clients->execute($user_filter_params);
$overdue_clients = $stmt_overdue_clients->fetchAll(PDO::FETCH_ASSOC);


// --- Data for "Rentabilidad de Cuentas Maestras" ---
$cm_profit_where_clauses = [];
$cm_profit_params = [];

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

// Add optional filters from GET parameters for profitability section
if (!empty($_GET['filtro_plataforma_profit'])) { $cm_profit_where_clauses[] = "p.id_plataforma = :id_plataforma_profit"; $cm_profit_params[':id_plataforma_profit'] = $_GET['filtro_plataforma_profit']; }
if (isset($_GET['filtro_estado_profit']) && ($_GET['filtro_estado_profit'] !== '')) { $cm_profit_where_clauses[] = "cm.estado_cuenta = :estado_cuenta_profit"; $cm_profit_params[':estado_cuenta_profit'] = $_GET['filtro_estado_profit']; }
if (($_GET['filtro_perfiles_disponibles_profit'] ?? '') === 'si') { $cm_profit_where_clauses[] = "cm.perfiles_disponibles > 0"; }

// LÓGICA DE FILTRADO CORREGIDA para incluir el teléfono del cliente
if (!empty($_GET['search_query_profit'])) {
    $search_query_param_profit = '%' . trim($_GET['search_query_profit']) . '%';
    $cm_profit_where_clauses[] = "(cm.email_cuenta LIKE :search_query_profit_email OR cm.nombre_proveedor LIKE :search_query_profit_proveedor OR p.nombre_plataforma LIKE :search_query_profit_plataforma OR pv.nombre_perfil_cliente LIKE :search_query_profit_perfil OR c.nombre_completo LIKE :search_query_profit_cliente OR c.telefono LIKE :search_query_profit_telefono)";
    $cm_profit_params[':search_query_profit_email'] = $search_query_param_profit;
    $cm_profit_params[':search_query_profit_proveedor'] = $search_query_param_profit;
    $cm_profit_params[':search_query_profit_plataforma'] = $search_query_param_profit;
    $cm_profit_params[':search_query_profit_perfil'] = $search_query_param_profit;
    $cm_profit_params[':search_query_profit_cliente'] = $search_query_param_profit;
    $cm_profit_params[':search_query_profit_telefono'] = $search_query_param_profit;
}

$cm_profit_sql_where = !empty($cm_profit_where_clauses) ? " WHERE " . implode(" AND ", $cm_profit_where_clauses) : "";


$sql_master_account_profitability = "
    SELECT
        cm.id_cuenta_maestra, cm.email_cuenta, cm.costo_compra, cm.perfiles_total, cm.perfiles_disponibles,
        cm.estado_cuenta, cm.fecha_vencimiento_proveedor, cm.nombre_proveedor,
        p.id_plataforma, p.nombre_plataforma, p.max_perfiles_cuenta,
        COALESCE(SUM(pv.precio_venta), 0) AS total_revenue_generated,
        DATEDIFF(cm.fecha_vencimiento_proveedor, CURDATE()) as dias_restantes_cm,
        GROUP_CONCAT(
            DISTINCT
            CASE WHEN pv.estado_suscripcion != 2 THEN
                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, '')
                )
            ELSE NULL END
            ORDER BY pv.nombre_perfil_cliente ASC SEPARATOR '###'
        ) AS perfiles_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
    {$cm_profit_sql_where}
    GROUP BY
        cm.id_cuenta_maestra, cm.email_cuenta, cm.costo_compra, cm.perfiles_total, cm.perfiles_disponibles,
        cm.estado_cuenta, cm.fecha_vencimiento_proveedor, cm.nombre_proveedor, p.id_plataforma, p.nombre_plataforma, p.max_perfiles_cuenta
    ORDER BY
        total_revenue_generated DESC, cm.perfiles_disponibles DESC
";

$stmt_master_account_profitability = $pdo->prepare($sql_master_account_profitability);
$stmt_master_account_profitability->execute($cm_profit_params);
$master_accounts_profitability_data = $stmt_master_account_profitability->fetchAll(PDO::FETCH_ASSOC);

$total_plataformas_con_activas = 0;

$grouped_profitability_data = [];
foreach ($master_accounts_profitability_data as $cm) {
    if (!isset($cm['id_plataforma']) || $cm['id_plataforma'] === null) {
        error_log("Warning: Master account with email " . ($cm['email_cuenta'] ?? 'N/A') . " has a missing or NULL id_plataforma. Skipping for display.");
        continue;
    }

    if (!isset($grouped_profitability_data[$cm['id_plataforma']])) {
        $grouped_profitability_data[$cm['id_plataforma']] = [
            'nombre_plataforma' => $cm['nombre_plataforma'],
            'cuentas' => []
        ];
    }

    $cm['net_profit'] = $cm['total_revenue_generated'] - (float)$cm['costo_compra'];
    $cm['profiles_sold'] = $cm['perfiles_total'] - $cm['perfiles_disponibles'];

    $profiles_for_master_account = [];
    if (!empty($cm['perfiles_data'])) {
        $profiles_raw = explode('###', $cm['perfiles_data']);
        foreach ($profiles_raw as $p_data) {
            $parts = explode('|', $p_data);
            if (count($parts) === 9) {
                $profiles_for_master_account[] = [
                    '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' => (float)$parts[5],
                    'estado_suscripcion' => (int)$parts[6],
                    'nombre_cliente' => (string)$parts[7],
                    'cliente_telefono' => (string)$parts[8]
                ];
            }
        }
    }
    $cm['perfiles'] = $profiles_for_master_account;
    $grouped_profitability_data[$cm['id_plataforma']]['cuentas'][] = $cm;
}


$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']);
}

$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 failed to initialize: " . intl_get_error_message());
    }
} else {
    $fecha_actual_formateada = date('d/m/Y');
    error_log("PHP intl extension is not enabled.");
}
?>

<!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 */

            --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); }
        .kpi-card.kpi-danger-light { background: #e04b4b; } /* A softer red for debt KPI */


        /* --- 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 (for Profitability section) --- */
        .platform-group {
            position: relative;
            margin-bottom: 3rem;
        }
        .platform-header {
            display: flex;
            align-items: center;
            gap: 1.5rem;
            padding: 2rem;
            margin-bottom: 2.5rem;
            border: 2px solid var(--primary-color);
            position: -webkit-sticky;
            position: sticky;
            top: 0;
            z-index: 100;
            background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 50%, #e3f2fd 100%);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            border-radius: 24px;
            backdrop-filter: blur(10px);
        }
        .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-header:hover {
            transform: translateY(-4px);
            box-shadow: 0 16px 48px rgba(0, 0, 0, 0.15);
            border-color: var(--primary-dark);
        }

                .platform-icon {
            width: 72px; 
            height: 72px; 
            border-radius: 50%;
            display: flex; 
            align-items: center; 
            justify-content: center;
            background: linear-gradient(145deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            color: white;
            font-size: 2.75rem;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
            flex-shrink: 0;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            border: 3px solid rgba(255, 255, 255, 0.3);
        }
        
        .platform-icon:hover {
            transform: scale(1.15) rotate(5deg);
            box-shadow: 0 12px 32px rgba(0, 0, 0, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
        }
        .platform-header h2 {
            font-size: 2.5rem;
            font-weight: 900;
            color: var(--primary-color);
            margin-bottom: 0.5rem;
            text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            letter-spacing: -0.02em;
        }
        .platform-header h2 small {
            font-size: 1rem;
            font-weight: 600;
            color: #6c757d;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Mejoras adicionales para las cards */
        .account-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .account-card:hover::before {
            opacity: 1;
        }
        
        /* Mejora para los badges de estado */
        .badge {
            font-weight: 600;
            letter-spacing: 0.03em;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        /* Mejora para el scrollbar de perfiles */
        .profiles-list::-webkit-scrollbar-thumb {
            background: linear-gradient(180deg, #c2c8d0 0%, #9da5b0 100%);
            border-radius: 10px;
        }
        
        .profiles-list::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(180deg, #9da5b0 0%, #6c757d 100%);
        }

                /* --- Master Account Card (for Profitability section) --- */
        .account-card {
            border: 1px solid var(--border-color);
            border-radius: 16px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex; 
            flex-direction: column;
            height: 100%;
            overflow: hidden;
            position: relative;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            padding-top: 2.5rem; /* Space for the status badge */
            min-height: 380px; /* Reduced minimum height */
            backdrop-filter: blur(5px);
        }
        .account-card:hover {
            transform: translateY(-4px) scale(1.01);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
            border-color: var(--primary-color);
        }
        
        /* 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; }


        /* 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.7rem;
            font-weight: 700;
            padding: 0.4em 1em;
            border-radius: 0 0 12px 12px; /* Rounded bottom only */
            z-index: 3; /* Ensure it's on top */
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            text-transform: uppercase;
            letter-spacing: 0.03em;
            backdrop-filter: blur(5px);
        }
        .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: 1rem;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        
        .card-header.bg-primary {
            background: var(--primary-color) !important;
            border: none;
            color: white;
        }
        
        .card-header .email-container {
            overflow: hidden;
        }
        
        .card-header .email-container span {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
            color: white !important;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        
        .card-header .email-container i {
            color: white !important;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        
        /* Asegurar que el email sea visible */
        .card-header .email-container span,
        .card-header .email-container strong,
        .card-header .email-container div {
            color: white !important;
        }
        
        /* Mejorar contraste del header */
        .card-header.bg-primary {
            background: var(--primary-color) !important;
            border: none;
            color: white;
            box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
        }
        
        .btn-icon.btn-light {
            background: rgba(255, 255, 255, 0.95) !important;
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: var(--primary-color) !important;
        }
        
        .btn-icon.btn-light:hover {
            background: white !important;
            border-color: white;
            transform: scale(1.03);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }
        .account-details {
            font-size: 0.9rem;
            margin-bottom: 0;
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            padding: 1rem;
            border-radius: 12px;
            border: 1px solid #e9ecef;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
        }
                .account-details .detail-item {
            display: flex; 
            justify-content: space-between;
            margin-bottom: 0.75rem;
            color: var(--text-muted);
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f3f4;
            transition: all 0.2s ease;
        }
        
        .account-details .detail-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        
        .account-details .detail-item:hover {
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: 8px;
            padding-left: 0.5rem;
            padding-right: 0.5rem;
            margin-left: -0.5rem;
            margin-right: -0.5rem;
        }
        .account-details .detail-item span:first-child { 
            font-weight: 600; 
            color: #495057; 
            font-size: 0.85rem;
        }
        .account-details .detail-item strong {
            color: #212529;
            font-weight: 700;
            font-size: 0.95rem;
        }
        .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); }
        
        .profitability-metrics {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            border: 1px solid #e9ecef;
            border-radius: 12px;
            box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.05);
        }
        
        .metrics-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 0.75rem;
        }
        
        .metrics-grid .metric-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 1rem;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 8px;
            border: 1px solid #e9ecef;
            transition: all 0.2s ease;
            margin: 0;
        }
        
        .metrics-grid .metric-item:hover {
            transform: translateX(3px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            border-color: var(--primary-color);
            background: linear-gradient(135deg, #ffffff 0%, #e3f2fd 100%);
        }
        
        .metric-label {
            font-weight: 600;
            color: #495057;
            font-size: 0.85rem;
            display: flex;
            align-items: center;
        }
        
        .metric-value {
            font-weight: 700;
            font-size: 1rem;
            text-align: right;
            min-width: 70px;
        }
        
        .metric-item {
            transition: all 0.3s ease;
            padding: 0.5rem 0;
            border-radius: 8px;
            margin: 0.25rem 0;
        }
        
        .metric-item:hover {
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 12px;
            padding: 0.75rem 1rem;
            margin: 0 -0.5rem;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transform: translateX(5px);
        }

        /* Account Expiry Progress Bar */
        .account-expiry-bar-container {
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 2px solid #e9ecef;
            position: relative;
        }
        
        .account-expiry-bar-container::before {
            content: '';
            position: absolute;
            top: -1px;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, #e9ecef 0%, #dee2e6 50%, #e9ecef 100%);
            border-radius: 1px;
        }
        .account-expiry-bar-container .progress {
            height: 12px; /* Thicker progress bar */
            background-color: #f8f9fa; /* Lighter background for progress track */
            border-radius: 999px;
            margin-top: 8px;
            box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
            border: 1px solid #e9ecef;
        }
        .account-expiry-bar-container .progress-bar {
            font-weight: 600;
            font-size: 0.75rem;
            line-height: 12px;
            border-radius: 999px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        /* --- Client Profile Cards within Master Account Cards --- */
        .profiles-list-wrapper { 
            margin-top: 1.25rem; 
            flex-grow: 1; 
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            padding: 1rem;
            border-radius: 12px;
            border: 1px solid #e9ecef;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
        }
        .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.75rem;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            margin-bottom: 0.5rem;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border: 1px solid #e9ecef;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
            transition: all 0.2s ease;
            position: relative;
        }
        .profile-item:hover {
            transform: translateY(-2px) scale(1.01);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            border-color: var(--primary-color);
            background: linear-gradient(135deg, #ffffff 0%, #f0f8ff 100%);
        }
        .profile-status {
            width: 12px; 
            height: 12px;
            border-radius: 50%;
            flex-shrink: 0;
            border: 2px solid white;
            box-shadow: 0 0 0 2px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .profile-item:hover .profile-status {
            transform: scale(1.2);
            box-shadow: 0 0 0 3px rgba(0,0,0,0.15);
        }
        .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.9rem;
            font-weight: 700;
            color: var(--primary-color);
            display: block;
            margin-bottom: 0.2rem;
            line-height: 1.2;
        }
        .profile-info small {
            font-size: 0.8rem;
            color: #6c757d;
            display: block;
            line-height: 1.3;
            font-weight: 500;
        }
        .status-badge-profile {
            padding: 0.3em 0.8em;
            font-size: 0.7rem;
            font-weight: 700;
            border-radius: 50px;
            text-transform: uppercase;
            display: inline-block;
            margin-left: 0.75rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            transition: all 0.2s ease;
        }
        .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: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border: 1px solid #e9ecef;
            color: #6c757d;
            width: 32px; 
            height: 32px;
            border-radius: 50%;
            display: inline-flex; 
            align-items: center; 
            justify-content: center;
            transition: all 0.2s ease;
            font-size: 1rem;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
        }
        .btn-icon:hover {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            color: white;
            border-color: var(--primary-color);
            transform: translateY(-1px) scale(1.03);
            box-shadow: 0 4px 12px rgba(var(--primary-color-rgb, 0, 123, 255), 0.25);
        }
        .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;
        }

        /* NEW: Styles for Overdue Clients list */
        .overdue-client-item {
            background-color: var(--bs-danger-soft);
            border: 1px solid var(--danger-color);
            border-radius: var(--border-radius-md);
            padding: 0.8rem 1rem;
            margin-bottom: 0.75rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            transition: var(--transition-base);
            box-shadow: var(--shadow-sm);
        }
        .overdue-client-item:last-child {
            margin-bottom: 0;
        }
        .overdue-client-item:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
            background-color: rgba(var(--danger-color), 0.1);
        }
        .overdue-client-info strong {
            color: var(--bs-danger-emphasis);
            font-size: 1rem;
            display: block;
        }
        .overdue-client-info small {
            color: var(--bs-danger-emphasis);
            opacity: 0.8;
            font-size: 0.85rem;
            display: block;
        }
        .overdue-client-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: 0.5rem; /* Adjust for wrap */
        }
        .overdue-client-actions .btn {
            font-size: 0.8rem;
            padding: 0.4rem 0.75rem;
        }

        /* NEW: Styles for Profitability metrics within account cards */
        .profitability-metrics {
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px dashed var(--border-color); /* Changed to dashed for more distinction */
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.9rem;
            color: var(--text-dark);
        }
        .profitability-metrics .metric-item span:first-child {
            color: var(--text-muted);
            font-size: 0.85rem;
        }
        .profitability-metrics .metric-item strong {
            font-size: 1rem;
            display: block;
            font-weight: 600;
        }
        .profitability-metrics .metric-item.positive strong { color: var(--success-color); }
        .profitability-metrics .metric-item.negative strong { color: var(--danger-color); }
        .profitability-metrics .metric-item.neutral strong { color: var(--info-color); } /* For zero or balanced profit */


        /* Responsive Adjustments (ensure new elements also adapt) */
        @media (max-width: 991.98px) {
            .overdue-client-actions {
                width: 100%;
                justify-content: flex-end;
            }
        }
        @media (max-width: 767.98px) {
            .overdue-client-item {
                flex-direction: column;
                align-items: flex-start;
            }
            .overdue-client-actions {
                margin-top: 0.75rem;
                justify-content: flex-start;
                width: auto;
            }
            .profitability-metrics {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }
            .profitability-metrics .metric-item strong {
                display: inline-block; /* Keep inline for smaller screens if on separate lines */
                margin-left: 0.5rem;
            }
            
            .platform-header {
                flex-direction: column;
                text-align: center;
                gap: 1rem;
            }
            
            .platform-header .d-flex {
                flex-direction: column;
                gap: 1rem;
            }
            
            .account-card {
                min-height: 350px;
            }
            
            .account-card .card-header {
                flex-direction: column;
                gap: 0.5rem;
                text-align: center;
            }
        }
        @media (max-width: 575.98px) {
            .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; }
        }

    </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-chart-line me-2"></i>Dashboard de Finanzas
            </h1>
            <p class="text-muted fs-6 mb-0">
                Bienvenido a **<?php echo htmlspecialchars($nombre_negocio); ?>**. Gestiona tus cobranzas y rentabilidad.
            </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 btn-warning position-relative" data-bs-toggle="modal" data-bs-target="#modalCuentasPorCobrar">
                <i class="fas fa-hand-holding-dollar me-2"></i> Cuentas por Cobrar
                <?php if ($total_monto_adeudado > 0): ?>
                    <span class="alert-badge-count bg-danger"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($total_monto_adeudado, 2); ?></span>
                <?php endif; ?>
            </button>
            <a href="/digitalpremium/pages/dashboard.php" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-2"></i> Volver al Panel Principal
            </a>
            <a href="/digitalpremium/pages/perfiles_vendidos_crear.php" class="btn btn-primary">
                <i class="fas fa-plus-circle me-2"></i> Nueva Venta
            </a>
        </div>
    </header>

    <div class="modal fade" id="modalCuentasPorCobrar" tabindex="-1" aria-labelledby="modalCuentasPorCobrarLabel" 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-danger text-white rounded-top-4">
                    <h5 class="modal-title" id="modalCuentasPorCobrarLabel"><i class="fas fa-exclamation-triangle me-2"></i>Cuentas por Cobrar (Clientes Vencidos)</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <?php if (empty($overdue_clients)): ?>
                        <div class="alert alert-success text-center shadow-sm py-4" role="alert">
                            <i class="fas fa-check-circle fa-2x d-block mb-2"></i>
                            ¡Excelente! No tienes clientes con pagos pendientes de cobro en este momento.
                        </div>
                    <?php else: ?>
                        <div class="card shadow-sm p-4">
                            <div class="card-body p-0">
                                <?php foreach ($overdue_clients as $client): ?>
                                    <div class="overdue-client-item">
                                        <div class="overdue-client-info">
                                            <strong>Cliente: <?php echo htmlspecialchars($client['cliente_nombre']); ?></strong>
                                            <small>
                                                Perfil: **<?php echo htmlspecialchars($client['nombre_perfil_cliente']); ?>** (<?php echo htmlspecialchars($client['nombre_plataforma']); ?>)<br>
                                                Venció hace **<?php echo $client['dias_atrasados']; ?> día(s)** | Monto: <span class="fw-bold text-danger"><?php echo $moneda_simbolo . number_format($client['precio_venta'], 2); ?></span>
                                                <?php if (!empty($client['cliente_telefono'])): ?>
                                                    <br>Teléfono: <?php echo htmlspecialchars($client['cliente_telefono']); ?>
                                                <?php endif; ?>
                                            </small>
                                        </div>
                                        <div class="overdue-client-actions">
                                            <button type="button" class="btn btn-sm btn-danger"
                                                data-bs-toggle="modal" data-bs-target="#modalRenovarPerfil"
                                                data-id="<?php echo htmlspecialchars($client['id_perfil_vendido']); ?>"
                                                data-client-name="<?php echo htmlspecialchars($client['cliente_nombre']); ?>"
                                                data-platform-name="<?php echo htmlspecialchars($client['nombre_plataforma']); ?>"
                                                data-profile-name="<?php echo htmlspecialchars($client['nombre_perfil_cliente']); ?>"
                                                data-price="<?php echo htmlspecialchars($client['precio_venta']); ?>"
                                                title="Cobrar o Renovar este perfil">
                                                <i class="fas fa-hand-holding-dollar me-1"></i> Cobrar / Renovar
                                            </button>
                                            <?php if (!empty($client['cliente_telefono'])): ?>
                                                <a href="https://wa.me/<?php echo htmlspecialchars(limpiarNumeroWhatsApp($client['cliente_telefono'])); ?>?text=<?php echo urlencode(generarMensajeParaCliente($pdo, $client['id_perfil_vendido'], $id_usuario_sesion, "recordatorio_vencimiento") ?? ''); ?>" target="_blank" class="btn btn-sm btn-action-whatsapp"><i class="fab fa-whatsapp me-1"></i> WhatsApp</a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row g-3">
        <div class="col-xl-4 col-md-6 mb-3">
            <button type="button" class="card kpi-card kpi-danger-light h-100 shadow-sm lift text-decoration-none" data-bs-toggle="modal" data-bs-target="#modalCuentasPorCobrar">
                <div class="card-body d-flex align-items-center">
                    <div class="kpi-icon-wrapper">
                        <i class="fas fa-hand-holding-dollar"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <div class="kpi-value"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($total_monto_adeudado, 2); ?></div>
                        <div class="kpi-title">Monto Total Adeudado</div>
                    </div>
                </div>
            </button>
        </div>
        <div class="col-xl-4 col-md-6 mb-3">
            <div class="card kpi-card kpi-primary h-100 shadow-sm lift text-decoration-none">
                <div class="card-body d-flex align-items-center">
                    <div class="kpi-icon-wrapper">
                        <i class="fas fa-sack-dollar"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <div class="kpi-value"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($monthly_revenue_kpi, 2); ?></div>
                        <div class="kpi-title">Ingresos Mes Actual</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-4 col-md-6 mb-3">
            <div class="card kpi-card kpi-success h-100 shadow-sm lift text-decoration-none">
                <div class="card-body d-flex align-items-center">
                    <div class="kpi-icon-wrapper">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <div class="kpi-value"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($monthly_profit_kpi, 2); ?></div>
                        <div class="kpi-title">Ganancia Neta Mes Actual</div>
                    </div>
                </div>
            </div>
        </div>
    </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; ?>
    
    <hr>

    <section class="filter-search-section mt-5">
        <h4 class="mb-4 fw-bold text-secondary"><i class="fas fa-filter me-2"></i>Filtros para Rentabilidad de Cuentas Maestras</h4>
        <form action="" method="GET" class="row g-3 align-items-end">
            <div class="col-lg-4 col-md-6">
                <label for="search_query_profit" class="form-label">Buscar (Email, Proveedor, Cliente, Perfil, Teléfono):</label>
                <input type="text" name="search_query_profit" id="search_query_profit" class="form-control" value="<?php echo htmlspecialchars($_GET['search_query_profit'] ?? ''); ?>" placeholder="Buscar en cuentas, perfiles o clientes...">
            </div>
            <div class="col-lg-3 col-md-6">
                <label for="filtro_plataforma_profit" class="form-label">Plataforma:</label>
                <select name="filtro_plataforma_profit" id="filtro_plataforma_profit" class="form-select">
                    <option value="">Todas</option>
                    <?php
                    // Fetch active platforms for the filter dropdown
                    $stmt_plataformas_filter_profit = $pdo->query("SELECT id_plataforma, nombre_plataforma FROM plataformas WHERE estado = 1 ORDER BY nombre_plataforma ASC");
                    $plataformas_activas_filter_profit = $stmt_plataformas_filter_profit->fetchAll(PDO::FETCH_ASSOC);
                    ?>
                    <?php foreach ($plataformas_activas_filter_profit as $plataforma_f): ?>
                        <option value="<?php echo htmlspecialchars($plataforma_f['id_plataforma']); ?>" <?php echo (($_GET['filtro_plataforma_profit'] ?? '') == $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_profit" class="form-label">Estado de Cuenta Maestra:</label>
                <select name="filtro_estado_profit" id="filtro_estado_profit" class="form-select">
                    <option value="">Todas</option>
                    <option value="1" <?php echo (isset($_GET['filtro_estado_profit']) && $_GET['filtro_estado_profit'] === '1') ? 'selected' : ''; ?>>Activa</option>
                    <option value="0" <?php echo (isset($_GET['filtro_estado_profit']) && $_GET['filtro_estado_profit'] === '0') ? 'selected' : ''; ?>>Inactiva/Vencida</option>
                    <option value="2" <?php echo (isset($_GET['filtro_estado_profit']) && $_GET['filtro_estado_profit'] === '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_profit" value="si" id="filtro_perfiles_disponibles_profit" <?php echo (($_GET['filtro_perfiles_disponibles_profit'] ?? '') === 'si') ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="filtro_perfiles_disponibles_profit">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/dashboard3.php" class="btn btn-outline-secondary w-100"><i class="fas fa-eraser me-1"></i> Limpiar Filtros</a>
            </div>
        </form>
    </section>

    <hr>

    <section class="mt-5" id="rentabilidadCuentasMaestrasSection">
        <h3 class="mb-4 section-title"><i class="fas fa-money-bill-trend-up me-2"></i>Rentabilidad de Cuentas Maestras</h3>
        <?php if (empty($grouped_profitability_data)): ?>
            <div class="alert alert-light text-center mt-4 border shadow-sm py-5" role="alert">
                <div class="mb-3">
                    <i class="fas fa-chart-line fa-3x text-muted"></i>
                </div>
                <h4 class="text-muted mb-3">No hay datos para mostrar</h4>
                <p class="text-muted mb-3">No se encontraron cuentas maestras con los filtros aplicados para analizar su rentabilidad.</p>
                <div class="d-flex justify-content-center gap-2">
                    <a href="/digitalpremium/pages/dashboard3.php" class="btn btn-outline-primary">
                        <i class="fas fa-eraser me-2"></i>Limpiar Filtros
                    </a>
                    <a href="/digitalpremium/pages/cuentas_maestras.php" class="btn btn-primary">
                        <i class="fas fa-plus me-2"></i>Agregar Cuenta
                    </a>
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($grouped_profitability_data as $platform_id => $platform_data): ?>
                <section class="platform-group mb-5" id="platform-profitability-<?php echo htmlspecialchars($platform_id); ?>">
                    <div class="platform-header bg-light p-4 rounded-4 border shadow-sm mb-4">
                        <div class="d-flex align-items-center">
                            <span class="platform-icon me-3"><i class="fas <?php echo htmlspecialchars(getPlatformIcon($platform_data['nombre_plataforma'])); ?> fa-2x"></i></span>
                            <div>
                                <h2 class="mb-1"><?php echo htmlspecialchars($platform_data['nombre_plataforma']); ?></h2>
                                <div class="d-flex align-items-center gap-3">
                                    <span class="badge bg-primary fs-6 px-3 py-2">
                                        <i class="fas fa-server me-2"></i><?php
                                            $active_accounts_count = 0;
                                            foreach($platform_data['cuentas'] as $c) {
                                                if ($c['estado_cuenta'] == 1) {
                                                    $active_accounts_count++;
                                                }
                                            }
                                            echo $active_accounts_count;
                                        ?> cuenta(s)
                                    </span>
                                    <span class="badge bg-success fs-6 px-3 py-2">
                                        <i class="fas fa-users me-2"></i><?php 
                                            $total_profiles = 0;
                                            foreach ($platform_data['cuentas'] as $cuenta) {
                                                $total_profiles += $cuenta['profiles_sold'];
                                            }
                                            echo $total_profiles;
                                        ?> perfil(es)
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row g-3 justify-content-start">
                        <?php foreach ($platform_data['cuentas'] as $cuenta): ?>
                            <div class="col-xxl-3 col-xl-4 col-lg-6 col-md-6 col-sm-12 mb-3">
                                <div class="account-card <?php echo getPlatformCardColorClass($cuenta['nombre_plataforma']); ?> h-100">
                                    <?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 d-flex justify-content-between align-items-center p-3 border-bottom bg-primary">
                                        <div class="email-container flex-grow-1 me-2">
                                            <div class="d-flex align-items-center">
                                                <i class="fas fa-envelope me-2 text-white fs-6"></i>
                                                <span class="text-white fw-semibold fs-6" title="<?php echo htmlspecialchars($cuenta['email_cuenta']); ?>">
                                                    <?php echo htmlspecialchars($cuenta['email_cuenta']); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <a href="/digitalpremium/pages/cuentas_maestras.php?editar_id=<?php echo htmlspecialchars($cuenta['id_cuenta_maestra']); ?>" 
                                           class="btn-icon btn-sm btn-light" 
                                           data-bs-toggle="tooltip" 
                                           title="Configurar Cuenta">
                                            <i class="fas fa-cog text-primary"></i>
                                        </a>
                                    </div>
                                    <div class="card-body p-3">
                                        <div class="account-details mb-3">
                                            <div class="detail-item mb-2">
                                                <span class="text-muted"><i class="fas fa-building me-2"></i>Proveedor:</span> 
                                                <strong class="text-dark"><?php echo htmlspecialchars($cuenta['nombre_proveedor'] ?? 'N/A'); ?></strong>
                                            </div>
                                            <div class="detail-item mb-2">
                                                <span class="text-muted"><i class="fas fa-calendar-alt me-2"></i>Vencimiento:</span>
                                                <strong class="text-dark"><?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) {
                                                        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 {
                                                        $expiry_text_status = 'Inactiva';
                                                        $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="profitability-metrics bg-light p-3 rounded-3 border">
                                                <h6 class="text-uppercase text-muted mb-3 fw-bold small text-center">
                                                    <i class="fas fa-chart-line me-2"></i>Métricas de Rentabilidad
                                                </h6>
                                                <div class="metrics-grid">
                                                    <div class="metric-item">
                                                        <div class="metric-label">
                                                            <i class="fas fa-dollar-sign me-2"></i>Costo
                                                        </div>
                                                        <div class="metric-value text-danger">
                                                            <?php echo htmlspecialchars($moneda_simbolo) . number_format((float)$cuenta['costo_compra'], 2); ?>
                                                        </div>
                                                    </div>
                                                    <div class="metric-item">
                                                        <div class="metric-label">
                                                            <i class="fas fa-arrow-up me-2"></i>Ingresos
                                                        </div>
                                                        <div class="metric-value text-success">
                                                            <?php echo htmlspecialchars($moneda_simbolo) . number_format($cuenta['total_revenue_generated'], 2); ?>
                                                        </div>
                                                    </div>
                                                    <div class="metric-item">
                                                        <div class="metric-label">
                                                            <i class="fas fa-trophy me-2"></i>Ganancia
                                                        </div>
                                                        <div class="metric-value <?php echo ($cuenta['net_profit'] < 0) ? 'text-danger' : 'text-success'; ?>">
                                                            <?php echo htmlspecialchars($moneda_simbolo) . number_format($cuenta['net_profit'], 2); ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </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['profiles_sold']; ?></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['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']))); ?>
                                                                | Precio: <?php echo $moneda_simbolo . number_format($perfil['precio_venta'], 2); ?>
                                                            </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>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endforeach; ?>
        <?php endif; ?>
    </section>

    <div class="modal fade" id="modalRenovarPerfil" tabindex="-1" aria-labelledby="modalRenovarPerfilLabel" 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-primary text-white border-0 rounded-top-4">
                    <h5 class="modal-title" id="modalRenovarPerfilLabel"><i class="fas fa-sync-alt me-2"></i>Renovar Suscripción de Cliente</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="/digitalpremium/actions/perfiles_vendidos_controlador.php" method="POST">
                    <div class="modal-body p-4">
                        <input type="hidden" name="accion" value="renovar_desde_dashboard">
                        <input type="hidden" name="id_perfil_vendido" id="id_perfil_vendido_renew">
                        <p class="mb-3 text-dark">Vas a renovar el perfil: <strong id="info_perfil_renew" class="text-primary"></strong>.</p>
                        <p class="mb-3 text-muted">Asegúrate de que el cliente haya realizado el pago antes de confirmar.</p>
                        <div class="mb-3">
                            <label for="fecha_fin_servicio_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_fin_servicio_renew" name="fecha_fin_servicio" required>
                        </div>
                        <div class="mb-3">
                            <label for="precio_venta_renew" class="form-label fw-semibold">Precio de Venta (<?php echo htmlspecialchars($moneda_simbolo); ?>)</label>
                            <input type="number" step="0.01" class="form-control rounded-3" id="precio_venta_renew" name="precio_venta" placeholder="0.00">
                            <small class="form-text text-muted">Deja en blanco si el precio 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 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 Renew Master Account modal
    const modalRenovarCuenta = document.getElementById('modalRenovarCuenta');
    if(modalRenovarCuenta) {
        modalRenovarCuenta.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget; // Button that triggered the modal
            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;

            // Set default renewal date to one month from today
            let today = new Date();
            let futureDate = new Date();
            futureDate.setMonth(today.getMonth() + 1);
            // Format to YYYY-MM-DD
            document.getElementById('fecha_vencimiento_renew').value = futureDate.toISOString().split('T')[0];
        });
    }

    // Logic for Renoving Profiles directly from Dashboard3
    const modalRenovarPerfil = document.getElementById('modalRenovarPerfil');
    if(modalRenovarPerfil) {
        modalRenovarPerfil.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget; // Button that triggered the modal
            const idPerfilVendido = button.getAttribute('data-id');
            const clientName = button.getAttribute('data-client-name');
            const platformName = button.getAttribute('data-platform-name');
            const profileName = button.getAttribute('data-profile-name');
            const precioVenta = button.getAttribute('data-price'); // Get price

            document.getElementById('id_perfil_vendido_renew').value = idPerfilVendido;
            document.getElementById('info_perfil_renew').textContent = `${profileName} (${platformName}) de ${clientName}`;
            document.getElementById('precio_venta_renew').value = precioVenta; // Set price

            // Set default renewal date to one month from today, or from current end date
            let today = new Date();
            let futureDate = new Date();
            futureDate.setMonth(today.getMonth() + 1);
            document.getElementById('fecha_fin_servicio_renew').value = futureDate.toISOString().split('T')[0];
        });
    }

    // Sticky Platform Headers (for profitability section)
    const platformHeaders = document.querySelectorAll('.platform-group .platform-header');
    const observerOptions = {
        rootMargin: '-10px 0px 0px 0px', // Trigger slightly before it hits the very top
        threshold: [0, 0.5, 1] // Observe when 0%, 50%, and 100% is visible
    };

    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);
    });
    
    // 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();
            });
        }
    });

});

// 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);
        }
    }
</script>
</body>
</html>