<?php
// FILE: /digitalpremium/pages/reporte_ganancias.php (VERSIÓN MEJORADA Y CORREGIDA CON DISEÑO V6)

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';

// --- 1. OBTENER DATOS DE SESIÓN ---
$id_usuario_sesion = $_SESSION['id_usuario'];
$rol_usuario_sesion = $_SESSION['rol'];

// --- 2. FUNCIÓN DE CONFIGURACIÓN MULTIUSUARIO ---
if (!function_exists('getConfigValue')) {
    function getConfigValue($key, $id_usuario, $default = null) {
        global $pdo;
        try {
            $stmt = $pdo->prepare("SELECT valor_config FROM configuraciones WHERE clave_config = :key AND id_usuario = :id_usuario");
            $stmt->execute([':key' => $key, ':id_usuario' => $id_usuario]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$result) {
                $stmt = $pdo->prepare("SELECT valor_config FROM configuraciones WHERE clave_config = :key AND id_usuario IS NULL");
                $stmt->execute([':key' => $key]);
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
            }

            return $result ? $result['valor_config'] : $default;
        } catch (PDOException $e) {
            error_log("Error al obtener config value para usuario {$id_usuario} y clave {$key}: " . $e->getMessage());
            return $default;
        }
    }
}

$page_title = "Dashboard de Rentabilidad - DigitalPremium";
include_once '../includes/header.php';

// --- INICIO: CÓDIGO CSS PERSONALIZADO (Integrado para asegurar que funcione) ---
?>
<style>
/* ==========================================================================
           DigitalPremium - Estilos Mejorados V6 (Rediseño Profesional de Perfiles Vendidos Crear y General)
   ========================================================================== */
