<?php

declare(strict_types=1);

ob_start();
require_once __DIR__ . '/init.php';

if (mb_strtolower(trim((string) ($_SESSION['admin']['rol'] ?? '')), 'UTF-8') !== 'admin'
    || !tiene_permiso('ver_reportes_propios_admin')) {
    $_SESSION['flash_message'] = [
        'type' => 'error',
        'text' => 'Acceso denegado. Este módulo es para Administradores.',
    ];
    header('Location: index.php');
    exit;
}

$idAdmin = (int) ($_SESSION['admin']['uid'] ?? 0);
$errorMessage = '';

$accountSummary = [
    'total_cuentas' => 0,
    'cuentas_asignadas' => 0,
    'cuentas_sin_asignar' => 0,
    'cuentas_vencidas' => 0,
    'vencen_hoy' => 0,
    'vencen_7_dias' => 0,
    'vencen_8_30_dias' => 0,
    'vigentes_mas_30' => 0,
    'sin_fecha' => 0,
];
$accountsByPlatform = [];
$clientsReport = [];
$mailboxesReport = [];
$renewalsReport = [];

try {
    $summaryStmt = $pdo->prepare(
        "SELECT
            COUNT(cs.id) AS total_cuentas,
            COALESCE(SUM(CASE WHEN linked.id_correo_servicio IS NOT NULL THEN 1 ELSE 0 END), 0) AS cuentas_asignadas,
            COALESCE(SUM(CASE WHEN linked.id_correo_servicio IS NULL THEN 1 ELSE 0 END), 0) AS cuentas_sin_asignar,
            COALESCE(SUM(CASE WHEN cs.fecha_renovacion < CURDATE() THEN 1 ELSE 0 END), 0) AS cuentas_vencidas,
            COALESCE(SUM(CASE WHEN cs.fecha_renovacion = CURDATE() THEN 1 ELSE 0 END), 0) AS vencen_hoy,
            COALESCE(SUM(CASE WHEN cs.fecha_renovacion BETWEEN DATE_ADD(CURDATE(), INTERVAL 1 DAY)
                AND DATE_ADD(CURDATE(), INTERVAL 7 DAY) THEN 1 ELSE 0 END), 0) AS vencen_7_dias,
            COALESCE(SUM(CASE WHEN cs.fecha_renovacion BETWEEN DATE_ADD(CURDATE(), INTERVAL 8 DAY)
                AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) THEN 1 ELSE 0 END), 0) AS vencen_8_30_dias,
            COALESCE(SUM(CASE WHEN cs.fecha_renovacion > DATE_ADD(CURDATE(), INTERVAL 30 DAY)
                THEN 1 ELSE 0 END), 0) AS vigentes_mas_30,
            COALESCE(SUM(CASE WHEN cs.fecha_renovacion IS NULL THEN 1 ELSE 0 END), 0) AS sin_fecha
         FROM correos_servicios cs
         LEFT JOIN (
            SELECT DISTINCT id_correo_servicio
            FROM asociaciones
            WHERE id_admin_propietario = ? AND id_correo_servicio IS NOT NULL
         ) linked ON linked.id_correo_servicio = cs.id
         WHERE cs.id_admin_propietario = ?"
    );
    $summaryStmt->execute([$idAdmin, $idAdmin]);
    $summaryRow = $summaryStmt->fetch(PDO::FETCH_ASSOC);
    if (is_array($summaryRow)) {
        foreach ($accountSummary as $key => $default) {
            $accountSummary[$key] = (int) ($summaryRow[$key] ?? $default);
        }
    }

    $platformStmt = $pdo->prepare(
        "SELECT p.id, p.nombre AS plataforma_nombre, COUNT(cs.id) AS total_cuentas
         FROM plataformas p
         JOIN correos_servicios cs ON cs.id_plataforma = p.id
         WHERE cs.id_admin_propietario = ?
         GROUP BY p.id, p.nombre
         ORDER BY total_cuentas DESC, p.nombre ASC"
    );
    $platformStmt->execute([$idAdmin]);
    $accountsByPlatform = $platformStmt->fetchAll(PDO::FETCH_ASSOC);

    $clientsStmt = $pdo->prepare(
        "SELECT
            u.id,
            u.nombre_usuario,
            u.correo,
            u.telefono,
            r.nombre_rol,
            COUNT(DISTINCT cs.id) AS total_cuentas,
            COUNT(DISTINCT CASE WHEN cs.fecha_renovacion < CURDATE() THEN cs.id END) AS cuentas_vencidas,
            COUNT(DISTINCT CASE WHEN cs.fecha_renovacion BETWEEN CURDATE()
                AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) THEN cs.id END) AS proximas_30_dias
         FROM usuarios u
         JOIN roles r ON r.id = u.id_rol
         LEFT JOIN asociaciones a
            ON a.id_usuario = u.id AND a.id_admin_propietario = ?
         LEFT JOIN correos_servicios cs
            ON cs.id = a.id_correo_servicio AND cs.id_admin_propietario = ?
         WHERE u.id_admin_propietario = ?
           AND r.nombre_rol IN ('Revendedor', 'Cliente Final')
         GROUP BY u.id, u.nombre_usuario, u.correo, u.telefono, r.nombre_rol
         ORDER BY total_cuentas DESC, u.nombre_usuario ASC"
    );
    $clientsStmt->execute([$idAdmin, $idAdmin, $idAdmin]);
    $clientsReport = $clientsStmt->fetchAll(PDO::FETCH_ASSOC);

    $mailboxesStmt = $pdo->prepare(
        "SELECT
            ci.id,
            ci.imap_usuario,
            ci.imap_host,
            ci.imap_puerto,
            ci.fecha_renovacion,
            COALESCE(NULLIF(ci.nombre_proveedor, ''), NULLIF(ci.plataforma, ''), 'Manual') AS proveedor,
            COUNT(DISTINCT d.id) AS total_dominios
         FROM configuraciones_imap ci
         LEFT JOIN dominios d
            ON d.id_buzon_entrada = ci.id AND d.id_admin_propietario = ci.id_admin
         WHERE ci.id_admin = ?
         GROUP BY ci.id, ci.imap_usuario, ci.imap_host, ci.imap_puerto,
                  ci.fecha_renovacion, ci.nombre_proveedor, ci.plataforma
         ORDER BY total_dominios DESC, ci.imap_usuario ASC"
    );
    $mailboxesStmt->execute([$idAdmin]);
    $mailboxesReport = $mailboxesStmt->fetchAll(PDO::FETCH_ASSOC);

    $cutoff = date('Y-m-d', strtotime('+30 days'));
    $renewalsStmt = $pdo->prepare(
        "SELECT
            cs.id,
            cs.correo,
            p.id AS plataforma_id,
            p.nombre AS plataforma_nombre,
            cs.fecha_renovacion,
            u.id AS cliente_id,
            u.nombre_usuario AS cliente_asociado,
            u.telefono AS cliente_telefono,
            DATEDIFF(cs.fecha_renovacion, CURDATE()) AS dias
         FROM correos_servicios cs
         JOIN plataformas p ON p.id = cs.id_plataforma
         LEFT JOIN (
            SELECT id_correo_servicio, MIN(id_usuario) AS id_usuario
            FROM asociaciones
            WHERE id_admin_propietario = ? AND id_correo_servicio IS NOT NULL
            GROUP BY id_correo_servicio
         ) link ON link.id_correo_servicio = cs.id
         LEFT JOIN usuarios u ON u.id = link.id_usuario
         WHERE cs.id_admin_propietario = ?
           AND cs.fecha_renovacion IS NOT NULL
           AND cs.fecha_renovacion <= ?
         ORDER BY cs.fecha_renovacion ASC, p.nombre ASC, cs.correo ASC"
    );
    $renewalsStmt->execute([$idAdmin, $idAdmin, $cutoff]);
    $renewalsReport = $renewalsStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log('Error al cargar reportes propios: ' . $e->getMessage());
    $errorMessage = 'No se pudieron cargar los reportes operativos. Inténtalo nuevamente.';
}

function af_report_renewal_view(array $row): array
{
    $days = (int) ($row['dias'] ?? 0);
    if ($days < 0) {
        return [
            'state' => 'expired',
            'label' => 'Vencida',
            'detail' => 'Hace ' . abs($days) . ' día' . (abs($days) === 1 ? '' : 's'),
            'badge' => 'af-badge-danger',
        ];
    }
    if ($days === 0) {
        return [
            'state' => 'today',
            'label' => 'Vence hoy',
            'detail' => 'Atención inmediata',
            'badge' => 'af-badge-danger',
        ];
    }
    if ($days <= 7) {
        return [
            'state' => 'urgent',
            'label' => 'Por vencer',
            'detail' => $days === 1 ? 'Vence mañana' : "En {$days} días",
            'badge' => 'af-badge-warning',
        ];
    }
    if ($days <= 15) {
        return [
            'state' => 'soon',
            'label' => 'Próxima',
            'detail' => "En {$days} días",
            'badge' => 'af-badge-warning',
        ];
    }
    return [
        'state' => 'later',
        'label' => 'Programada',
        'detail' => "En {$days} días",
        'badge' => 'af-badge-success',
    ];
}

$totalClients = count($clientsReport);
$clientsWithWhatsapp = 0;
$clientsWithoutWhatsapp = 0;
$roleCounts = [];
foreach ($clientsReport as $clientRow) {
    $phone = preg_replace('/\D+/', '', (string) ($clientRow['telefono'] ?? ''));
    if ($phone === '') {
        $clientsWithoutWhatsapp++;
    } else {
        $clientsWithWhatsapp++;
    }
    $roleName = (string) ($clientRow['nombre_rol'] ?? 'Sin rol');
    $roleCounts[$roleName] = ($roleCounts[$roleName] ?? 0) + 1;
}