:root {
    --primary-hue: 240;
    --primary-color: hsl(var(--primary-hue), 70%, 55%);
    --primary-color-dark: hsl(var(--primary-hue), 65%, 45%);
    --primary-color-light: hsl(var(--primary-hue), 70%, 95%);
    --primary-bg-subtle: hsl(var(--primary-hue), 70%, 98%);
    --primary-text-emphasis: hsl(var(--primary-hue), 60%, 30%);
    --primary-gradient: linear-gradient(135deg, hsl(var(--primary-hue), 70%, 50%), hsl(var(--primary-hue), 60%, 65%));
    --secondary-color: #6b7280;
    --success-hue: 145;
    --success-color: hsl(var(--success-hue), 60%, 40%);
    --success-bg-subtle: hsl(var(--success-hue), 60%, 95%);
    --success-text-emphasis: hsl(var(--success-hue), 60%, 25%);
    --info-hue: 200;
    --info-color: hsl(var(--info-hue), 70%, 45%);
    --info-bg-subtle: hsl(var(--info-hue), 70%, 95%);
    --info-text-emphasis: hsl(var(--info-hue), 70%, 28%);
    --warning-hue: 45;
    --warning-color: hsl(var(--warning-hue), 90%, 50%);
    --warning-bg-subtle: hsl(var(--warning-hue), 90%, 95%);
    --warning-text-emphasis: hsl(var(--warning-hue), 70%, 30%);
    --danger-hue: 0;
    --danger-color: hsl(var(--danger-hue), 65%, 50%);
    --danger-bg-subtle: hsl(var(--danger-hue), 65%, 95%);
    --danger-text-emphasis: hsl(var(--danger-hue), 65%, 30%);
    --light-bg: #f8f9fa;
    --content-bg: #ffffff;
    --body-bg: #eef2f6;
    --text-dark: #212529;
    --text-light: #ffffff;
    --text-muted: #6c757d;
    --text-muted-light: #adb5bd;
    --dark-hue: 210;
    --dark-color: hsl(var(--dark-hue), 10%, 23%);
    --dark-bg-subtle: hsl(var(--dark-hue), 10%, 95%);
    --dark-text-emphasis: hsl(var(--dark-hue), 10%, 10%);
    --sidebar-width: 260px;
    --sidebar-bg-start: #1c2b3e;
    --sidebar-bg-end: #2d4059;
    --sidebar-text-color: rgba(255, 255, 255, 0.9);
    --sidebar-icon-color: rgba(255, 255, 255, 0.75);
    --sidebar-link-hover-bg: rgba(255, 255, 255, 0.15);
    --sidebar-link-hover-text: #ffffff;
    --sidebar-link-active-bg: var(--primary-color);
    --sidebar-link-active-text: #ffffff;
    --sidebar-border-active: var(--warning-color);
    --sidebar-submenu-bg: rgba(0, 0, 0, 0.25);
    --sidebar-title-color: rgba(255,255,255,0.55);
    --font-family-base: 'Poppins', sans-serif;
    --base-font-size: 16px;
    
    /* Colores para las cards de KPIs */
    --kpi-ventas-bg: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    --kpi-ventas-border: #10b981;
    --kpi-ventas-text: #065f46;
    
    --kpi-inversion-bg: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
    --kpi-inversion-border: #ef4444;
    --kpi-inversion-text: #991b1b;
    
    --kpi-ganancia-positive-bg: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    --kpi-ganancia-positive-border: #10b981;
    --kpi-ganancia-positive-text: #065f46;
    
    --kpi-ganancia-negative-bg: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
    --kpi-ganancia-negative-border: #ef4444;
    --kpi-ganancia-negative-text: #991b1b;
    --line-height-base: 1.6;
    --border-radius-sm: 0.375rem;
    --border-radius-md: 0.75rem;
    --border-radius-lg: 1.25rem;
    --border-color: #e5e7eb;
    --box-shadow-xs: 0 0 5px rgba(0,0,0,0.05);
    --box-shadow-sm: 0 2px 8px rgba(0,0,0,0.08);
    --box-shadow-md: 0 5px 18px rgba(0,0,0,0.1);
    --box-shadow-lg: 0 12px 35px rgba(0,0,0,0.18);
    --transition-base: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    --mobile-navbar-height: 60px;
    --mobile-navbar-bg: var(--content-bg);
    --mobile-navbar-text-color: var(--primary-color);
    --mobile-navbar-box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
html[data-theme='dark'] {
    --light-bg: #2a313c;
    --content-bg: #1e2530;
    --body-bg: #141920;
    --text-dark: #e9ecef;
    --text-light: #141920;
    --text-muted: #8892b0;
    --text-muted-light: #5d687e;
    --border-color: #343f50;
    --box-shadow-xs: 0 0 5px rgba(0,0,0,0.15);
    --box-shadow-sm: 0 2px 8px rgba(0,0,0,0.25);
    --box-shadow-md: 0 5px 18px rgba(0,0,0,0.3);
    --box-shadow-lg: 0 12px 35px rgba(0,0,0,0.4);
    --primary-bg-subtle: hsla(var(--primary-hue), 70%, 50%, 0.15);
    --primary-text-emphasis: hsl(var(--primary-hue), 70%, 80%);
    --success-bg-subtle: hsla(var(--success-hue), 60%, 40%, 0.15);
    --success-text-emphasis: hsl(var(--success-hue), 60%, 75%);
    --info-bg-subtle: hsla(var(--info-hue), 70%, 45%, 0.15);
    --info-text-emphasis: hsl(var(--info-hue), 70%, 75%);
    --warning-bg-subtle: hsla(var(--warning-hue), 90%, 50%, 0.15);
    --warning-text-emphasis: hsl(var(--warning-hue), 90%, 75%);
    --danger-bg-subtle: hsla(var(--danger-hue), 65%, 50%, 0.15);
    --danger-text-emphasis: hsl(var(--danger-hue), 65%, 80%);
    --dark-bg-subtle: hsla(var(--dark-hue), 10%, 80%, 0.15);
    --dark-text-emphasis: hsl(var(--dark-hue), 10%, 85%);
    --mobile-navbar-bg: var(--content-bg);
    --modal-footer-bg: var(--body-bg);
    --scrollbar-track-bg: #202731;
    --scrollbar-thumb-bg: #4a5464;
    --scrollbar-thumb-hover-bg: #5d687e;
}
.bg-primary-soft { background-color: var(--primary-bg-subtle) !important; }
.text-primary-emphasis { color: var(--primary-text-emphasis) !important; }
.bg-success-soft { background-color: var(--success-bg-subtle) !important; }
.text-success-emphasis { color: var(--success-text-emphasis) !important; }
.bg-info-soft { background-color: var(--info-bg-subtle) !important; }
.text-info-emphasis { color: var(--info-text-emphasis) !important; }
.bg-warning-soft { background-color: var(--warning-bg-subtle) !important; }
.text-warning-emphasis { color: var(--warning-text-emphasis) !important; }
.bg-danger-soft { background-color: var(--danger-bg-subtle) !important; }
.text-danger-emphasis { color: var(--danger-text-emphasis) !important; }
.bg-dark-soft { background-color: var(--dark-bg-subtle) !important; }
.text-dark-emphasis { color: var(--text-dark-emphasis) !important; }
html[data-theme='dark'] .bg-light-subtle { background-color: rgba(255, 255, 255, 0.05) !important; }
.bg-light-subtle { background-color: #fcfcfd !important; }
*, *::before, *::after { box-sizing: border-box; }
html { scroll-behavior: smooth; font-size: var(--base-font-size); }
body {
    font-family: var(--font-family-base);
    line-height: var(--line-height-base);
    color: var(--text-dark);
    background-color: var(--body-bg);
    margin: 0;
    display: flex;
    min-height: 100vh;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    overflow-x: hidden;
    transition: background-color 0.3s ease, color 0.3s ease;
}
body.sidebar-mobile-open { overflow: hidden; }
.sidebar {
    width: var(--sidebar-width);
    background-image: linear-gradient(180deg, var(--sidebar-bg-start) 0%, var(--sidebar-bg-end) 100%);
    color: var(--sidebar-text-color);
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1050;
    display: flex;
    flex-direction: column;
    box-shadow: 3px 0 15px -5px rgba(0,0,0,0.4);
    transition: var(--transition-base);
}
.sidebar-header {
    padding: 1.25rem 1rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.18);
    min-height: var(--mobile-navbar-height);
    display: flex;
    align-items: center;
    justify-content: center;
}
@media (max-width: 991.98px) {
    .sidebar-header {
        display: none;
        padding: 0;
        min-height: 0;
        border-bottom: none;
    }
}
.sidebar-logo-link {
    color: var(--text-light);
    font-size: 1.8rem;
    font-family: var(--font-family-base);
    font-weight: 700;
    text-decoration: none;
    display: flex;
    align-items: center;
    transition: opacity 0.2s ease;
    letter-spacing: 0.5px;
}
.sidebar-logo-link:hover { opacity: 0.9; color: var(--text-light); }
.sidebar-logo-icon { margin-right: 0.85rem; font-size: 2.2rem; opacity: 0.95; }
.sidebar-logo-text { letter-spacing: 0.5px; }
.sidebar-nav {
    flex-grow: 1;
    overflow-y: auto;
    padding: 0.5rem 0;
}
.sidebar .nav-item-title {
    padding: 1.2rem 1.5rem 0.6rem;
    font-size: 0.75rem;
    font-weight: 700;
    color: var(--sidebar-title-color);
    text-transform: uppercase;
    letter-spacing: 0.12em;
    border-bottom: 1px dashed rgba(255,255,255,0.15);
    margin-bottom: 0.6rem;
}
.sidebar .nav-link {
    color: var(--sidebar-text-color);
    padding: 0.95rem 1.5rem;
    font-size: 0.98rem;
    font-weight: 500;
    border-left: 5px solid transparent;
    transition: var(--transition-base);
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;
    text-decoration: none;
}
.sidebar .nav-link::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background-color: var(--sidebar-link-hover-bg);
    transition: left 0.35s ease-in-out;
    z-index: -1;
}
.sidebar .nav-link:hover::before { left: 0; }
.sidebar .nav-link i.fas, .sidebar .nav-link i.far {
    width: 22px;
    margin-right: 1.1rem;
    font-size: 1.2em;
    color: var(--sidebar-icon-color);
    transition: var(--transition-base);
    text-align: center;
}
.sidebar .nav-link span { transition: transform 0.25s ease; }
.sidebar .nav-link:hover { color: var(--sidebar-link-hover-text); }
.sidebar .nav-link:hover i.fas, .sidebar .nav-link:hover i.far { color: var(--sidebar-link-hover-text); }
.sidebar .nav-link:hover span { transform: translateX(6px); }
.sidebar .nav-link.active, .sidebar .nav-link.active-parent {
    background-color: var(--sidebar-link-active-bg);
    color: var(--sidebar-link-active-text);
    font-weight: 600;
    border-left-color: var(--sidebar-border-active);
    box-shadow: inset 0 0 12px rgba(0,0,0,0.3);
}
.sidebar .nav-link.active i.fas, .sidebar .nav-link.active i.far,
.sidebar .nav-link.active-parent i.fas, .sidebar .nav-link.active-parent i.far {
    color: var(--sidebar-link-active-text);
}
.sidebar .nav-link .arrow-icon {
    transition: transform 0.3s ease;
    margin-left: auto;
    font-size: 0.9em;
}
.sidebar .nav-link[aria-expanded="true"] .arrow-icon { transform: rotate(180deg); }
.sidebar .sub-menu {
    background-color: var(--sidebar-submenu-bg);
    padding-left: 0;
    list-style: none;
    padding-top: 0.6rem;
    padding-bottom: 0.6rem;
    border-top: 1px solid rgba(255,255,255,0.08);
}
.sidebar .sub-menu .nav-link {
    padding-left: calc(1.5rem + 22px + 1.1rem);
    font-size: 0.9rem;
    font-weight: 400;
    border-left: none;
    color: rgba(255,255,255,0.75);
}
.sidebar .sub-menu .nav-link::before {
    content: '—';
    left: 1.7rem;
    font-size: 1em;
    color: var(--sidebar-icon-color);
}
.sidebar .sub-menu .nav-link:hover::before, .sidebar .sub-menu .nav-link.active::before {
    color: var(--sidebar-link-active-text);
}
.sidebar .sub-menu .nav-link:hover {
    background-color: rgba(255,255,255,0.08);
    color: #ffffff;
}
.sidebar .sub-menu .nav-link.active {
    background-color: transparent;
    color: var(--sidebar-link-active-text) !important;
    font-weight: 500;
}
.sidebar .sub-menu .nav-link i.fas { display: none; }
.sidebar-footer {
    padding: 0.85rem 0;
    margin-top: auto;
    border-top: 1px solid rgba(255, 255, 255, 0.18);
    flex-shrink: 0;
}
.sidebar-divider {
    margin: 0.85rem 1.5rem;
    border-color: rgba(255, 255, 255, 0.15);
}
.sidebar .logout-link {
    color: var(--sidebar-text-color);
    padding: 0.95rem 1.5rem;
    font-size: 0.98rem;
    font-weight: 500;
    transition: var(--transition-base);
    display: flex;
    align-items: center;
    text-decoration: none;
    background-color: rgba(220, 53, 69, 0.2);
    border-radius: var(--border-radius-md);
    margin: 0 1.5rem;
    justify-content: center;
    box-shadow: var(--box-shadow-xs);
}
.sidebar .logout-link:hover {
    background-color: var(--danger-color);
    color: var(--text-light);
    transform: translateY(-3px);
    box-shadow: var(--box-shadow-sm);
}
.sidebar .logout-link i.fas {
    width: 22px;
    margin-right: 1.1rem;
    color: rgba(255, 255, 255, 0.8);
    transition: var(--transition-base);
}
.sidebar .logout-link:hover i.fas { color: var(--text-light); }
.mobile-top-navbar {
    background: var(--primary-gradient);
    height: var(--mobile-navbar-height);
    padding: 0 1rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1040;
    box-shadow: var(--box-shadow-md);
    color: white;
}
.sidebar-toggle-btn-mobile {
    font-size: 1.6rem;
    color: white;
    background-color: transparent;
    border: none;
    padding: 0.5rem;
    cursor: pointer;
    transition: transform 0.2s ease;
}
.sidebar-toggle-btn-mobile:hover { transform: scale(1.1); }
.mobile-navbar-brand {
    font-family: var(--font-family-base);
    font-size: 1.5rem;
    font-weight: 700;
    color: white;
    text-decoration: none;
    display: flex;
    align-items: center;
}
.mobile-navbar-brand i.fas { margin-right: 0.7rem; font-size: 1.3em; opacity: 0.9; }
.main-content {
    margin-left: var(--sidebar-width);
    width: calc(100% - var(--sidebar-width));
    padding: 1.5rem;
    background-color: var(--body-bg);
    transition: margin-left 0.3s ease-in-out, background-color 0.3s ease;
    overflow-y: auto;
    height: 100vh;
    padding-top: 1.5rem;
}
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
    padding-bottom: 1.5rem;
    border-bottom: 1px solid var(--border-color);
    transition: border-color 0.3s ease;
}
.page-header .page-title {
    font-size: 2.2rem;
    font-weight: 700;
    color: var(--text-dark);
    margin-bottom: 0;
    transition: color 0.3s ease;
}
.page-header .page-title i {
    margin-right: 1rem;
    font-size: 1.2em;
    color: var(--primary-color);
}
.page-header .btn {
    font-size: 1rem;
    padding: 0.7rem 1.4rem;
    font-weight: 600;
    border-radius: var(--border-radius-md);
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}
.card {
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius-lg);
    box-shadow: var(--box-shadow-md);
    margin-bottom: 1.75rem;
    background-color: var(--content-bg);
    overflow: hidden;
    transition: var(--transition-base);
}
html[data-theme='light'] .card { border: none; }
.card-header {
    background-color: var(--primary-bg-subtle);
    border-bottom: 1px solid var(--border-color);
    padding: 1.2rem 1.8rem;
    font-weight: 600;
    color: var(--text-dark);
    font-size: 1.15rem;
    transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
}
.card-header h1, .card-header h2, .card-header h3,
.card-header h4, .card-header h5, .card-header h6 {
    margin-bottom: 0;
    font-size: inherit;
    font-weight: 600;
    color: inherit;
}
.card-header i.fas, .card-header i.far {
    margin-right: 0.8rem;
    color: var(--text-muted);
    font-size: 1.1em;
}
.card-body { padding: 1.8rem; }
.table {
    margin-bottom: 0;
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
}
.table thead th {
    background-color: var(--light-bg);
    color: var(--text-muted);
    border-bottom: 2px solid var(--border-color);
    font-weight: 600;
    text-transform: uppercase;
    font-size: 0.8rem;
    letter-spacing: 0.08em;
    padding: 0.9rem 1.2rem;
    vertical-align: middle;
    transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
}
.table tbody td {
    padding: 0.8rem 1.2rem;
    vertical-align: middle;
    border-top: 1px solid var(--border-color);
    color: var(--text-dark);
    font-size: 0.95rem;
    transition: border-color 0.3s ease, color 0.3s ease;
}
.table tbody tr:first-child td { border-top: none; }
.table-hover tbody tr:hover { background-color: var(--primary-bg-subtle); }
.card-body > .table:first-child:not(.no-border-radius) {
    border-top-left-radius: var(--border-radius-lg);
    border-top-right-radius: var(--border-radius-lg);
}
.card-body > .table:last-child:not(.no-border-radius) {
    border-bottom-left-radius: var(--border-radius-lg);
    border-bottom-right-radius: var(--border-radius-lg);
}
.table .badge {
    font-size: 0.85rem;
    padding: 0.4em 0.7em;
    font-weight: 600;
    border-radius: var(--border-radius-md);
}
.table.table-compact th, .table.table-compact td { font-size: 0.9rem; padding: 0.75rem 0.9rem; vertical-align: middle; }
.table.table-x-compact th, .table.table-x-compact td { font-size: 0.82rem; padding: 0.4rem 0.6rem !important; white-space: nowrap; vertical-align: middle; }
.table.table-x-compact .badge { font-size: 0.78rem; padding: 0.25em 0.5em; font-weight: 500; }
.table.table-x-compact .btn-group-sm > .btn, .table.table-x-compact .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.8rem; }
.table.table-x-compact .btn i.fas, .table.table-x-compact .btn i.fab { font-size: 0.9em; vertical-align: middle; }
.truncate-text { max-width: 280px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: inline-block; vertical-align: middle; cursor: help; }
.truncate-email-short { max-width: 180px; }
.form-label {
    font-weight: 500;
    margin-bottom: 0.5rem;
    font-size: 0.95rem;
    color: var(--text-dark);
}
.form-control, .form-select {
    font-size: 1rem;
    border-radius: var(--border-radius-md);
    border: 1px solid var(--border-color);
    padding: 0.75rem 1rem;
    transition: var(--transition-base);
    background-color: var(--content-bg);
    color: var(--text-dark);
}
.form-control-sm, .form-select-sm {
    font-size: 0.9rem;
    border-radius: var(--border-radius-sm);
    padding: 0.5rem 0.8rem;
}
.form-control:focus, .form-select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 0.25rem hsla(var(--primary-hue), 70%, 55%, 0.25);
    outline: none;
    background-color: var(--content-bg);
}
.input-group-text {
    background-color: var(--light-bg);
    border: 1px solid var(--border-color);
    color: var(--text-muted);
    padding: 0.75rem 1rem;
    border-radius: var(--border-radius-md) 0 0 var(--border-radius-md);
    font-size: 1rem;
    transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
}
.input-group .form-control,
.input-group .form-select { border-radius: var(--border-radius-md); }
.input-group .form-control:not(:first-child),
.input-group .form-select:not(:first-child) {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}
.input-group .btn { border-radius: 0 var(--border-radius-md) var(--border-radius-md) 0; }
.modal-header {
    background-color: var(--primary-color);
    border-bottom: 1px solid var(--border-color);
    padding: 1.5rem 2rem;
    color: white;
    border-top-left-radius: var(--border-radius-lg);
    border-top-right-radius: var(--border-radius-lg);
}
.modal-header .modal-title { font-weight: 600; font-size: 1.5rem; }
.modal-header .btn-close {
    filter: invert(1) brightness(2);
    opacity: 0.9;
}
.modal-content {
    border-radius: var(--border-radius-lg);
    border: 1px solid var(--border-color);
    box-shadow: var(--box-shadow-lg);
    background-color: var(--content-bg);
    transition: background-color 0.3s ease, border-color 0.3s ease;
}
.modal-body { padding: 2rem; }
.modal-footer {
    padding: 1.5rem 2rem;
    border-top: 1px solid var(--border-color);
    background-color: var(--light-bg);
    border-bottom-left-radius: var(--border-radius-lg);
    border-bottom-right-radius: var(--border-radius-lg);
    transition: background-color 0.3s ease, border-color 0.3s ease;
}
.modal-lg { max-width: 960px; }
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(135deg, #2c3e50 0%, #1a2536 100%);
    padding: 1.5rem;
}
.login-box {
    background: var(--content-bg);
    padding: 3.5rem;
    border-radius: var(--border-radius-lg);
    box-shadow: var(--box-shadow-lg);
    width: 100%;
    max-width: 500px;
    text-align: center;
    position: relative;
    overflow: hidden;
}
.login-box::before, .login-box::after {
    content: '';
    position: absolute;
    border-radius: 50%;
    pointer-events: none;
    filter: blur(40px);
    opacity: 0.4;
}
.login-box::before {
    top: -80px; left: -80px;
    width: 160px; height: 160px;
    background: radial-gradient(circle, var(--primary-color) 0%, transparent 70%);
}
.login-box::after {
    bottom: -80px; right: -80px;
    width: 160px; height: 160px;
    background: radial-gradient(circle, var(--success-color) 0%, transparent 70%);
}
.login-box .login-logo {
    font-size: 2.8rem;
    font-weight: 800;
    color: var(--primary-color);
    margin-bottom: 1.2rem;
    display: block;
    text-decoration: none;
    letter-spacing: 1.5px;
}
.login-box .login-logo i { margin-right: 0.8rem; font-size: 1.1em; }
.login-box .login-box-msg {
    margin-bottom: 3rem;
    font-size: 1.15rem;
    color: var(--text-muted);
}
.login-box .form-control {
    height: auto;
    padding: 0.95rem 1.4rem;
    font-size: 1.05rem;
    margin-bottom: 1.8rem;
    border-radius: var(--border-radius-md);
}
.login-box .btn {
    padding: 0.95rem 2rem;
    font-size: 1.15rem;
    font-weight: 600;
    border-radius: var(--border-radius-md);
    background-color: var(--primary-color);
    border-color: var(--primary-color);
    transition: var(--transition-base);
}
.login-box .btn:hover {
    background-color: var(--primary-color-dark);
    border-color: var(--primary-color-dark);
    box-shadow: var(--box-shadow-sm);
    transform: translateY(-2px);
}
.login-box .form-check-label { color: var(--text-muted); }
.login-box .social-auth-links { margin-top: 2rem; }
.login-box .social-auth-links a.btn { font-size: 0.95rem; padding: 0.7rem 1.2rem; }
.lift { transition: var(--transition-base); }
.lift:hover { transform: translateY(-8px); box-shadow: var(--box-shadow-lg) !important; }
::-webkit-scrollbar { width: 12px; height: 12px; }
::-webkit-scrollbar-track { background: var(--body-bg); border-radius: 6px; }
::-webkit-scrollbar-thumb { background: var(--text-muted); border-radius: 6px; }
::-webkit-scrollbar-thumb:hover { background: var(--secondary-color); }
html[data-theme='dark'] ::-webkit-scrollbar-track { background: var(--scrollbar-track-bg, var(--body-bg)); }
html[data-theme='dark'] ::-webkit-scrollbar-thumb { background: var(--scrollbar-thumb-bg, var(--text-muted)); }
html[data-theme='dark'] ::-webkit-scrollbar-thumb:hover { background: var(--scrollbar-thumb-hover-bg, var(--secondary-color)); }
.sidebar-nav::-webkit-scrollbar { width: 8px; }
.sidebar-nav::-webkit-scrollbar-track { background: rgba(0,0,0,0.1); }
.sidebar-nav::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.3); border-radius: 4px; }
.sidebar-nav::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.5); }
@media (max-width: 991.98px) {
    :root { 
        --sidebar-width: 280px;
        --base-font-size: 15px;
    }
    body { padding-top: var(--mobile-navbar-height); }
    .sidebar {
        transform: translateX(calc(-1 * var(--sidebar-width)));
        height: calc(100vh - var(--mobile-navbar-height));
        top: var(--mobile-navbar-height);
        box-shadow: none;
    }
    .sidebar.expanded {
        transform: translateX(0);
        box-shadow: 0.25rem 0 1.5rem rgba(0,0,0,0.3);
    }
    .main-content {
        margin-left: 0;
        width: 100%;
        padding: 1rem;
        height: calc(100vh - var(--mobile-navbar-height));
        padding-top: 1rem;
    }
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .page-header .page-title {
        margin-bottom: 0.75rem;
        font-size: 1.8rem;
    }
    .page-header .btn {
        width: 100%;
        margin-top: 0.5rem;
    }
    .card-body form.row > [class*="col-md-"],
    .card-body form.row > [class*="col-lg-"] { margin-bottom: 1rem; }
    .card-body form.row > [class*="col-md-"]:last-child,
    .card-body form.row > [class*="col-lg-"]:last-child { margin-bottom: 0; }
    .card-body form.row .d-flex.justify-content-end {
        flex-direction: column;
        gap: 0.75rem;
    }
    .card-body form.row .d-flex.justify-content-end .btn {
        width: 100%;
        margin-right: 0 !important;
    }
    .login-box { margin: 1rem; padding: 2.5rem; }
    .login-box .login-logo { font-size: 2.2rem; }
    .login-box .login-box-msg { font-size: 1.05rem; margin-bottom: 1.5rem; }
    .login-box .form-control { padding: 0.75rem 1rem; font-size: 1rem; margin-bottom: 1rem; }
    .login-box .btn { padding: 0.75rem 1.5rem; font-size: 1rem; }
}
.rounded-pill { border-radius: 50rem !important; }
.shadow-sm { box-shadow: var(--box-shadow-sm) !important; }
.shadow-md { box-shadow: var(--box-shadow-md) !important; }
.shadow-lg { box-shadow: var(--box-shadow-lg) !important; }
.shadow-xs { box-shadow: var(--box-shadow-xs) !important; }
.btn.icon-left {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}
.alerts-button {
    background-color: var(--warning-color);
    border-color: var(--warning-color);
    color: var(--text-dark);
    font-weight: 600;
    transition: var(--transition-base);
    box-shadow: var(--box-shadow-sm);
}
.alerts-button:hover {
    background-color: var(--warning-text-emphasis);
    border-color: var(--warning-text-emphasis);
    transform: translateY(-2px);
    box-shadow: var(--box-shadow-md);
}
html[data-theme='light'] .alerts-button { color: white; }
.alerts-count-badge {
    background-color: var(--danger-color) !important;
    color: white !important;
    font-size: 0.75em;
    padding: 0.3em 0.6em;
    border-radius: 50%;
    position: relative;
    top: -2px;
}
.subscription-card-wrapper { }
.subscription-card {
    border-radius: var(--border-radius-lg);
    background-color: var(--content-bg);
    border: 1px solid var(--border-color);
    box-shadow: var(--box-shadow-sm);
    transition: transform 0.2s ease-out, box-shadow 0.2s ease-out;
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
}
html[data-theme='light'] .subscription-card { border: none; }
.subscription-card:hover {
    transform: translateY(-5px);
    box-shadow: var(--box-shadow-md);
}
.card-glow-warning { box-shadow: inset 0 0 0 3px var(--warning-color), var(--box-shadow-sm); }
.card-glow-danger { box-shadow: inset 0 0 0 3px var(--danger-color), var(--box-shadow-sm); }
.subscription-card .card-header {
    padding: 1rem 1.5rem;
    border-bottom: 1px solid rgba(255,255,255,0.2);
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-weight: 600;
    color: white;
    position: relative;
    z-index: 1;
}
.subscription-card .card-header h5 {
    font-weight: 700;
    display: flex;
    align-items: center;
    margin-bottom: 0;
    flex-grow: 1;
    color: inherit;
}
.subscription-card .platform-icon {
    font-size: 1.8rem;
    margin-right: 0.75rem;
    text-shadow: 0 1px 3px rgba(0,0,0,0.2);
}
.header-netflix { background-color: #E50914; color: white; }
.header-disney { background-color: #1A2A4B; color: white; }
.header-prime { background-color: #00A8E1; color: white; }
.header-hbo { background-color: #6C2B80; color: white; }
.header-spotify { background-color: #1DB954; color: white; }
.header-crunchyroll { background-color: #F47521; color: white; }
.header-canva { background-color: #00C4CC; color: white; }
.header-paramount { background-color: #0064FF; color: white; }
.header-iptv { background-color: #6a1b9a; color: white; }
.header-capcut { background-color: #16C79A; color: white; }
.header-directv { background-color: #0199d6; color: white; }
.header-movistar { background-color: #147ee5; color: white; }
.header-flujo { background-color: #FF5722; color: white; }
.header-viki { background-color: #FF005D; color: white; }
.header-youtube { background-color: #FF0000; color: white; }
.header-default { background-color: var(--secondary-color); color: white; }
.subscription-card .card-footer {
    background-color: var(--light-bg);
    border-top: 1px solid var(--border-color);
    padding: 1rem 1.5rem;
    display: flex;
    flex-wrap: wrap;
    gap: 0.75rem;
    justify-content: flex-end;
    margin-top: auto;
    transition: background-color 0.3s ease, border-color 0.3s ease;
}
.copy-btn, .toggle-password-btn {
    cursor: pointer;
    transition: color 0.2s, transform 0.1s;
    color: var(--text-muted);
    opacity: 0.8;
    font-size: 0.95rem;
}
.copy-btn:hover, .toggle-password-btn:hover {
    color: var(--primary-color);
    opacity: 1;
    transform: translateY(-1px);
}
.subscription-card .list-group-item {
    background: transparent !important;
    border: none !important;
    padding: .6rem 0;
    font-size: 0.95rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.subscription-card .list-group-item .text-muted {
    color: var(--text-muted) !important;
    font-weight: 500;
    display: flex;
    align-items: center;
}
.subscription-card .list-group-item .text-muted i {
    margin-right: 0.75rem;
    font-size: 1.1rem;
    color: var(--secondary-color);
}
.subscription-card .list-group-item .fw-bold {
    color: var(--text-dark);
    word-break: break-all;
}
.subscription-card .list-group-item .form-control-plaintext {
    background-color: transparent !important;
    border: none !important;
    padding: 0;
    font-size: inherit;
    color: inherit;
    width: 130px;
    text-align: right;
    font-family: 'Roboto Mono', monospace;
}
.subscription-card .list-group-item .form-control-plaintext:focus {
    box-shadow: none !important;
    outline: none !important;
}
.subscription-card .card-footer .btn {
    padding: .6rem 1.2rem;
    font-size: 0.9rem;
    border-radius: 50rem !important;
    font-weight: 500;
    transition: var(--transition-base);
    box-shadow: var(--box-shadow-xs);
}
.subscription-card .card-footer .btn:hover {
    transform: translateY(-2px);
    box-shadow: var(--box-shadow-sm);
}
.subscription-card .btn-outline-primary { color: var(--primary-color); border-color: var(--primary-color); }
.subscription-card .btn-outline-primary:hover { background-color: var(--primary-color); color: white; }
.subscription-card .btn-outline-secondary { color: var(--secondary-color); border-color: var(--secondary-color); }
.subscription-card .btn-outline-secondary:hover { background-color: var(--secondary-color); color: white; }
.subscription-card .btn-outline-success { color: var(--success-color); border-color: var(--success-color); }
.subscription-card .btn-outline-success:hover { background-color: var(--success-color); color: white; }
.subscription-card .btn-outline-warning { color: var(--warning-color); border-color: var(--warning-color); }
.subscription-card .btn-outline-warning:hover { background-color: var(--warning-color); color: var(--text-dark); }
.subscription-card .btn-outline-danger { color: var(--danger-color); border-color: var(--danger-color); }
.subscription-card .btn-outline-danger:hover { background-color: var(--danger-color); color: white; }
.subscription-card .btn-renew {
    font-size: 0.8rem;
    padding: 0.3rem 0.7rem;
    font-weight: 600;
    background-color: white !important;
    color: var(--primary-color) !important;
    border: 1px solid var(--primary-color) !important;
    transition: var(--transition-base);
    box-shadow: var(--box-shadow-xs);
}
.subscription-card .btn-renew:hover {
    background-color: var(--primary-color) !important;
    color: white !important;
    transform: scale(1.05);
    box-shadow: var(--box-shadow-sm);
}
.progress {
    height: 10px;
    border-radius: 10px;
    background-color: var(--border-color);
    margin-top: 12px;
}
.progress-bar { transition: width 0.6s ease; }
.modal-header.bg-warning {
    background-color: var(--warning-color) !important;
    color: #212529 !important;
}
.modal-header.bg-warning .btn-close {
    filter: none;
    opacity: 0.7;
    color: var(--text-dark);
}
html[data-theme='light'] .modal-header.bg-warning .btn-close { color: #212529; }
.modal-header.bg-warning .btn-close:hover { opacity: 1; }
.alert-notifications-card .card-body { padding: 1.5rem; }
.alert-notifications-card .alert.alert-item {
    border-left: 6px solid;
    border-radius: var(--border-radius-md);
    padding: 1.25rem 1.5rem;
    box-shadow: var(--box-shadow-sm);
    margin-bottom: 1.25rem;
    background-color: var(--content-bg);
}
.alert-notifications-card .alert.alert-item:last-child { margin-bottom: 0; }
.alert-notifications-card .alert-heading {
    font-size: 1.25rem;
    font-weight: 700;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    color: var(--text-dark);
}
.alert-notifications-card .alert-heading i {
    margin-right: 0.75rem;
    font-size: 1.1em;
}
.alert-notifications-card .alert-item.alert-danger { border-left-color: var(--danger-color); }
.alert-notifications-card .alert-item.alert-warning { border-left-color: var(--warning-color); }
.alert-notifications-card .alert-item.alert-success { border-left-color: var(--success-color); }
.alert-notifications-card .alert-list { margin-top: 0.5rem; }
.alert-notifications-card .alert-list li {
    padding: 0.75rem 0;
    border-bottom: 1px dashed var(--border-color);
}
.alert-notifications-card .alert-list li:last-child {
    border-bottom: none;
    padding-bottom: 0;
}
.alert-notifications-card .alert-info-text {
    flex-grow: 1;
    padding-right: 1rem;
}
.alert-notifications-card .alert-info-text strong {
    color: var(--primary-text-emphasis);
    font-size: 1.05rem;
}
.alert-notifications-card .alert-info-text small {
    color: var(--text-muted);
    font-size: 0.85rem;
}
.alert-notifications-card .alert-actions {
    display: flex;
    gap: 0.6rem;
    flex-shrink: 0;
}
.alert-notifications-card .btn-renew-alert {
    background-color: var(--success-color) !important;
    color: white !important;
    border: none;
    font-weight: 600;
    box-shadow: var(--box-shadow-xs);
    padding: 0.4rem 1rem;
    font-size: 0.85rem;
    transition: var(--transition-base);
}
.alert-notifications-card .btn-renew-alert:hover {
    background-color: var(--success-text-emphasis) !important;
    transform: translateY(-2px);
    box-shadow: var(--box-shadow-sm);
}
.alert-notifications-card .btn-outline-info {
    color: var(--info-color) !important;
    border-color: var(--info-color) !important;
    background-color: transparent !important;
    box-shadow: var(--box-shadow-xs);
    padding: 0.4rem 1rem;
    font-size: 0.85rem;
    transition: var(--transition-base);
}
.alert-notifications-card .btn-outline-info:hover {
    background-color: var(--info-color) !important;
    color: white !important;
    transform: translateY(-2px);
    box-shadow: var(--box-shadow-sm);
}
.alert-badge {
    font-size: 0.8em;
    padding: .5em 1em;
    margin: 0 .4em .4em 0;
    border-radius: 50rem !important;
    font-weight: 600;
    text-shadow: none;
    transition: transform 0.1s ease-out, box-shadow 0.1s ease-out;
    cursor: pointer;
}
.alert-badge:hover {
    transform: translateY(-2px);
    box-shadow: var(--box-shadow-sm);
}
.notes-toggle {
    cursor: pointer;
    color: var(--text-muted);
    font-size: 0.9rem;
    transition: color 0.2s ease;
    margin-top: 0.75rem;
    display: block;
    text-align: right;
}
.notes-toggle:hover {
    color: var(--primary-color);
    text-decoration: underline;
}
.notes-toggle .fas {
    font-size: 0.8em;
    transition: transform 0.2s ease;
}
.notes-toggle[aria-expanded="true"] .fas { transform: rotate(180deg); }
.notes-collapse-content {
    margin-top: 0.75rem;
    padding: 1rem;
    background-color: var(--body-bg);
    border-radius: var(--border-radius-sm);
    font-size: 0.9rem;
    color: var(--text-dark);
    border: 1px solid var(--border-color);
    box-shadow: inset 0 1px 3px rgba(0,0,0,0.05);
    transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
}
@media (max-width: 767.98px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
        text-align: center;
    }
    .page-header .page-title {
        font-size: 1.8rem;
        margin-bottom: 1rem;
    }
    .page-header .btn {
        width: 100%;
        font-size: 0.9rem;
        padding: 0.6rem 1rem;
    }
    .page-header .alerts-button {
        width: 100%;
        margin-bottom: 0.75rem;
    }
    .page-header .btn-primary { width: 100%; }
    .page-header .d-flex.align-items-center.gap-3 {
        flex-direction: column;
        width: 100%;
        gap: 0.75rem;
    }
    .alert-notifications-card .card-body { padding: 1rem; }
    .alert-notifications-card .alert.alert-item {
        padding: 1rem;
        font-size: 0.95rem;
    }
    .alert-notifications-card .alert-heading { font-size: 1.15rem; }
    .alert-notifications-card .alert-list li {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
        padding: 0.75rem 0;
    }
    .alert-notifications-card .alert-actions {
        width: 100%;
        justify-content: flex-end;
        margin-top: 0.5rem;
    }
    .alert-notifications-card .btn-renew-alert,
    .alert-notifications-card .btn-outline-info {
        flex-grow: 1;
        font-size: 0.8rem;
        padding: 0.35rem 0.75rem;
    }
    .subscription-card .card-header {
        padding: 0.8rem 1rem;
        font-size: 1rem;
    }
    .subscription-card .platform-icon {
        font-size: 1.5rem;
        margin-right: 0.5rem;
    }
    .subscription-card .card-body { padding: 1.2rem; }
    .subscription-card .list-group-item {
        font-size: 0.9rem;
        flex-direction: column;
        align-items: flex-start;
    }
    .subscription-card .list-group-item small.text-muted,
    .subscription-card .list-group-item .fw-bold {
        width: 100%;
        text-align: left;
    }
    .subscription-card .list-group-item .d-flex.align-items-center {
        width: 100%;
        justify-content: space-between;
    }
    .subscription-card .list-group-item .form-control-plaintext {
        width: auto;
        text-align: left;
    }
    .subscription-card .notes-toggle { text-align: left; }
    .subscription-card .card-footer {
        flex-direction: column;
        gap: 0.5rem;
        padding: 0.8rem 1rem;
    }
    .subscription-card .card-footer .btn {
        width: 100%;
        font-size: 0.85rem;
        padding: 0.5rem 1rem;
    }
    .quick-search-icon { left: 0.8rem !important; }
    .form-control-lg.ps-5 { padding-left: 2.5rem !important; }
    
    /* ==========================================================================
       ESTILOS PARA LAS CARDS DE KPIs DEL REPORTE DE GANANCIAS
       ========================================================================== */
    
    .kpi-card {
        background: #ffffff;
        border-radius: 1.25rem;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.12);
        overflow: hidden;
        transition: all 0.3s ease;
        border: 2px solid transparent;
        height: 100%;
        display: flex;
        align-items: center;
        padding: 1.5rem;
        position: relative;
    }
    
    .kpi-card:hover {
        transform: translateY(-8px);
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
    }
    
    .kpi-card.ventas {
        background: var(--kpi-ventas-bg);
        border-color: var(--kpi-ventas-border);
    }
    
    .kpi-card.inversion {
        background: var(--kpi-inversion-bg);
        border-color: var(--kpi-inversion-border);
    }
    
    .kpi-card.ganancia.positive {
        background: var(--kpi-ganancia-positive-bg);
        border-color: var(--kpi-ganancia-positive-border);
    }
    
    .kpi-card.ganancia.negative {
        background: var(--kpi-ganancia-negative-bg);
        border-color: var(--kpi-ganancia-negative-border);
    }
    
    .kpi-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 1rem;
        flex-shrink: 0;
        font-size: 1.5rem;
        color: white;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    
    .kpi-card.ventas .kpi-icon {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    }
    
    .kpi-card.inversion .kpi-icon {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    }
    
    .kpi-card.ganancia.positive .kpi-icon {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    }
    
    .kpi-card.ganancia.negative .kpi-icon {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    }
    
    .kpi-content {
        flex-grow: 1;
        min-width: 0;
    }
    
    .kpi-title {
        font-size: 0.85rem;
        font-weight: 600;
        color: var(--text-secondary);
        margin-bottom: 0.5rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .kpi-value {
        font-size: 1.8rem;
        font-weight: 800;
        margin-bottom: 0.25rem;
        line-height: 1;
    }
    
    .kpi-card.ventas .kpi-value {
        color: var(--kpi-ventas-text);
    }
    
    .kpi-card.inversion .kpi-value {
        color: var(--kpi-inversion-text);
    }
    
    .kpi-card.ganancia.positive .kpi-value {
        color: var(--kpi-ganancia-positive-text);
    }
    
    .kpi-card.ganancia.negative .kpi-value {
        color: var(--kpi-ganancia-negative-text);
    }
    
    .kpi-subtitle {
        font-size: 0.75rem;
        color: var(--text-muted);
        font-weight: 500;
    }
    
    /* Responsive para las cards de KPIs */
    @media (max-width: 1200px) {
        .col-xl-4 {
            flex: 0 0 50%;
            max-width: 50%;
        }
    }
    
    @media (max-width: 768px) {
        .col-lg-6,
        .col-xl-4 {
            flex: 0 0 100%;
            max-width: 100%;
        }
        
        .kpi-card {
            padding: 1rem;
        }
        
        .kpi-icon {
            width: 50px;
            height: 50px;
            font-size: 1.2rem;
        }
        
        .kpi-value {
            font-size: 1.5rem;
        }
    }
}
</style>
<?php
// --- FIN: CÓDIGO CSS PERSONALIZADO ---

// --- 3. LÓGICA DE FILTROS Y FECHAS ---
$fecha_actual_obj = new DateTime("now", new DateTimeZone(getConfigValue('zona_horaria_default', $id_usuario_sesion, 'America/Lima')));
$primer_dia_mes_actual = $fecha_actual_obj->format('Y-m-01');
$ultimo_dia_mes_actual = $fecha_actual_obj->format('Y-m-t');

$fecha_desde = $_GET['filtro_fecha_desde_rg'] ?? $primer_dia_mes_actual;
$fecha_hasta = $_GET['filtro_fecha_hasta_rg'] ?? $ultimo_dia_mes_actual;

// Parámetros base para las consultas
$params_ventas = [
    ':fecha_desde' => $fecha_desde,
    ':fecha_hasta' => $fecha_hasta
];

$params_inversion = [
    ':fecha_desde' => $fecha_desde,
    ':fecha_hasta' => $fecha_hasta
];

// Filtro de usuario dinámico para cada consulta
$user_filter_sql_ventas = '';
$user_filter_sql_inversion = '';

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

    $user_filter_sql_inversion = " AND cm.id_usuario = :id_usuario_sesion";
    $params_inversion[':id_usuario_sesion'] = $id_usuario_sesion;
}

// --- 4. CONSULTA SQL DE VENTAS POR FECHA DE INICIO DE SERVICIO ---
$sql_ventas_por_plataforma = "
    SELECT
        p.id_plataforma,
        p.nombre_plataforma,
        COUNT(pv.id_perfil_vendido) AS numero_perfiles_vendidos,
        COALESCE(SUM(pv.precio_venta), 0) AS total_ventas
    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
    WHERE
        pv.fecha_inicio_servicio BETWEEN :fecha_desde AND :fecha_hasta
        {$user_filter_sql_ventas}
    GROUP BY
        p.id_plataforma, p.nombre_plataforma;
";

$stmt_ventas = $pdo->prepare($sql_ventas_por_plataforma);
$stmt_ventas->execute($params_ventas);
$datos_ventas = $stmt_ventas->fetchAll(PDO::FETCH_ASSOC);

// --- 5. CONSULTA SQL DE INVERSIÓN POR FECHA DE COMPRA DE CUENTA MAESTRA ---
$sql_inversion_por_plataforma = "
    SELECT
        p.id_plataforma,
        p.nombre_plataforma,
        COALESCE(SUM(cm.costo_compra), 0) AS total_inversion
    FROM
        cuentas_maestras cm
    JOIN
        plataformas p ON cm.id_plataforma = p.id_plataforma
    WHERE
        cm.fecha_compra_proveedor BETWEEN :fecha_desde AND :fecha_hasta
        {$user_filter_sql_inversion}
    GROUP BY
        p.id_plataforma, p.nombre_plataforma;
";

$stmt_inversion = $pdo->prepare($sql_inversion_por_plataforma);
$stmt_inversion->execute($params_inversion);
$datos_inversion = $stmt_inversion->fetchAll(PDO::FETCH_ASSOC);

// --- 6. CONSULTAS PARA DETALLES DE TRANSACCIONES ---
$sql_detalle_ventas = "
    SELECT
        pv.fecha_venta,
        c.nombre_completo AS nombre_cliente,
        p.nombre_plataforma AS plataforma,
        pv.nombre_perfil_cliente AS perfil_vendido,
        cm.email_cuenta AS cuenta_maestra,
        pv.precio_venta
    FROM perfiles_vendidos pv
    JOIN clientes c ON pv.id_cliente = c.id_cliente
    JOIN cuentas_maestras cm ON pv.id_cuenta_maestra = cm.id_cuenta_maestra
    JOIN plataformas p ON cm.id_plataforma = p.id_plataforma
    WHERE pv.fecha_venta BETWEEN :fecha_desde AND :fecha_hasta
        {$user_filter_sql_ventas}
    ORDER BY pv.fecha_venta DESC;
";
$stmt_detalle_ventas = $pdo->prepare($sql_detalle_ventas);
$stmt_detalle_ventas->execute($params_ventas);
$detalle_ventas = $stmt_detalle_ventas->fetchAll(PDO::FETCH_ASSOC);

$sql_detalle_inversion = "
    SELECT
        cm.fecha_compra_proveedor AS fecha_compra,
        p.nombre_plataforma AS plataforma,
        cm.nombre_proveedor AS proveedor,
        cm.email_cuenta AS cuenta_maestra,
        cm.costo_compra
    FROM cuentas_maestras cm
    JOIN plataformas p ON cm.id_plataforma = p.id_plataforma
    WHERE cm.fecha_compra_proveedor BETWEEN :fecha_desde AND :fecha_hasta
        {$user_filter_sql_inversion}
    ORDER BY cm.fecha_compra_proveedor DESC;
";
$stmt_detalle_inversion = $pdo->prepare($sql_detalle_inversion);
$stmt_detalle_inversion->execute($params_inversion);
$detalle_inversion = $stmt_detalle_inversion->fetchAll(PDO::FETCH_ASSOC);


// --- 7. CONSOLIDAR DATOS ---
$consolidated_data = [];
$plataformas_nombres = [];

foreach ($datos_ventas as $row) {
    $id_plataforma = $row['id_plataforma'];
    $plataformas_nombres[$id_plataforma] = $row['nombre_plataforma'];
    $consolidated_data[$id_plataforma] = [
        'nombre_plataforma' => $row['nombre_plataforma'],
        'numero_perfiles_vendidos' => (int)$row['numero_perfiles_vendidos'],
        'total_ventas' => (float)$row['total_ventas'],
        'total_inversion' => 0,
    ];
}

foreach ($datos_inversion as $row) {
    $id_plataforma = $row['id_plataforma'];
    $plataformas_nombres[$id_plataforma] = $row['nombre_plataforma'];
    if (isset($consolidated_data[$id_plataforma])) {
        $consolidated_data[$id_plataforma]['total_inversion'] = (float)$row['total_inversion'];
    } else {
        $consolidated_data[$id_plataforma] = [
            'nombre_plataforma' => $row['nombre_plataforma'],
            'numero_perfiles_vendidos' => 0,
            'total_ventas' => 0,
            'total_inversion' => (float)$row['total_inversion'],
        ];
    }
}

// --- 8. PROCESAMIENTO DE DATOS PARA GRÁFICOS Y KPIs ---
$reporte_data_calculado = [];
$gran_total_cts = 0;
$gran_total_ventas = 0;
$gran_total_inversion = 0;
$chart_labels = [];
$chart_ventas = [];
$chart_inversion = [];
$chart_ganancia = [];

foreach ($consolidated_data as $row) {
    $ventas = (float)$row['total_ventas'];
    $inversion = (float)$row['total_inversion'];
    $ganancia = $ventas - $inversion;
    $margen_ganancia_porc = ($ventas > 0) ? ($ganancia / $ventas) * 100 : 0;

    $reporte_data_calculado[] = [
        'nombre_plataforma' => $row['nombre_plataforma'],
        'numero_perfiles_vendidos' => (int)$row['numero_perfiles_vendidos'],
        'total_ventas' => $ventas,
        'total_inversion' => $inversion,
        'total_ganancia' => $ganancia,
        'margen_ganancia_porc' => $margen_ganancia_porc,
    ];

    $gran_total_cts += (int)$row['numero_perfiles_vendidos'];
    $gran_total_ventas += $ventas;
    $gran_total_inversion += $inversion;

    $chart_labels[] = $row['nombre_plataforma'];
    $chart_ventas[] = $ventas;
    $chart_inversion[] = $inversion;
    $chart_ganancia[] = $ganancia;
}

usort($reporte_data_calculado, function($a, $b) {
    return $b['total_ganancia'] <=> $a['total_ganancia'];
});

$gran_total_ganancia = $gran_total_ventas - $gran_total_inversion;
$gran_total_margen_porc = ($gran_total_ventas > 0) ? ($gran_total_ganancia / $gran_total_ventas) * 100 : 0;

$moneda_simbolo = getConfigValue('moneda_simbolo', $id_usuario_sesion, 'S/');

?>

<div class="container-fluid px-lg-5 px-md-4 py-4">
    <header class="page-header d-flex justify-content-between align-items-center">
        <h1 class="page-title"><i class="fas fa-search-dollar"></i>Dashboard de Rentabilidad</h1>
        <div class="d-flex align-items-center gap-3">
            <button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#modalFiltros">
                <i class="fas fa-calendar-alt me-2"></i> Filtrar Periodo
            </button>
            <div class="btn-group">
                <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="fas fa-download me-2"></i> Exportar
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li><a class="dropdown-item" href="#" id="exportExcel"><i class="fas fa-file-excel me-2 text-success"></i>Exportar a Excel</a></li>
                    <li><a class="dropdown-item" href="#" id="exportPdf"><i class="fas fa-file-pdf me-2 text-danger"></i>Exportar a PDF</a></li>
                </ul>
            </div>
        </div>
    </header>

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

    <div class="row g-4">
        <div class="col-lg-8 order-lg-1">
            <!-- Cards de Resumen de KPIs -->
            <div class="row g-4 mb-4">
                <div class="col-lg-4 col-md-6">
                    <div class="kpi-card ventas">
                        <div class="kpi-icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <div class="kpi-content">
                            <div class="kpi-title">Ventas Totales</div>
                            <div class="kpi-value"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($gran_total_ventas, 2); ?></div>
                            <div class="kpi-subtitle">Ingresos del período</div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4 col-md-6">
                    <div class="kpi-card inversion">
                        <div class="kpi-icon">
                            <i class="fas fa-shopping-cart"></i>
                        </div>
                        <div class="kpi-content">
                            <div class="kpi-title">Inversión Total</div>
                            <div class="kpi-value"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($gran_total_inversion, 2); ?></div>
                            <div class="kpi-subtitle">Costos del período</div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4 col-md-12">
                    <div class="kpi-card ganancia <?php echo ($gran_total_ganancia >= 0 ? 'positive' : 'negative'); ?>">
                        <div class="kpi-icon">
                            <i class="fas fa-coins"></i>
                        </div>
                        <div class="kpi-content">
                            <div class="kpi-title">Ganancia Neta</div>
                            <div class="kpi-value"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($gran_total_ganancia, 2); ?></div>
                            <div class="kpi-subtitle"><?php echo number_format($gran_total_margen_porc, 1); ?>% de margen</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
               <div class="card-header">
                    <h6 class="m-0 fw-bold"><i class="fas fa-table me-2"></i>Análisis Detallado por Plataforma</h6>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table id="tablaGanancias" class="table table-hover" style="width:100%">
                            <thead>
                                <tr>
                                    <th class="text-start">Plataforma</th>
                                    <th class="text-center"># Vend.</th>
                                    <th class="text-end">Ventas</th>
                                    <th class="text-end">Inversión</th>
                                    <th class="text-end">Ganancia</th>
                                    <th class="text-end">Margen</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($reporte_data_calculado as $row): ?>
                                    <tr>
                                        <td class="text-start"><strong><?php echo htmlspecialchars($row['nombre_plataforma']); ?></strong></td>
                                        <td class="text-center"><?php echo htmlspecialchars($row['numero_perfiles_vendidos']); ?></td>
                                        <td class="text-end" data-sort="<?=$row['total_ventas']?>"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($row['total_ventas'], 2); ?></td>
                                        <td class="text-end" data-sort="<?=$row['total_inversion']?>"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($row['total_inversion'], 2); ?></td>
                                        <td class="text-end fw-bold <?php echo ($row['total_ganancia'] >= 0 ? 'text-success-emphasis' : 'text-danger-emphasis'); ?>" data-sort="<?=$row['total_ganancia']?>">
                                            <?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($row['total_ganancia'], 2); ?>
                                        </td>
                                        <td class="text-end <?php echo ($row['margen_ganancia_porc'] >= 0 ? 'text-success-emphasis' : 'text-danger-emphasis'); ?>" data-sort="<?=$row['margen_ganancia_porc']?>">
                                            <?php echo number_format($row['margen_ganancia_porc'], 1); ?>%
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <?php if (count($reporte_data_calculado) > 0): ?>
                            <tfoot class="table-group-divider">
                                <tr class="fw-bolder bg-light-subtle">
                                    <td class="text-start">TOTALES</td>
                                    <td class="text-center"><?php echo $gran_total_cts; ?></td>
                                    <td class="text-end"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($gran_total_ventas, 2); ?></td>
                                    <td class="text-end"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($gran_total_inversion, 2); ?></td>
                                    <td class="text-end <?php echo ($gran_total_ganancia >= 0 ? 'text-success-emphasis' : 'text-danger-emphasis'); ?>">
                                        <?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($gran_total_ganancia, 2); ?>
                                    </td>
                                    <td class="text-end <?php echo ($gran_total_margen_porc >= 0 ? 'text-success-emphasis' : 'text-danger-emphasis'); ?>">
                                        <?php echo number_format($gran_total_margen_porc, 1); ?>%
                                    </td>
                                </tr>
                            </tfoot>
                            <?php endif; ?>
                        </table>
                    </div>
                </div>
            </div>
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="m-0 fw-bold"><i class="fas fa-coins me-2"></i>Detalle de Transacciones</h6>
                </div>
                <div class="card-body p-0">
                    <div class="accordion accordion-flush" id="accordionDetallesTransacciones">
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseVentas" aria-expanded="false">
                                    <i class="fas fa-chart-line me-2 text-success-emphasis"></i>Detalle de Ventas (Perfiles)
                                </button>
                            </h2>
                            <div id="collapseVentas" class="accordion-collapse collapse" data-bs-parent="#accordionDetallesTransacciones">
                                <div class="accordion-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-x-compact table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Fecha Venta</th>
                                                    <th>Cliente</th>
                                                    <th>Plataforma</th>
                                                    <th>Perfil</th>
                                                    <th class="text-end">Precio</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($detalle_ventas as $venta): ?>
                                                    <tr>
                                                        <td><?php echo (new DateTime($venta['fecha_venta']))->format('d/m/Y'); ?></td>
                                                        <td><?php echo htmlspecialchars($venta['nombre_cliente']); ?></td>
                                                        <td><?php echo htmlspecialchars($venta['plataforma']); ?></td>
                                                        <td><?php echo htmlspecialchars($venta['perfil_vendido']); ?></td>
                                                        <td class="text-end"><?php echo $moneda_simbolo . ' ' . number_format($venta['precio_venta'], 2); ?></td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseInversiones" aria-expanded="false">
                                    <i class="fas fa-shopping-cart me-2 text-danger-emphasis"></i>Detalle de Inversión (Cuentas Maestras)
                                </button>
                            </h2>
                            <div id="collapseInversiones" class="accordion-collapse collapse" data-bs-parent="#accordionDetallesTransacciones">
                                <div class="accordion-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-x-compact table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Fecha Compra</th>
                                                    <th>Plataforma</th>
                                                    <th>Proveedor</th>
                                                    <th class="text-end">Costo</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($detalle_inversion as $inversion): ?>
                                                    <tr>
                                                        <td><?php echo (new DateTime($inversion['fecha_compra']))->format('d/m/Y'); ?></td>
                                                        <td><?php echo htmlspecialchars($inversion['plataforma']); ?></td>
                                                        <td><?php echo htmlspecialchars($inversion['proveedor'] ?? 'N/A'); ?></td>
                                                        <td class="text-end"><?php echo $moneda_simbolo . ' ' . number_format($inversion['costo_compra'], 2); ?></td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4 order-lg-2">
             <div class="summary-card mb-4">
                <div class="card-header">
                    <h6 class="m-0 fw-bold"><i class="fas fa-calculator me-2"></i>Resumen Financiero</h6>
                </div>
                <div class="card-body">
                    <div class="info-row">
                        <span class="info-label">Ventas Totales</span>
                        <span class="info-value text-primary"><?php echo $moneda_simbolo; ?> <?php echo number_format($gran_total_ventas, 2); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Inversión Total</span>
                        <span class="info-value text-danger"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($gran_total_inversion, 2); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Margen de Ganancia</span>
                        <span class="info-value <?php echo ($gran_total_margen_porc >= 0 ? 'text-success' : 'text-danger'); ?>"><?php echo number_format($gran_total_margen_porc, 1); ?>%</span>
                    </div>
                    <div class="final-profit-box <?php echo ($gran_total_ganancia >= 0 ? 'bg-success-soft' : 'bg-danger-soft'); ?>">
                        <span class="fw-bolder <?php echo ($gran_total_ganancia >= 0 ? 'text-success-emphasis' : 'text-danger-emphasis'); ?>">GANANCIA NETA</span>
                        <span class="fw-bolder <?php echo ($gran_total_ganancia >= 0 ? 'text-success-emphasis' : 'text-danger-emphasis'); ?> fs-4"><?php echo htmlspecialchars($moneda_simbolo); ?> <?php echo number_format($gran_total_ganancia, 2); ?></span>
                    </div>
                </div>
            </div>
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="m-0 fw-bold"><i class="fas fa-pie-chart me-2"></i>Aporte a la Ganancia Total</h6>
                </div>
                <div class="card-body">
                    <div class="chart-pie pt-4">
                        <canvas id="graficoGananciaDona"></canvas>
                    </div>
                </div>
            </div>
            <div class="accordion" id="accordionHelp">
                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseHelp" aria-expanded="false" aria-controls="collapseHelp">
                            <i class="fas fa-info-circle me-2"></i>¿Cómo se calcula este reporte?
                        </button>
                    </h2>
                    <div id="collapseHelp" class="accordion-collapse collapse" data-bs-parent="#accordionHelp">
                        <div class="accordion-body">
                            <ul>
                                <li>**Ventas:** Suma del `precio_venta` de todas las suscripciones cuyo **inicio de servicio** se encuentra dentro del periodo de fechas seleccionado.</li>
                                <li>**Inversión (Costo de Ventas):** Suma del `costo_compra` total de las cuentas maestras cuya **fecha de compra** se encuentra dentro del periodo seleccionado. El costo de una cuenta se imputa completamente al mes de su compra.</li>
                                <li>**Ganancia:** Se calcula como **Ventas Totales - Inversión Total**.</li>
                                <li>**Margen de Ganancia:** Se calcula como `(Ganancia Neta / Ventas Totales) * 100`.</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalFiltros" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-calendar-alt me-2"></i>Filtrar Periodo del Reporte</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="" method="GET">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="filtro_fecha_desde_rg" class="form-label">Desde:</label>
                        <input type="date" name="filtro_fecha_desde_rg" class="form-control" value="<?php echo htmlspecialchars($fecha_desde); ?>">
                    </div>
                    <div class="mb-3">
                        <label for="filtro_fecha_hasta_rg" class="form-label">Hasta:</label>
                        <input type="date" name="filtro_fecha_hasta_rg" class="form-control" value="<?php echo htmlspecialchars($fecha_hasta); ?>">
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="/digitalpremium/pages/reporte_ganancias.php" class="btn btn-outline-secondary">Mes Actual</a>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-check me-1"></i> Generar Reporte</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const monedaSimbolo = '<?php echo $moneda_simbolo; ?>';
    const chartColors = {
        primary: 'hsl(240, 70%, 55%)',
        success: 'hsl(145, 60%, 40%)',
        danger: 'hsl(0, 65%, 50%)',
        warning: 'hsl(45, 90%, 50%)',
        info: 'hsl(200, 70%, 45%)',
        secondary: '#6b7280',
        lightGray: '#eef2f6',
        darkGray: '#212529'
    };

    const ctxBarras = document.getElementById('graficoRentabilidadBarras')?.getContext('2d');
    if (ctxBarras) {
        new Chart(ctxBarras, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($chart_labels); ?>,
                datasets: [
                    {
                        label: 'Ventas',
                        data: <?php echo json_encode($chart_ventas); ?>,
                        backgroundColor: chartColors.primary,
                        borderRadius: 5,
                    },
                    {
                        label: 'Inversión',
                        data: <?php echo json_encode(array_map(fn($val) => abs($val), $chart_inversion)); ?>,
                        backgroundColor: chartColors.danger,
                        borderRadius: 5,
                    },
                    {
                        label: 'Ganancia',
                        data: <?php echo json_encode($chart_ganancia); ?>,
                        backgroundColor: chartColors.success,
                        borderRadius: 5,
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        stacked: false,
                        grid: { display: false },
                        ticks: { color: chartColors.darkGray }
                    },
                    y: {
                        stacked: false,
                        beginAtZero: true,
                        grid: { color: chartColors.lightGray },
                        ticks: {
                            callback: (v) => `${monedaSimbolo} ${v.toLocaleString(undefined, {minimumFractionDigits: 2})}`,
                            color: chartColors.darkGray
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            boxWidth: 15,
                            padding: 20,
                            color: chartColors.darkGray
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: (c) => {
                                let value = c.parsed.y;
                                return ` ${c.dataset.label}: ${monedaSimbolo} ${value.toLocaleString(undefined, {minimumFractionDigits: 2})}`;
                            }
                        },
                        backgroundColor: chartColors.darkGray,
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: chartColors.primary,
                        borderWidth: 1,
                        cornerRadius: 4,
                        displayColors: true
                    }
                }
            }
        });
    }

    const ctxDona = document.getElementById('graficoGananciaDona')?.getContext('2d');
    if (ctxDona) {
        const positiveGainsLabels = [];
        const positiveGainsData = [];
        const backgroundColors = [];
        const dynamicColors = [
            '#4CAF50', '#2196F3', '#FFC107', '#9C27B0', '#FF5722', '#795548', '#607D8B', '#009688', '#E91E63'
        ];
        let colorIndex = 0;

        <?php foreach ($reporte_data_calculado as $row): ?>
            <?php if ($row['total_ganancia'] > 0): ?>
                positiveGainsLabels.push('<?php echo htmlspecialchars($row['nombre_plataforma']); ?>');
                positiveGainsData.push(<?php echo $row['total_ganancia']; ?>);
                backgroundColors.push(dynamicColors[colorIndex % dynamicColors.length]);
                colorIndex++;
            <?php endif; ?>
        <?php endforeach; ?>

        new Chart(ctxDona, {
            type: 'doughnut',
            data: {
                labels: positiveGainsLabels,
                datasets: [{
                    data: positiveGainsData,
                    backgroundColor: backgroundColors,
                    hoverOffset: 8,
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            boxWidth: 12,
                            padding: 15,
                            color: chartColors.darkGray
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = context.parsed || 0;
                                const totalPositiveGain = context.chart.data.datasets[0].data.reduce((a, b) => a + b, 0);
                                const percentage = totalPositiveGain > 0 ? ((value / totalPositiveGain) * 100).toFixed(2) : 0;
                                return ` ${label}: ${monedaSimbolo} ${value.toLocaleString(undefined, {minimumFractionDigits: 2})} (${percentage}%)`;
                            }
                        },
                        backgroundColor: chartColors.darkGray,
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: chartColors.primary,
                        borderWidth: 1,
                        cornerRadius: 4,
                        displayColors: true
                    }
                }
            }
        });
    }

    const tabla = $('#tablaGanancias').DataTable({
        language: { url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/es-ES.json' },
        order: [[4, 'desc']],
        paging: false,
        info: false,
        searching: false,
        dom: 'Brt',
        buttons: [
            { extend: 'excelHtml5', title: 'Reporte de Rentabilidad', filename: 'reporte_rentabilidad_excel', exportOptions: { columns: [0,1,2,3,4,5] } },
            { extend: 'pdfHtml5', title: 'Reporte de Rentabilidad', filename: 'reporte_rentabilidad_pdf', orientation: 'landscape', pageSize: 'A4', exportOptions: { columns: [0,1,2,3,4,5] } }
        ]
    });

    $('#exportExcel').on('click', (e) => { e.preventDefault(); tabla.button('.buttons-excel').trigger(); });
    $('#exportPdf').on('click', (e) => { e.preventDefault(); tabla.button('.buttons-pdf').trigger(); });
});
</script>