$totalMailboxes = count($mailboxesReport);
$totalDomains = array_sum(array_map(
    static fn(array $row): int => (int) ($row['total_dominios'] ?? 0),
    $mailboxesReport
));

$platformLabels = array_map(
    static fn(array $row): string => (string) ($row['plataforma_nombre'] ?? ''),
    $accountsByPlatform
);
$platformValues = array_map(
    static fn(array $row): int => (int) ($row['total_cuentas'] ?? 0),
    $accountsByPlatform
);
$roleLabels = array_keys($roleCounts);
$roleValues = array_values($roleCounts);
$renewalLabels = ['Vencidas', 'Vencen hoy', '1–7 días', '8–30 días', 'Vigentes', 'Sin fecha'];
$renewalValues = [
    $accountSummary['cuentas_vencidas'],
    $accountSummary['vencen_hoy'],
    $accountSummary['vencen_7_dias'],
    $accountSummary['vencen_8_30_dias'],
    $accountSummary['vigentes_mas_30'],
    $accountSummary['sin_fecha'],
];

$renewalPlatforms = [];
$renewalClients = [];
$renewalCounters = ['expired' => 0, 'today' => 0, 'urgent' => 0, 'soon' => 0, 'later' => 0];
foreach ($renewalsReport as $renewalRow) {
    $renewalPlatforms[(int) ($renewalRow['plataforma_id'] ?? 0)] =
        (string) ($renewalRow['plataforma_nombre'] ?? 'Sin plataforma');
    if (!empty($renewalRow['cliente_id'])) {
        $renewalClients[(int) $renewalRow['cliente_id']] =
            (string) ($renewalRow['cliente_asociado'] ?? 'Cliente');
    }
    $view = af_report_renewal_view($renewalRow);
    $renewalCounters[$view['state']]++;
}
natcasesort($renewalPlatforms);
natcasesort($renewalClients);

$mailboxProviders = [];
foreach ($mailboxesReport as $mailboxRow) {
    $providerName = trim((string) ($mailboxRow['proveedor'] ?? 'Manual')) ?: 'Manual';
    $mailboxProviders[$providerName] = $providerName;
}
natcasesort($mailboxProviders);

$titulo_pagina = 'Mis Reportes';
require_once __DIR__ . '/admin_header.php';
?>
<style>
.af-report-insights {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 12px;
}
.af-report-insight {
    display: flex;
    align-items: center;
    gap: 12px;
    min-height: 78px;
    padding: 14px 16px;
    border: 1px solid var(--af-border, #e2e8f0);
    border-radius: 14px;
    background: #fff;
}
.af-report-insight > i {
    width: 36px;
    height: 36px;
    display: grid;
    place-items: center;
    flex: 0 0 36px;
    border-radius: 10px;
    background: #fff1f2;
    color: #dc2626;
}
.af-report-insight strong { display: block; font-size: 18px; color: #111827; }
.af-report-insight span { display: block; margin-top: 2px; font-size: 12px; color: #64748b; }
.af-report-grid--three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.af-report-chart { height: 280px; }
.af-phone-state { display: inline-flex; align-items: center; gap: 6px; }
@media (max-width: 1180px) {
    .af-report-insights { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    .af-report-grid--three { grid-template-columns: 1fr 1fr; }
    .af-report-grid--three > :last-child { grid-column: 1 / -1; }
}
@media (max-width: 720px) {
    .af-report-insights,
    .af-report-grid--three { grid-template-columns: 1fr; }
    .af-report-grid--three > :last-child { grid-column: auto; }
}
</style>
<div class="af-page">
    <header class="af-heading">
        <div class="af-heading-main">
            <span class="af-heading-icon"><i class="fas fa-chart-line"></i></span>
            <div>
                <p class="af-eyebrow">Indicadores de mi operación</p>
                <h1>Mis reportes</h1>
                <p>Revisa cuentas, clientes, WhatsApp, buzones, dominios y renovaciones sin mezclar información de otros administradores.</p>
            </div>
        </div>
        <div class="af-heading-actions">
            <a href="gestionar_cuentas.php" class="af-btn af-btn-primary"><i class="fas fa-briefcase"></i> Gestionar cuentas</a>
        </div>
    </header>

    <?php if ($errorMessage !== ''): ?>
        <div class="af-alert af-alert-danger"><i class="fas fa-triangle-exclamation"></i><div><?= htmlspecialchars($errorMessage) ?></div></div>
    <?php endif; ?>

    <section class="af-stats" aria-label="Resumen operativo">
        <article class="af-stat"><span class="af-stat-icon"><i class="fas fa-envelope"></i></span><div><p class="af-stat-label">Cuentas</p><p class="af-stat-value"><?= number_format($accountSummary['total_cuentas']) ?></p><div class="af-stat-note">Registradas en tu operación</div></div></article>
        <article class="af-stat"><span class="af-stat-icon"><i class="fas fa-user-check"></i></span><div><p class="af-stat-label">Asignadas</p><p class="af-stat-value"><?= number_format($accountSummary['cuentas_asignadas']) ?></p><div class="af-stat-note"><?= number_format($accountSummary['cuentas_sin_asignar']) ?> sin cliente</div></div></article>
        <article class="af-stat"><span class="af-stat-icon"><i class="fas fa-calendar-xmark"></i></span><div><p class="af-stat-label">Vencidas</p><p class="af-stat-value"><?= number_format($accountSummary['cuentas_vencidas']) ?></p><div class="af-stat-note"><?= number_format($accountSummary['vencen_7_dias']) ?> vencen en 7 días</div></div></article>
        <article class="af-stat"><span class="af-stat-icon"><i class="fab fa-whatsapp"></i></span><div><p class="af-stat-label">Sin WhatsApp</p><p class="af-stat-value"><?= number_format($clientsWithoutWhatsapp) ?></p><div class="af-stat-note"><?= number_format($clientsWithWhatsapp) ?> clientes con teléfono</div></div></article>
    </section>

    <section class="af-report-insights" aria-label="Alertas rápidas">
        <article class="af-report-insight"><i class="fas fa-user-slash"></i><div><strong><?= number_format($accountSummary['cuentas_sin_asignar']) ?></strong><span>Cuentas sin cliente asignado</span></div></article>
        <article class="af-report-insight"><i class="fas fa-calendar-question"></i><div><strong><?= number_format($accountSummary['sin_fecha']) ?></strong><span>Cuentas sin fecha de renovación</span></div></article>
        <article class="af-report-insight"><i class="fas fa-inbox"></i><div><strong><?= number_format($totalMailboxes) ?></strong><span>Buzones de entrada registrados</span></div></article>
        <article class="af-report-insight"><i class="fas fa-at"></i><div><strong><?= number_format($totalDomains) ?></strong><span>Dominios asociados a buzones</span></div></article>
    </section>

    <section class="af-report-grid af-report-grid--three">
        <article class="af-panel">
            <div class="af-panel-head"><div class="af-panel-title"><span class="af-panel-title-icon"><i class="fas fa-tv"></i></span><div><h2>Cuentas por plataforma</h2><p>Distribución actual de tus accesos.</p></div></div></div>
            <div class="af-panel-body af-report-chart"><canvas id="platformReportChart"></canvas></div>
        </article>
        <article class="af-panel">
            <div class="af-panel-head"><div class="af-panel-title"><span class="af-panel-title-icon"><i class="fas fa-calendar-check"></i></span><div><h2>Estado de renovación</h2><p>Salud actual de las fechas registradas.</p></div></div></div>
            <div class="af-panel-body af-report-chart"><canvas id="renewalReportChart"></canvas></div>
        </article>
        <article class="af-panel">
            <div class="af-panel-head"><div class="af-panel-title"><span class="af-panel-title-icon"><i class="fas fa-users"></i></span><div><h2>Clientes por rol</h2><p><?= number_format($totalClients) ?> clientes en total.</p></div></div></div>
            <div class="af-panel-body af-report-chart"><canvas id="roleReportChart"></canvas></div>
        </article>
    </section>

    <section class="af-panel">
        <div class="af-panel-head">
            <div class="af-panel-title"><span class="af-panel-title-icon"><i class="fas fa-address-book"></i></span><div><h2>Cartera de clientes</h2><p>Detecta clientes sin WhatsApp, sin cuentas o con renovaciones pendientes.</p></div></div>
            <a href="gestionar_clientes.php" class="af-btn af-btn-secondary"><i class="fas fa-arrow-right"></i> Gestionar clientes</a>
        </div>
        <div class="af-toolbar">
            <div class="af-field"><label class="af-label" for="clientReportSearch"><i class="fas fa-search"></i> Buscar</label><input id="clientReportSearch" type="search" class="af-control" placeholder="Nombre, correo o teléfono"></div>
            <div class="af-field"><label class="af-label" for="clientReportRole"><i class="fas fa-user-tag"></i> Rol</label><select id="clientReportRole" class="af-control"><option value="">Todos</option><option value="Revendedor">Revendedor</option><option value="Cliente Final">Cliente Final</option></select></div>
            <div class="af-field"><label class="af-label" for="clientReportWhatsapp"><i class="fab fa-whatsapp"></i> WhatsApp</label><select id="clientReportWhatsapp" class="af-control"><option value="">Todos</option><option value="yes">Con WhatsApp</option><option value="no">Sin WhatsApp</option></select></div>
            <div class="af-field"><label class="af-label" for="clientReportPerPage"><i class="fas fa-list-ol"></i> Mostrar</label><select id="clientReportPerPage" class="af-control"><option value="100">100 registros</option><option value="200">200 registros</option><option value="400">400 registros</option><option value="all">Todos</option></select></div>
            <div class="af-toolbar-actions"><button type="button" id="clearClientReportFilters" class="af-btn af-btn-secondary"><i class="fas fa-eraser"></i> Limpiar</button></div>
        </div>
        <div class="af-list-meta"><span><?= number_format($totalClients) ?> clientes analizados</span><span id="clientReportSummary"></span></div>
        <div class="af-table-wrap">
            <table id="clientReportTable" class="af-table">
                <thead><tr><th>Cliente</th><th>Rol</th><th>WhatsApp</th><th>Cuentas</th><th>Vencidas</th><th>Próximas 30 días</th></tr></thead>
                <tbody>
                <?php foreach ($clientsReport as $row):
                    $phoneDigits = preg_replace('/\D+/', '', (string) ($row['telefono'] ?? ''));
                    $hasWhatsapp = $phoneDigits !== '';
                ?>
                    <tr data-af-row data-role="<?= htmlspecialchars((string) $row['nombre_rol'], ENT_QUOTES, 'UTF-8') ?>" data-whatsapp="<?= $hasWhatsapp ? 'yes' : 'no' ?>" data-search="<?= htmlspecialchars(($row['nombre_usuario'] ?? '') . ' ' . ($row['correo'] ?? '') . ' ' . ($row['telefono'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
                        <td><span class="af-row-title"><?= htmlspecialchars((string) $row['nombre_usuario']) ?></span><span class="af-row-sub"><?= htmlspecialchars((string) $row['correo']) ?></span></td>
                        <td><span class="af-badge af-badge-neutral"><i class="fas fa-user-tag"></i><?= htmlspecialchars((string) $row['nombre_rol']) ?></span></td>
                        <td><?php if ($hasWhatsapp): ?><span class="af-badge af-badge-success af-phone-state"><i class="fab fa-whatsapp"></i> +<?= htmlspecialchars($phoneDigits) ?></span><?php else: ?><span class="af-badge af-badge-danger"><i class="fas fa-phone-slash"></i> Sin teléfono</span><?php endif; ?></td>
                        <td><strong><?= number_format((int) $row['total_cuentas']) ?></strong></td>
                        <td><span class="af-badge <?= (int) $row['cuentas_vencidas'] > 0 ? 'af-badge-danger' : 'af-badge-success' ?>"><?= number_format((int) $row['cuentas_vencidas']) ?></span></td>
                        <td><span class="af-badge <?= (int) $row['proximas_30_dias'] > 0 ? 'af-badge-warning' : 'af-badge-neutral' ?>"><?= number_format((int) $row['proximas_30_dias']) ?></span></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <div id="clientReportEmpty" class="af-empty" hidden><i class="fas fa-users-slash"></i><strong>No hay clientes para estos filtros</strong></div>
        </div>
        <div class="af-pagination-bar"><span class="af-pagination-summary">Prioriza clientes sin WhatsApp o con cuentas vencidas.</span><div id="clientReportPagination" class="af-pagination"></div></div>
    </section>

    <section class="af-panel">
        <div class="af-panel-head">
            <div class="af-panel-title"><span class="af-panel-title-icon"><i class="fas fa-server"></i></span><div><h2>Buzones y dominios</h2><p>Comprueba qué buzones reciben dominios y cuáles todavía no tienen asignaciones.</p></div></div>
            <a href="gestionar_buzones.php" class="af-btn af-btn-secondary"><i class="fas fa-arrow-right"></i> Gestionar buzones</a>
        </div>
        <div class="af-toolbar compact-3">
            <div class="af-field"><label class="af-label" for="mailboxReportSearch"><i class="fas fa-search"></i> Buscar</label><input id="mailboxReportSearch" type="search" class="af-control" placeholder="Correo, host o proveedor"></div>
            <div class="af-field"><label class="af-label" for="mailboxReportProvider"><i class="fas fa-server"></i> Proveedor</label><select id="mailboxReportProvider" class="af-control"><option value="">Todos</option><?php foreach ($mailboxProviders as $provider): ?><option value="<?= htmlspecialchars($provider, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($provider) ?></option><?php endforeach; ?></select></div>
            <div class="af-field"><label class="af-label" for="mailboxReportPerPage"><i class="fas fa-list-ol"></i> Mostrar</label><select id="mailboxReportPerPage" class="af-control"><option value="100">100 registros</option><option value="200">200 registros</option><option value="400">400 registros</option><option value="all">Todos</option></select></div>
            <div class="af-toolbar-actions"><button type="button" id="clearMailboxReportFilters" class="af-btn af-btn-secondary"><i class="fas fa-eraser"></i> Limpiar</button></div>
        </div>
        <div class="af-list-meta"><span><?= number_format($totalMailboxes) ?> buzones · <?= number_format($totalDomains) ?> dominios</span><span id="mailboxReportSummary"></span></div>
        <div class="af-table-wrap">
            <table id="mailboxReportTable" class="af-table">
                <thead><tr><th>Buzón</th><th>Proveedor</th><th>Servidor</th><th>Renovación</th><th>Dominios</th></tr></thead>
                <tbody>
                <?php foreach ($mailboxesReport as $row):
                    $mailboxRenewal = !empty($row['fecha_renovacion']) ? strtotime((string) $row['fecha_renovacion']) : null;
                    $mailboxExpired = $mailboxRenewal !== null && $mailboxRenewal < strtotime(date('Y-m-d'));
                    $providerName = trim((string) ($row['proveedor'] ?? 'Manual')) ?: 'Manual';
                ?>
                    <tr data-af-row data-provider="<?= htmlspecialchars($providerName, ENT_QUOTES, 'UTF-8') ?>" data-search="<?= htmlspecialchars(($row['imap_usuario'] ?? '') . ' ' . ($row['imap_host'] ?? '') . ' ' . $providerName, ENT_QUOTES, 'UTF-8') ?>">
                        <td><span class="af-row-title"><?= htmlspecialchars((string) $row['imap_usuario']) ?></span></td>
                        <td><span class="af-badge af-badge-neutral"><i class="fas fa-envelope-open-text"></i><?= htmlspecialchars($providerName) ?></span></td>
                        <td><span class="af-row-title"><?= htmlspecialchars((string) $row['imap_host']) ?></span><span class="af-row-sub">Puerto <?= (int) $row['imap_puerto'] ?></span></td>
                        <td><?php if ($mailboxRenewal): ?><span class="af-badge <?= $mailboxExpired ? 'af-badge-danger' : 'af-badge-success' ?>"><i class="fas fa-calendar"></i><?= date('d/m/Y', $mailboxRenewal) ?></span><?php else: ?><span class="af-badge af-badge-neutral">Sin fecha</span><?php endif; ?></td>
                        <td><span class="af-badge <?= (int) $row['total_dominios'] > 0 ? 'af-badge-success' : 'af-badge-warning' ?>"><i class="fas fa-at"></i><?= number_format((int) $row['total_dominios']) ?></span></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <div id="mailboxReportEmpty" class="af-empty" hidden><i class="fas fa-inbox"></i><strong>No hay buzones para estos filtros</strong></div>
        </div>
        <div class="af-pagination-bar"><span class="af-pagination-summary">Un buzón sin dominios todavía no participa en las consultas.</span><div id="mailboxReportPagination" class="af-pagination"></div></div>
    </section>

    <section class="af-panel">
        <div class="af-panel-head">
            <div class="af-panel-title"><span class="af-panel-title-icon"><i class="fas fa-calendar-day"></i></span><div><h2>Cuentas próximas a vencer</h2><p>Prioriza vencidas, renovaciones urgentes y próximas fechas con filtros independientes.</p></div></div>
            <a href="gestionar_cuentas.php" class="af-btn af-btn-primary"><i class="fas fa-arrow-right"></i> Gestionar cuentas</a>
        </div>
        <div class="af-toolbar af-renewal-toolbar">
            <div class="af-field"><label class="af-label" for="renewalSearch"><i class="fas fa-search"></i> Buscar</label><input id="renewalSearch" type="search" class="af-control" placeholder="Correo, plataforma, cliente o teléfono"></div>
            <div class="af-field"><label class="af-label" for="renewalState"><i class="fas fa-calendar-check"></i> Prioridad</label><select id="renewalState" class="af-control"><option value="">🔎 Todas</option><option value="expired">🔴 Vencidas</option><option value="today">🟠 Vencen hoy</option><option value="urgent">🟡 1 a 7 días</option><option value="soon">🔵 8 a 15 días</option><option value="later">🟢 16 a 30 días</option></select></div>
            <div class="af-field"><label class="af-label" for="renewalPlatform"><i class="fas fa-tv"></i> Plataforma</label><select id="renewalPlatform" class="af-control"><option value="">Todas</option><?php foreach ($renewalPlatforms as $platformId => $platformName): ?><option value="<?= (int) $platformId ?>"><?= htmlspecialchars($platformName) ?></option><?php endforeach; ?></select></div>
            <div class="af-field"><label class="af-label" for="renewalClient"><i class="fas fa-user"></i> Cliente</label><select id="renewalClient" class="af-control"><option value="">Todos</option><option value="none">Sin asignar</option><?php foreach ($renewalClients as $clientId => $clientName): ?><option value="<?= (int) $clientId ?>"><?= htmlspecialchars($clientName) ?></option><?php endforeach; ?></select></div>
            <div class="af-field"><label class="af-label" for="renewalPerPage"><i class="fas fa-list-ol"></i> Mostrar</label><select id="renewalPerPage" class="af-control"><option value="100">100 registros</option><option value="200">200 registros</option><option value="400">400 registros</option><option value="all">Todos</option></select></div>
            <div class="af-toolbar-actions"><button type="button" id="clearRenewalFilters" class="af-btn af-btn-secondary"><i class="fas fa-eraser"></i> Limpiar</button></div>
        </div>
        <div class="af-list-meta"><span><strong><?= number_format($renewalCounters['expired']) ?></strong> vencidas · <strong><?= number_format($renewalCounters['today']) ?></strong> hoy · <strong><?= number_format($renewalCounters['urgent']) ?></strong> en 7 días</span><span id="renewalSummary"></span></div>
        <div class="af-table-wrap">
            <table id="renewalTable" class="af-table">
                <thead><tr><th>Cuenta</th><th>Plataforma</th><th>Cliente</th><th>Renovación</th><th>Prioridad</th><th class="af-text-center">Contacto</th></tr></thead>
                <tbody>
                <?php foreach ($renewalsReport as $row):
                    $view = af_report_renewal_view($row);
                    $date = !empty($row['fecha_renovacion']) ? strtotime((string) $row['fecha_renovacion']) : null;
                    $clientKey = !empty($row['cliente_id']) ? (string) $row['cliente_id'] : 'none';
                    $phone = preg_replace('/\D+/', '', (string) ($row['cliente_telefono'] ?? ''));
                    $clientName = trim((string) ($row['cliente_asociado'] ?? '')) ?: 'cliente';
                    $dateLabel = $date ? date('d/m/Y', $date) : 'sin fecha';
                    $statusLine = $view['state'] === 'expired'
                        ? "🔴 *Estado:* venció el {$dateLabel}"
                        : ($view['state'] === 'today'
                            ? "🟠 *Estado:* vence hoy, {$dateLabel}"
                            : "🟡 *Estado:* {$view['detail']}");
                    $message = "🔔 *RECORDATORIO DE RENOVACIÓN*\n\n"
                        . "Hola *{$clientName}*, esperamos que te encuentres bien.\n\n"
                        . "📺 *Servicio:* {$row['plataforma_nombre']}\n"
                        . "📧 *Cuenta:* {$row['correo']}\n"
                        . "📅 *Renovación:* {$dateLabel}\n"
                        . $statusLine . "\n\n"
                        . "✅ *Para renovar:* responde a este mensaje y te ayudaremos de inmediato.\n"
                        . "🙌 Gracias por confiar en nuestro servicio.";
                ?>
                    <tr data-af-row data-state="<?= htmlspecialchars($view['state']) ?>" data-platform="<?= (int) ($row['plataforma_id'] ?? 0) ?>" data-client="<?= htmlspecialchars($clientKey, ENT_QUOTES, 'UTF-8') ?>" data-search="<?= htmlspecialchars(($row['correo'] ?? '') . ' ' . ($row['plataforma_nombre'] ?? '') . ' ' . ($row['cliente_asociado'] ?? '') . ' ' . ($row['cliente_telefono'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
                        <td><span class="af-row-title"><?= htmlspecialchars((string) $row['correo']) ?></span><span class="af-row-sub">Cuenta #<?= (int) $row['id'] ?></span></td>
                        <td><span class="af-badge af-badge-neutral"><i class="fas fa-tv"></i><?= htmlspecialchars((string) $row['plataforma_nombre']) ?></span></td>
                        <td><span class="af-row-title"><?= htmlspecialchars((string) ($row['cliente_asociado'] ?? 'Sin asignar')) ?></span><?php if ($phone !== ''): ?><span class="af-row-sub">+<?= htmlspecialchars($phone) ?></span><?php endif; ?></td>
                        <td><strong><?= htmlspecialchars($dateLabel) ?></strong></td>
                        <td><div class="af-status-stack"><span class="af-badge <?= htmlspecialchars($view['badge']) ?>"><i class="fas <?= $view['state'] === 'expired' || $view['state'] === 'today' ? 'fa-circle-exclamation' : ($view['state'] === 'urgent' || $view['state'] === 'soon' ? 'fa-clock' : 'fa-calendar-check') ?>"></i><?= htmlspecialchars($view['label']) ?></span><span class="af-status-detail"><?= htmlspecialchars($view['detail']) ?></span></div></td>
                        <td><div class="af-actions af-actions-center"><?php if ($phone !== ''): ?><a class="af-btn af-whatsapp-btn af-btn-icon" href="https://wa.me/<?= htmlspecialchars($phone) ?>?text=<?= rawurlencode($message) ?>" target="_blank" rel="noopener" title="Enviar recordatorio por WhatsApp"><i class="fab fa-whatsapp"></i></a><?php else: ?><button type="button" class="af-btn af-whatsapp-btn af-btn-icon" disabled title="Cliente sin teléfono"><i class="fab fa-whatsapp"></i></button><?php endif; ?></div></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <div id="renewalEmpty" class="af-empty" hidden><i class="fas fa-calendar-check"></i><strong>No hay renovaciones para estos filtros</strong><div>Prueba otra prioridad, plataforma o cliente.</div></div>
        </div>
        <div class="af-pagination-bar"><span class="af-pagination-summary">Las cuentas vencidas aparecen primero para facilitar la renovación.</span><div id="renewalPagination" class="af-pagination"></div></div>
    </section>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const clientList = new AfenixAdmin.UnifiedList({
        table: '#clientReportTable',
        search: '#clientReportSearch',
        perPage: '#clientReportPerPage',
        filters: [
            {selector: '#clientReportRole', data: 'role'},
            {selector: '#clientReportWhatsapp', data: 'whatsapp'}
        ],
        summary: '#clientReportSummary',
        pagination: '#clientReportPagination',
        empty: '#clientReportEmpty'
    });
    document.getElementById('clearClientReportFilters').addEventListener('click', () => {
        ['clientReportSearch', 'clientReportRole', 'clientReportWhatsapp'].forEach((id) => {
            document.getElementById(id).value = '';
        });
        document.getElementById('clientReportPerPage').value = '100';
        clientList.currentPage = 1;
        clientList.render();
    });

    const mailboxList = new AfenixAdmin.UnifiedList({
        table: '#mailboxReportTable',
        search: '#mailboxReportSearch',
        perPage: '#mailboxReportPerPage',
        filters: [{selector: '#mailboxReportProvider', data: 'provider'}],
        summary: '#mailboxReportSummary',
        pagination: '#mailboxReportPagination',
        empty: '#mailboxReportEmpty'
    });
    document.getElementById('clearMailboxReportFilters').addEventListener('click', () => {
        document.getElementById('mailboxReportSearch').value = '';
        document.getElementById('mailboxReportProvider').value = '';
        document.getElementById('mailboxReportPerPage').value = '100';
        mailboxList.currentPage = 1;
        mailboxList.render();
    });

    const renewalList = new AfenixAdmin.UnifiedList({
        table: '#renewalTable',
        search: '#renewalSearch',
        perPage: '#renewalPerPage',
        filters: [
            {selector: '#renewalState', data: 'state'},
            {selector: '#renewalPlatform', data: 'platform'},
            {selector: '#renewalClient', data: 'client'}
        ],
        summary: '#renewalSummary',
        pagination: '#renewalPagination',
        empty: '#renewalEmpty'
    });
    document.getElementById('clearRenewalFilters').addEventListener('click', () => {
        ['renewalSearch', 'renewalState', 'renewalPlatform', 'renewalClient'].forEach((id) => {
            document.getElementById(id).value = '';
        });
        document.getElementById('renewalPerPage').value = '100';
        renewalList.currentPage = 1;
        renewalList.render();
    });

    const platformChart = document.getElementById('platformReportChart');
    if (platformChart) {
        new Chart(platformChart, {
            type: 'bar',
            data: {
                labels: <?= json_encode($platformLabels, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
                datasets: [{label: 'Cuentas', data: <?= json_encode($platformValues) ?>, backgroundColor: 'rgba(220,38,38,.82)', borderRadius: 8}]
            },
            options: {responsive: true, maintainAspectRatio: false, plugins: {legend: {display: false}}, scales: {y: {beginAtZero: true, ticks: {precision: 0}}, x: {grid: {display: false}}}}
        });
    }

    const renewalChart = document.getElementById('renewalReportChart');
    if (renewalChart) {
        new Chart(renewalChart, {
            type: 'doughnut',
            data: {
                labels: <?= json_encode($renewalLabels, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
                datasets: [{data: <?= json_encode($renewalValues) ?>, backgroundColor: ['#dc2626', '#f97316', '#eab308', '#3b82f6', '#16a34a', '#94a3b8'], borderWidth: 0}]
            },
            options: {responsive: true, maintainAspectRatio: false, cutout: '64%', plugins: {legend: {position: 'bottom'}}}
        });
    }

    const roleChart = document.getElementById('roleReportChart');
    if (roleChart) {
        new Chart(roleChart, {
            type: 'doughnut',
            data: {
                labels: <?= json_encode($roleLabels, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
                datasets: [{data: <?= json_encode($roleValues) ?>, backgroundColor: ['#dc2626', '#111827', '#64748b'], borderWidth: 0}]
            },
            options: {responsive: true, maintainAspectRatio: false, cutout: '66%', plugins: {legend: {position: 'bottom'}}}
        });
    }
});
</script>
<?php require_once __DIR__ . '/admin_footer.php'; ob_end_flush(); ?>
