<?php

declare(strict_types=1);

require_once __DIR__ . '/init.php';
require_once __DIR__ . '/../lib/WalletSubscriptionService.php';
require_once __DIR__ . '/../lib/SubscriptionAccessService.php';

if (mb_strtolower(trim((string) ($_SESSION['admin']['rol'] ?? '')), 'UTF-8') !== 'admin') {
    header('Location: index.php?status=warning&msg=' . rawurlencode('Este módulo está disponible únicamente para cuentas Admin.'));
    exit;
}

$adminId = (int) ($_SESSION['admin']['uid'] ?? 0);
$walletService = new WalletSubscriptionService($pdo);
$accessService = new SubscriptionAccessService($pdo);

if (!function_exists('afenixx_wallet_csrf')) {
    function afenixx_wallet_csrf(): string
    {
        if (class_exists('Security')) {
            return Security::csrfToken();
        }
        if (empty($_SESSION['_csrf_wallet'])) {
            $_SESSION['_csrf_wallet'] = bin2hex(random_bytes(24));
        }
        return (string) $_SESSION['_csrf_wallet'];
    }
}

if (!function_exists('afenixx_wallet_check_csrf')) {
    function afenixx_wallet_check_csrf(string $token): bool
    {
        if (class_exists('Security')) {
            return hash_equals(Security::csrfToken(), $token);
        }
        return isset($_SESSION['_csrf_wallet']) && hash_equals((string) $_SESSION['_csrf_wallet'], $token);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!afenixx_wallet_check_csrf((string) ($_POST['csrf_token'] ?? ''))) {
            throw new RuntimeException('La sesión del formulario venció. Actualiza la página e inténtalo nuevamente.');
        }
        if (($_POST['action'] ?? '') !== 'renew_with_credit') {
            throw new InvalidArgumentException('La acción solicitada no es válida.');
        }

        $planId = filter_input(INPUT_POST, 'plan_id', FILTER_VALIDATE_INT) ?: 0;
        $cycle = trim((string) ($_POST['cycle'] ?? ''));
        $idempotency = trim((string) ($_POST['idempotency_key'] ?? ''));

        // Este módulo únicamente permite que cada Admin renueve su propia cuenta.
        $result = $walletService->renewWithCredit($adminId, $adminId, (int) $planId, $cycle, $idempotency);
        $_SESSION['admin']['subscription_status'] = $accessService->statusForAdmin($adminId);
        $_SESSION['subscription_wallet_flash'] = [
            'type' => 'success',
            'message' => 'Renovación completada. Nueva vigencia: ' . date('d/m/Y', strtotime($result['new_end_date']))
                . '. Saldo disponible: ' . $walletService->getCurrencySymbol() . ' ' . number_format($result['balance'], 2) . '.',
        ];
    } catch (Throwable $e) {
        $_SESSION['subscription_wallet_flash'] = [
            'type' => 'error',
            'message' => $e->getMessage(),
        ];
    }

    header('Location: mi_suscripcion.php');
    exit;
}

$flash = $_SESSION['subscription_wallet_flash'] ?? null;
unset($_SESSION['subscription_wallet_flash']);

$currency = $walletService->getCurrency();
$currencySymbol = $walletService->getCurrencySymbol();
$balance = $walletService->getBalance($adminId);
$currentSubscription = $walletService->getCurrentSubscription($adminId);
$status = $accessService->statusForAdmin($adminId);
$plans = $walletService->getAvailablePlans();
$currentCycle = mb_strtolower(trim((string) ($currentSubscription['ciclo_facturacion'] ?? '')), 'UTF-8');
$currentCycleLabel = match ($currentCycle) {
    'mensual' => 'Mensual',
    'anual' => 'Anual',
    'prueba' => 'Prueba',
    'interno' => 'Interno',
    default => 'Sin definir',
};

$rechargeContactName = 'Superadmin';
$rechargeContactRole = 'Superadmin';
$rechargeWhatsapp = '';
try {
    $referrerStmt = $pdo->prepare(
        "SELECT ref.id, ref.nombre_usuario, ref.telefono, rr.nombre_rol
         FROM usuarios current_user
         JOIN usuarios ref ON ref.id = COALESCE(
             NULLIF(current_user.id_referidor, 0),
             (
                 SELECT br.id_referidor
                 FROM beneficios_referidos br
                 WHERE br.id_referido = current_user.id
                 ORDER BY br.id DESC
                 LIMIT 1
             )
         )
         JOIN roles rr ON rr.id = ref.id_rol
         WHERE current_user.id = ?
           AND LOWER(TRIM(rr.nombre_rol)) = 'admin'
         LIMIT 1"
    );
    $referrerStmt->execute([$adminId]);
    $referrer = $referrerStmt->fetch(PDO::FETCH_ASSOC);

    if ($referrer) {
        $rechargeContactName = trim((string) ($referrer['nombre_usuario'] ?? 'Admin responsable')) ?: 'Admin responsable';
        $rechargeContactRole = 'Admin referente';
        $rechargeWhatsapp = preg_replace('/\D+/', '', (string) ($referrer['telefono'] ?? '')) ?: '';
    } else {
        $superadminStmt = $pdo->query(
            "SELECT u.nombre_usuario, u.telefono
             FROM usuarios u
             JOIN roles r ON r.id = u.id_rol
             WHERE r.nombre_rol = 'Superadmin'
             ORDER BY u.id ASC
             LIMIT 1"
        );
        $superadmin = $superadminStmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $rechargeContactName = trim((string) ($superadmin['nombre_usuario'] ?? 'Superadmin')) ?: 'Superadmin';
        $rechargeWhatsapp = preg_replace('/\D+/', '', (string) ($superadmin['telefono'] ?? '')) ?: '';
    }
} catch (Throwable $e) {
    error_log('No se pudo cargar el responsable de recargas: ' . $e->getMessage());
}
$adminRequestName = trim((string) ($_SESSION['admin']['nombre_usuario'] ?? 'Administrador'));
$adminRequestEmail = trim((string) ($_SESSION['admin']['correo'] ?? ''));

$historyStmt = $pdo->prepare(
    "SELECT mc.id, mc.tipo, mc.monto, mc.descripcion, mc.fecha_creacion,
            mc.creado_por, mc.id_usuario_relacionado,
            relacionado.nombre_usuario AS usuario_relacionado,
            creador.nombre_usuario AS usuario_creador,
            rc.id AS renovacion_id, rc.ciclo, rc.fecha_fin_nueva,
            p.nombre_plan
     FROM movimientos_credito mc
     LEFT JOIN usuarios relacionado ON relacionado.id = mc.id_usuario_relacionado
     LEFT JOIN usuarios creador ON creador.id = mc.creado_por
     LEFT JOIN renovaciones_credito rc ON rc.id_movimiento_credito = mc.id
     LEFT JOIN planes p ON p.id = rc.id_plan
     WHERE mc.id_usuario = ?
     ORDER BY mc.fecha_creacion DESC, mc.id DESC"
);
try {
    $historyStmt->execute([$adminId]);
    $history = $historyStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    error_log('Historial de movimientos del monedero: ' . $e->getMessage());
    $history = [];
}

$titulo_pagina = 'Mi suscripción y saldo';
require_once __DIR__ . '/admin_header.php';
?>

<div class="wallet-page-shell">
    <section class="wallet-hero">
        <div>
            <span class="wallet-eyebrow"><i class="fas fa-wallet"></i> Suscripción y monedero</span>
            <h2>Controla tu vigencia y renueva tu cuenta.</h2>
            <p>Elige un plan mensual o anual, revisa sus beneficios y confirma el descuento desde tu saldo disponible.</p>
        </div>
        <div class="wallet-balance-card">
            <span>Saldo disponible</span>
            <strong><?= htmlspecialchars($currencySymbol) ?> <?= number_format($balance, 2) ?></strong>
            <small><?= htmlspecialchars($currency) ?> · responsable: <?= htmlspecialchars($rechargeContactName) ?></small>
            <button type="button" id="requestWalletRecharge" class="wallet-recharge-hero-btn">
                <i class="fab fa-whatsapp"></i> Solicitar recarga
            </button>
        </div>
    </section>

    <?php if (is_array($flash)): ?>
        <div class="wallet-alert is-<?= $flash['type'] === 'success' ? 'success' : 'danger' ?>" role="alert">
            <i class="fas <?= $flash['type'] === 'success' ? 'fa-circle-check' : 'fa-triangle-exclamation' ?>"></i>
            <span><?= htmlspecialchars((string) $flash['message']) ?></span>
        </div>
    <?php endif; ?>

    <?php if (!$status['operational']): ?>
        <div class="wallet-alert is-danger" role="alert">
            <i class="fas fa-lock"></i>
            <div>
                <strong>Administración temporalmente bloqueada</strong>
                <span><?= htmlspecialchars($status['message']) ?> Renueva tu suscripción para habilitar nuevamente los módulos operativos.</span>
            </div>
        </div>
    <?php endif; ?>

    <div class="wallet-summary-grid">
        <article class="wallet-summary-card">
            <span class="wallet-summary-icon"><i class="fas fa-gem"></i></span>
            <div><small>Plan actual</small><strong><?= htmlspecialchars((string) ($currentSubscription['nombre_plan'] ?? 'Sin plan')) ?></strong></div>
        </article>
        <article class="wallet-summary-card">
            <span class="wallet-summary-icon"><i class="fas fa-calendar-check"></i></span>
            <div><small>Vigencia</small><strong><?= !empty($currentSubscription['fecha_fin']) ? date('d/m/Y', strtotime((string) $currentSubscription['fecha_fin'])) : 'Sin fecha' ?></strong></div>
        </article>
        <article class="wallet-summary-card">
            <span class="wallet-summary-icon"><i class="fas fa-traffic-light"></i></span>
            <div><small>Estado</small><strong class="<?= $status['operational'] ? 'text-emerald-600' : 'text-rose-600' ?>"><?= $status['operational'] ? 'Operativo' : 'Vencido / bloqueado' ?></strong></div>
        </article>
        <article class="wallet-summary-card">
            <span class="wallet-summary-icon"><i class="fas fa-repeat"></i></span>
            <div><small>Modalidad actual</small><strong><?= htmlspecialchars($currentCycleLabel) ?></strong></div>
        </article>
    </div>

    <section class="wallet-panel">
        <div class="wallet-panel-heading">
            <div>
                <span class="wallet-panel-icon"><i class="fas fa-arrows-rotate"></i></span>
                <h3>Renovar mi cuenta</h3>
                <p>Selecciona el plan y la modalidad disponibles. Verás el importe, la fecha actual y la nueva vigencia antes de confirmar.</p>
            </div>
        </div>
        <div class="wallet-renew-overview">
            <div class="wallet-renew-current">
                <span class="wallet-renew-current-icon"><i class="fas fa-gem"></i></span>
                <div>
                    <small>Suscripción actual</small>
                    <strong><?= htmlspecialchars((string) ($currentSubscription['nombre_plan'] ?? 'Sin plan')) ?></strong>
                    <p>
                        <?= !empty($currentSubscription['fecha_fin'])
                            ? 'Vigente hasta el ' . date('d/m/Y', strtotime((string) $currentSubscription['fecha_fin'])) . ' · ' . $currentCycleLabel
                            : 'Aún no tiene una fecha de vigencia registrada.' ?>
                    </p>
                </div>
            </div>
            <button
                type="button"
                class="wallet-open-renew"
                data-current-plan="<?= htmlspecialchars((string) ($currentSubscription['nombre_plan'] ?? 'Sin plan'), ENT_QUOTES) ?>"
                data-current-end="<?= htmlspecialchars((string) ($currentSubscription['fecha_fin'] ?? ''), ENT_QUOTES) ?>"
            >
                <span class="wallet-open-renew-icon"><i class="fas fa-calendar-plus"></i></span>
                <span>
                    <strong>Elegir plan y renovar</strong>
                    <small>Revisa beneficios, modalidad, costo y nueva fecha en un solo formulario.</small>
                </span>
                <i class="fas fa-arrow-right"></i>
            </button>
        </div>
    </section>

    <section class="wallet-panel wallet-recharge-panel">
        <div class="wallet-panel-heading is-responsive">
            <div>
                <span class="wallet-panel-icon is-whatsapp"><i class="fab fa-whatsapp"></i></span>
                <h3>Solicitar recarga de saldo</h3>
                <p>Prepara una solicitud con el importe que necesitas. Antes de enviarla podrás revisar el mensaje o copiarlo.</p>
            </div>
            <button type="button" id="requestWalletRechargeSecondary" class="wallet-whatsapp-btn">
                <i class="fab fa-whatsapp"></i> Solicitar por WhatsApp
            </button>
        </div>
        <div class="wallet-recharge-overview">
            <div>
                <small>¿Cómo funciona?</small>
                <strong>Solicita el saldo y espera la confirmación de <?= htmlspecialchars($rechargeContactName) ?>.</strong>
                <p>La solicitud no modifica tu monedero automáticamente. El saldo aparecerá cuando <?= htmlspecialchars($rechargeContactName) ?> registre o transfiera la recarga.</p>
            </div>
            <div class="wallet-recharge-steps">
                <span><b>1</b> Indica el monto</span>
                <span><b>2</b> Revisa o copia</span>
                <span><b>3</b> Envía por WhatsApp</span>
            </div>
        </div>
    </section>

    <section class="wallet-panel wallet-history-panel">
        <div class="wallet-panel-heading is-responsive">
            <div>
                <span class="wallet-panel-icon"><i class="fas fa-clock-rotate-left"></i></span>
                <h3>Historial de consumos</h3>
                <p>Consulta recargas recibidas, transferencias enviadas, bonos, ajustes y renovaciones descontadas de tu monedero.</p>
            </div>
            <label class="wallet-history-length" for="walletHistoryPerPage">
                <span><i class="fas fa-list-ol"></i> Mostrar</span>
                <select id="walletHistoryPerPage">
                    <option value="100" selected>100 registros</option>
                    <option value="200">200 registros</option>
                    <option value="400">400 registros</option>
                    <option value="all">Todos</option>
                </select>
            </label>
        </div>
        <div class="wallet-history-meta">
            <span><?= number_format(count($history)) ?> movimientos registrados</span>
            <span id="walletHistorySummary">Mostrando 0–0 de 0 registros</span>
        </div>
        <div class="wallet-table-wrap">
            <table class="wallet-table" id="walletHistoryTable">
                <thead><tr><th>Fecha</th><th>Movimiento</th><th>Detalle</th><th>Relacionado</th><th>Plan / vigencia</th><th>Importe</th></tr></thead>
                <tbody>
                <?php if (!$history): ?><tr class="wallet-history-empty-row"><td colspan="6"><div class="wallet-empty">Todavía no hay movimientos registrados en tu monedero.</div></td></tr><?php endif; ?>
                <?php foreach ($history as $item): ?>
                    <?php
                        $movementAmount = (float) ($item['monto'] ?? 0);
                        $movementType = (string) ($item['tipo'] ?? 'ajuste');
                        $isRenewal = !empty($item['renovacion_id']);
                        $movementLabel = match (true) {
                            $isRenewal => 'Renovación',
                            $movementType === 'recarga' && !empty($item['id_usuario_relacionado']) => 'Recarga recibida',
                            $movementType === 'recarga' => 'Recarga',
                            $movementType === 'debito'
                                && (int) ($item['id_usuario_relacionado'] ?? 0) > 0
                                && (int) ($item['id_usuario_relacionado'] ?? 0) !== $adminId => 'Transferencia enviada',
                            $movementType === 'debito' => 'Consumo',
                            $movementType === 'bono_referido' => 'Bono de referido',
                            $movementType === 'reembolso' => 'Reembolso',
                            default => 'Ajuste de saldo',
                        };
                        $movementClass = $movementAmount >= 0 ? 'is-credit' : 'is-debit';
                        $relatedName = trim((string) ($item['usuario_relacionado'] ?? ''));
                        if ((int) ($item['id_usuario_relacionado'] ?? 0) === $adminId) {
                            $relatedName = 'Mi cuenta';
                        }
                        if ($relatedName === '' && !empty($item['usuario_creador']) && (int) ($item['creado_por'] ?? 0) !== $adminId) {
                            $relatedName = (string) $item['usuario_creador'];
                        }
                    ?>
                    <tr data-wallet-history-row>
                        <td><?= date('d/m/Y H:i', strtotime((string) $item['fecha_creacion'])) ?></td>
                        <td><span class="wallet-movement-badge <?= htmlspecialchars($movementClass) ?>"><?= htmlspecialchars($movementLabel) ?></span></td>
                        <td><span class="wallet-history-detail"><?= htmlspecialchars((string) ($item['descripcion'] ?? 'Movimiento de saldo')) ?></span></td>
                        <td><?= $relatedName !== '' ? htmlspecialchars($relatedName) : '—' ?></td>
                        <td>
                            <?php if ($isRenewal): ?>
                                <strong><?= htmlspecialchars((string) ($item['nombre_plan'] ?? 'Plan')) ?></strong>
                                <small><?= htmlspecialchars(ucfirst((string) ($item['ciclo'] ?? ''))) ?> · hasta <?= !empty($item['fecha_fin_nueva']) ? date('d/m/Y', strtotime((string) $item['fecha_fin_nueva'])) : 'sin fecha' ?></small>
                            <?php else: ?>
                                <span>—</span>
                            <?php endif; ?>
                        </td>
                        <td><strong class="wallet-movement-amount <?= htmlspecialchars($movementClass) ?>"><?= $movementAmount >= 0 ? '+' : '-' ?><?= htmlspecialchars($currencySymbol) ?> <?= number_format(abs($movementAmount), 2) ?></strong></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="wallet-history-foot">
            <span>Los movimientos se ordenan desde el más reciente.</span>
            <div id="walletHistoryPagination" class="wallet-history-pagination" aria-label="Paginación del historial"></div>
        </div>
    </section>
</div>

<div id="walletRenewModal" class="wallet-modal" aria-hidden="true">
    <div class="wallet-modal-dialog wallet-modal-dialog-wide" role="dialog" aria-modal="true" aria-labelledby="walletRenewTitle">
        <header>
            <span class="wallet-modal-icon"><i class="fas fa-wallet"></i></span>
            <div>
                <small>RENOVACIÓN CON CRÉDITO</small>
                <h3 id="walletRenewTitle">Seleccionar plan y renovar</h3>
                <p>Compara beneficios y modalidad sin desplazamientos innecesarios.</p>
            </div>
            <button type="button" class="wallet-modal-close" aria-label="Cerrar"><i class="fas fa-xmark"></i></button>
        </header>
        <form method="post" id="walletRenewForm">
            <input type="hidden" name="action" value="renew_with_credit">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(afenixx_wallet_csrf(), ENT_QUOTES) ?>">
            <input type="hidden" name="plan_id" id="walletPlanId">
            <input type="hidden" name="cycle" id="walletCycle" value="">
            <input type="hidden" name="idempotency_key" id="walletIdempotency">
            <div class="wallet-modal-body">
                <div class="wallet-review-card">
                    <span><small>Beneficiario</small><strong>Mi cuenta</strong></span>
                    <span><small>Plan actual</small><strong id="walletCurrentPlan">Sin plan</strong></span>
                    <span><small>Saldo disponible</small><strong><?= htmlspecialchars($currencySymbol) ?> <?= number_format($balance, 2) ?></strong></span>
                </div>

                <div class="wallet-renew-layout">
                    <div class="wallet-renew-main">
                        <div class="wallet-field-block">
                            <label for="walletPlanSelect"><i class="fas fa-layer-group"></i> Plan a renovar</label>
                            <select id="walletPlanSelect" required>
                                <option value="">Selecciona un plan</option>
                                <?php foreach ($plans as $plan): ?>
                                    <option value="<?= (int) $plan['id'] ?>"><?= htmlspecialchars((string) $plan['nombre_plan']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small>Solo aparecen planes públicos, activos y disponibles para renovación.</small>
                        </div>

                        <section id="walletPlanBenefits" class="wallet-plan-benefits" hidden>
                            <div class="wallet-plan-benefits-head">
                                <span class="wallet-plan-benefits-icon"><i class="fas fa-gift"></i></span>
                                <div>
                                    <small>BENEFICIOS DEL PLAN</small>
                                    <h4 id="walletBenefitPlanName">Plan seleccionado</h4>
                                    <p id="walletBenefitDescription"></p>
                                </div>
                            </div>
                            <div id="walletBenefitChips" class="wallet-benefit-chips"></div>
                        </section>
                    </div>

                    <div class="wallet-renew-side">
                        <div id="walletCyclePlaceholder" class="wallet-cycle-placeholder">
                            <i class="fas fa-hand-pointer"></i>
                            <strong>Selecciona un plan</strong>
                            <span>Aquí aparecerán las modalidades habilitadas, el importe y la nueva vigencia.</span>
                        </div>

                        <section id="walletCycleSection" class="wallet-cycle-section" hidden>
                            <div class="wallet-cycle-heading">
                                <div>
                                    <small>MODALIDAD</small>
                                    <strong>Elige el periodo</strong>
                                </div>
                                <span>Solo se habilitan las opciones configuradas.</span>
                            </div>
                            <div class="wallet-cycle-grid">
                                <button type="button" class="wallet-cycle-option" data-cycle="mensual">
                                    <span class="wallet-cycle-option-icon"><i class="fas fa-calendar-day"></i></span>
                                    <span><small>Mensual</small><strong id="walletMonthlyPrice"><?= htmlspecialchars($currencySymbol) ?> 0.00</strong></span>
                                    <i class="fas fa-circle-check wallet-cycle-check"></i>
                                </button>
                                <button type="button" class="wallet-cycle-option" data-cycle="anual">
                                    <span class="wallet-cycle-option-icon"><i class="fas fa-calendar-days"></i></span>
                                    <span><small>Anual</small><strong id="walletAnnualPrice"><?= htmlspecialchars($currencySymbol) ?> 0.00</strong></span>
                                    <i class="fas fa-circle-check wallet-cycle-check"></i>
                                </button>
                            </div>
                        </section>

                        <div id="walletDatePreview" class="wallet-date-preview" hidden>
                            <span>
                                <small>Fecha actual</small>
                                <strong id="walletCurrentEnd">Sin fecha</strong>
                            </span>
                            <i class="fas fa-arrow-right"></i>
                            <span>
                                <small>Nueva vigencia</small>
                                <strong id="walletNewEnd">Selecciona modalidad</strong>
                            </span>
                        </div>

                        <div class="wallet-total">
                            <span>Importe a descontar</span>
                            <strong id="walletAmount"><?= htmlspecialchars($currencySymbol) ?> 0.00</strong>
                        </div>
                        <div id="walletInsufficientAlert" class="wallet-insufficient-alert" hidden>
                            <i class="fas fa-triangle-exclamation"></i>
                            <div>
                                <strong>Saldo insuficiente</strong>
                                <span id="walletInsufficientText">Solicita una recarga para completar la renovación.</span>
                            </div>
                            <button type="button" id="walletRequestRechargeFromRenew"><i class="fab fa-whatsapp"></i> Solicitar recarga</button>
                        </div>
                        <div class="wallet-note">
                            <i class="fas fa-circle-info"></i>
                            <span>Si la cuenta sigue vigente, el periodo se suma a la fecha final actual. Si venció, comienza desde hoy.</span>
                        </div>
                    </div>
                </div>
            </div>
            <footer>
                <button type="button" class="wallet-modal-cancel">Cancelar</button>
                <button type="submit" class="wallet-modal-confirm" disabled><i class="fas fa-circle-check"></i> Confirmar renovación</button>
            </footer>
        </form>
    </div>
</div>

<link rel="stylesheet" href="../assets/css/subscription-wallet.css?v=1.6.0">

<script>
(function () {
    'use strict';

    const modal = document.getElementById('walletRenewModal');
    const form = document.getElementById('walletRenewForm');
    const planSelect = document.getElementById('walletPlanSelect');
    const cycleInput = document.getElementById('walletCycle');
    const submitButton = form?.querySelector('button[type="submit"]');
    const plans = <?= json_encode(array_map(static fn(array $p): array => [
        'id' => (int) $p['id'],
        'name' => (string) $p['nombre_plan'],
        'description' => trim((string) ($p['descripcion'] ?? '')),
        'monthly' => (float) ($p['precio_mensual'] ?? 0),
        'annual' => (float) ($p['precio_anual'] ?? 0),
        'allowMonthly' => (int) ($p['permite_mensual'] ?? 0) === 1,
        'allowAnnual' => (int) ($p['permite_anual'] ?? 0) === 1,
        'mailboxes' => (int) ($p['limite_buzones'] ?? 0),
        'domains' => (int) ($p['limite_dominios'] ?? 0),
        'accounts' => (int) ($p['limite_cuentas'] ?? 0),
        'users' => (int) ($p['limite_usuarios'] ?? 0),
        'queries' => (int) ($p['limite_consultas'] ?? 0),
    ], $plans), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const balance = <?= json_encode((float) $balance) ?>;
    const currencySymbol = <?= json_encode($currencySymbol, JSON_UNESCAPED_UNICODE) ?>;
    const rechargeWhatsapp = <?= json_encode($rechargeWhatsapp) ?>;
    const rechargeContactName = <?= json_encode($rechargeContactName, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const rechargeContactRole = <?= json_encode($rechargeContactRole, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const adminRequestName = <?= json_encode($adminRequestName, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const adminRequestEmail = <?= json_encode($adminRequestEmail, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const currentPlanName = <?= json_encode((string) ($currentSubscription['nombre_plan'] ?? 'Sin plan'), JSON_UNESCAPED_UNICODE) ?>;
    const currentEndValue = <?= json_encode((string) ($currentSubscription['fecha_fin'] ?? ''), JSON_UNESCAPED_UNICODE) ?>;

    const byId = id => document.getElementById(id);
    const selectedPlan = () => plans.find(plan => Number(plan.id) === Number(planSelect?.value)) || null;
    const money = value => currencySymbol + ' ' + Number(value || 0).toFixed(2);
    const cycleAllowed = (plan, cycle) => cycle === 'anual'
        ? Boolean(plan?.allowAnnual) && Number(plan?.annual) > 0
        : Boolean(plan?.allowMonthly) && Number(plan?.monthly) > 0;

    const resourceText = (value, singular, plural) => {
        const amount = Number(value || 0);
        if (amount <= 0) return 'Ilimitado ' + plural;
        return amount + ' ' + (amount === 1 ? singular : plural);
    };

    const randomKey = () => {
        if (window.crypto && window.crypto.getRandomValues) {
            const bytes = new Uint8Array(18);
            window.crypto.getRandomValues(bytes);
            return 'renew_' + Array.from(bytes).map(byte => byte.toString(16).padStart(2, '0')).join('');
        }
        return 'renew_' + Date.now() + '_' + Math.random().toString(36).slice(2, 16);
    };

    const parseDate = value => {
        if (!value) return null;
        const normalized = String(value).trim().replace(' ', 'T');
        const date = new Date(normalized.length === 10 ? normalized + 'T00:00:00' : normalized);
        return Number.isNaN(date.getTime()) ? null : date;
    };

    const startOfToday = () => {
        const date = new Date();
        date.setHours(0, 0, 0, 0);
        return date;
    };

    const formatDate = date => {
        if (!(date instanceof Date) || Number.isNaN(date.getTime())) return 'Sin fecha';
        return new Intl.DateTimeFormat('es-PE', { day: '2-digit', month: '2-digit', year: 'numeric' }).format(date);
    };

    const addCalendarMonths = (date, months) => {
        const result = new Date(date.getTime());
        const originalDay = result.getDate();
        result.setDate(1);
        result.setMonth(result.getMonth() + months);
        const lastDay = new Date(result.getFullYear(), result.getMonth() + 1, 0).getDate();
        result.setDate(Math.min(originalDay, lastDay));
        return result;
    };

    const currentBaseDate = () => {
        const today = startOfToday();
        const currentEnd = parseDate(currentEndValue);
        if (currentEnd) currentEnd.setHours(0, 0, 0, 0);
        return currentEnd && currentEnd > today ? currentEnd : today;
    };

    const resetPlanDetails = () => {
        cycleInput.value = '';
        byId('walletPlanId').value = '';
        byId('walletPlanBenefits').hidden = true;
        byId('walletCycleSection').hidden = true;
        byId('walletCyclePlaceholder').hidden = false;
        byId('walletDatePreview').hidden = true;
        byId('walletAmount').textContent = money(0);
        byId('walletAmount').classList.remove('is-insufficient');
        byId('walletInsufficientAlert').hidden = true;
        byId('walletInsufficientText').textContent = 'Solicita una recarga para completar la renovación.';
        document.querySelectorAll('.wallet-cycle-option').forEach(option => {
            option.classList.remove('is-selected', 'is-disabled');
            option.disabled = false;
        });
        if (submitButton) submitButton.disabled = true;
    };

    const renderBenefits = plan => {
        byId('walletBenefitPlanName').textContent = plan.name;
        byId('walletBenefitDescription').textContent = plan.description || 'Capacidad preparada para administrar accesos, dominios y clientes desde el mismo panel.';
        const benefits = [
            ['fa-inbox', resourceText(plan.mailboxes, 'buzón', 'buzones')],
            ['fa-at', resourceText(plan.domains, 'dominio', 'dominios')],
            ['fa-envelope-open-text', resourceText(plan.accounts, 'cuenta de streaming', 'cuentas de streaming')],
            ['fa-users', resourceText(plan.users, 'cliente/usuario', 'clientes/usuarios')],
            ['fa-magnifying-glass', resourceText(plan.queries, 'consulta pública/mes', 'consultas públicas/mes')]
        ];
        byId('walletBenefitChips').innerHTML = benefits.map(item =>
            '<span><i class="fas ' + item[0] + '"></i><b>' + item[1] + '</b></span>'
        ).join('');
        byId('walletPlanBenefits').hidden = false;
    };

    const renderCycles = plan => {
        byId('walletMonthlyPrice').textContent = cycleAllowed(plan, 'mensual') ? money(plan.monthly) : 'No disponible';
        byId('walletAnnualPrice').textContent = cycleAllowed(plan, 'anual') ? money(plan.annual) : 'No disponible';
        document.querySelectorAll('.wallet-cycle-option').forEach(option => {
            const allowed = cycleAllowed(plan, option.dataset.cycle);
            option.disabled = !allowed;
            option.classList.toggle('is-disabled', !allowed);
            option.classList.remove('is-selected');
        });
        byId('walletCyclePlaceholder').hidden = true;
        byId('walletCycleSection').hidden = false;
    };

    const refreshDateAndAmount = () => {
        const plan = selectedPlan();
        const cycle = cycleInput.value;
        const currentEnd = parseDate(currentEndValue);
        byId('walletCurrentEnd').textContent = currentEnd ? formatDate(currentEnd) : 'Sin fecha vigente';

        if (!plan || !cycle || !cycleAllowed(plan, cycle)) {
            byId('walletDatePreview').hidden = true;
            byId('walletAmount').textContent = money(0);
            byId('walletInsufficientAlert').hidden = true;
            if (submitButton) submitButton.disabled = true;
            return;
        }

        const amount = cycle === 'anual' ? Number(plan.annual) : Number(plan.monthly);
        const newEnd = addCalendarMonths(currentBaseDate(), cycle === 'anual' ? 12 : 1);
        byId('walletNewEnd').textContent = formatDate(newEnd);
        byId('walletDatePreview').hidden = false;
        const insufficient = amount > balance + 0.0001;
        const missing = Math.max(0, amount - balance);
        byId('walletAmount').textContent = money(amount);
        byId('walletAmount').classList.toggle('is-insufficient', insufficient);
        byId('walletInsufficientAlert').hidden = !insufficient;
        byId('walletInsufficientText').textContent = insufficient
            ? `Tu saldo es ${money(balance)} y te faltan ${money(missing)} para renovar este plan.`
            : 'Solicita una recarga para completar la renovación.';
        byId('walletPlanId').value = String(plan.id);
        if (submitButton) submitButton.disabled = amount <= 0 || insufficient;
    };

    const chooseCycle = cycle => {
        const plan = selectedPlan();
        if (!plan || !cycleAllowed(plan, cycle)) return;
        cycleInput.value = cycle;
        document.querySelectorAll('.wallet-cycle-option').forEach(option => {
            option.classList.toggle('is-selected', option.dataset.cycle === cycle);
        });
        refreshDateAndAmount();
    };

    const openRenewModal = button => {
        byId('walletCurrentPlan').textContent = button?.dataset.currentPlan || currentPlanName || 'Sin plan';
        byId('walletIdempotency').value = randomKey();
        planSelect.value = '';
        resetPlanDetails();
        modal.classList.add('is-open');
        modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('overflow-hidden');
        setTimeout(() => planSelect.focus(), 30);
    };

    const closeRenewModal = () => {
        modal.classList.remove('is-open');
        modal.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('overflow-hidden');
        resetPlanDetails();
    };

    document.querySelector('.wallet-open-renew')?.addEventListener('click', event => openRenewModal(event.currentTarget));

    planSelect?.addEventListener('change', () => {
        const plan = selectedPlan();
        resetPlanDetails();
        if (!plan) return;
        renderBenefits(plan);
        renderCycles(plan);
        const defaultCycle = cycleAllowed(plan, 'mensual') ? 'mensual' : (cycleAllowed(plan, 'anual') ? 'anual' : '');
        if (defaultCycle) chooseCycle(defaultCycle);
    });

    document.querySelectorAll('.wallet-cycle-option').forEach(option => {
        option.addEventListener('click', () => chooseCycle(option.dataset.cycle));
    });

    modal.querySelector('.wallet-modal-close')?.addEventListener('click', closeRenewModal);
    modal.querySelector('.wallet-modal-cancel')?.addEventListener('click', closeRenewModal);
    modal.addEventListener('click', event => {
        if (event.target === modal) closeRenewModal();
    });
    window.addEventListener('keydown', event => {
        if (event.key === 'Escape' && modal.classList.contains('is-open')) {
            event.preventDefault();
            event.stopImmediatePropagation();
            closeRenewModal();
        }
    }, true);

    form?.addEventListener('submit', event => {
        const plan = selectedPlan();
        const cycle = cycleInput.value;
        const amount = plan ? (cycle === 'anual' ? Number(plan.annual) : Number(plan.monthly)) : 0;

        if (!plan || !cycle || !cycleAllowed(plan, cycle) || amount <= 0) {
            event.preventDefault();
            window.Swal ? Swal.fire('Atención', 'Selecciona un plan y una modalidad disponible.', 'warning') : alert('Selecciona un plan y una modalidad disponible.');
            return;
        }
        if (amount > balance + 0.0001) {
            event.preventDefault();
            window.Swal ? Swal.fire('Saldo insuficiente', 'Solicita una recarga antes de confirmar la renovación.', 'warning') : alert('El saldo disponible no alcanza para esta renovación.');
            return;
        }

        byId('walletPlanId').value = String(plan.id);
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Procesando renovación…';
    });

    const escapeHtml = value => String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');

    const formatWhatsAppPreview = message => escapeHtml(message)
        .replace(/\*([^*]+)\*/g, '<strong>$1</strong>')
        .replace(/\n/g, '<br>');

    const copyText = async text => {
        if (navigator.clipboard && window.isSecureContext) {
            await navigator.clipboard.writeText(text);
            return;
        }
        const area = document.createElement('textarea');
        area.value = text;
        area.style.position = 'fixed';
        area.style.opacity = '0';
        document.body.appendChild(area);
        area.select();
        const copied = document.execCommand('copy');
        area.remove();
        if (!copied) throw new Error('No se pudo copiar.');
    };

    const requestRecharge = async () => {
        if (!window.Swal) return;

        const request = await Swal.fire({
            title: '<span class="wallet-request-title"><i class="fas fa-wallet"></i> Solicitar recarga de saldo</span>',
            html: `<div class="wallet-request-form">
                <div class="wallet-request-guide">
                    <i class="fas fa-circle-info"></i>
                    <div>
                        <strong>La solicitud será enviada a ${escapeHtml(rechargeContactName)}.</strong>
                        <p>${escapeHtml(rechargeContactRole)} revisará el pago y registrará o transferirá el saldo a tu monedero. Esta solicitud no modifica el saldo automáticamente.</p>
                    </div>
                </div>
                <div class="wallet-request-summary">
                    <span><small>Solicitante</small><strong>${escapeHtml(adminRequestName || 'Administrador')}</strong></span>
                    <span><small>Plan actual</small><strong>${escapeHtml(currentPlanName || 'Sin plan')}</strong></span>
                    <span><small>Saldo disponible</small><strong>${escapeHtml(money(balance))}</strong></span>
                    <span><small>Responsable</small><strong>${escapeHtml(rechargeContactName)}</strong></span>
                </div>
                <div class="wallet-request-field">
                    <label for="walletRechargeAmount"><i class="fas fa-coins"></i> Monto solicitado (${escapeHtml(currencySymbol)}) <span>*</span></label>
                    <input id="walletRechargeAmount" class="wallet-request-control" type="number" min="0.01" step="0.01" inputmode="decimal" placeholder="Ejemplo: 50.00">
                    <small>Indica el importe exacto que necesitas recibir en tu monedero.</small>
                </div>
                <div class="wallet-request-field">
                    <label for="walletRechargeDetail"><i class="fas fa-receipt"></i> Referencia o detalle <em>Opcional</em></label>
                    <textarea id="walletRechargeDetail" class="wallet-request-control wallet-request-textarea" maxlength="300" placeholder="Ejemplo: pago realizado por Yape, operación 123456"></textarea>
                    <small>Puedes agregar el medio de pago, número de operación o una observación breve.</small>
                </div>
                <div class="wallet-request-reminder">
                    <i class="fas fa-shield-halved"></i>
                    <div>
                        <strong>Confirmación necesaria</strong>
                        <p>Espera la confirmación de ${escapeHtml(rechargeContactName)} antes de intentar renovar. El nuevo saldo aparecerá en esta misma página.</p>
                    </div>
                </div>
            </div>`,
            customClass: {
                popup: 'wallet-request-popup',
                htmlContainer: 'wallet-request-html',
                confirmButton: 'wallet-request-confirm',
                cancelButton: 'wallet-request-cancel'
            },
            buttonsStyling: false,
            showCancelButton: true,
            confirmButtonText: '<i class="fas fa-wand-magic-sparkles"></i> Preparar solicitud',
            cancelButtonText: 'Cancelar',
            width: 590,
            focusConfirm: false,
            didOpen: () => document.getElementById('walletRechargeAmount')?.focus(),
            preConfirm: () => {
                const amount = Number(document.getElementById('walletRechargeAmount')?.value || 0);
                const detail = String(document.getElementById('walletRechargeDetail')?.value || '').trim();
                if (!Number.isFinite(amount) || amount <= 0) {
                    Swal.showValidationMessage('Escribe un monto mayor que cero.');
                    return false;
                }
                return { amount, detail };
            }
        });

        if (!request.isConfirmed || !request.value) return;

        const data = request.value;
        const message = `💳 *SOLICITUD DE RECARGA DE SALDO*\n\n`
            + `Hola *${rechargeContactName || 'Administrador responsable'}* 👋\n\n`
            + `Solicito una recarga para mantener activa mi suscripción en *Ave Fénix*.\n\n`
            + `👤 *Administrador solicitante:* ${adminRequestName || 'Administrador'}\n`
            + (adminRequestEmail ? `📧 *Correo:* ${adminRequestEmail}\n` : '')
            + `📦 *Plan actual:* ${currentPlanName || 'Sin plan'}\n`
            + `💰 *Saldo disponible:* ${money(balance)}\n`
            + `➕ *Monto solicitado:* ${money(data.amount)}\n`
            + (data.detail ? `🧾 *Referencia o detalle:* ${data.detail}\n` : '')
            + `\n✅ *Acción requerida:* registrar o transferir la recarga a mi monedero y confirmarme cuando el saldo esté disponible.\n\n`
            + `Gracias por la atención.`;

        const preview = await Swal.fire({
            title: 'Solicitud lista para enviar',
            html: `<div style="text-align:left">
                <p style="margin:0 0 12px;color:#64748b;font-size:13px">Revisa el mensaje antes de copiarlo o enviarlo a ${escapeHtml(rechargeContactName)}.</p>
                ${rechargeWhatsapp === '' ? '<div style="margin-bottom:12px;padding:10px 12px;border-radius:10px;background:#fff7e3;color:#9a6700">El responsable no tiene un teléfono registrado. Puedes copiar la solicitud y enviarla manualmente.</div>' : ''}
                <div style="max-height:360px;overflow:auto;background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px;padding:16px;line-height:1.65;color:#1e293b">${formatWhatsAppPreview(message)}</div>
            </div>`,
            icon: 'info',
            showCancelButton: true,
            showDenyButton: true,
            showConfirmButton: rechargeWhatsapp !== '',
            confirmButtonText: '<i class="fab fa-whatsapp"></i> Enviar por WhatsApp',
            denyButtonText: '<i class="fas fa-copy"></i> Copiar solicitud',
            cancelButtonText: 'Cancelar',
            confirmButtonColor: '#16a34a',
            denyButtonColor: '#475569',
            reverseButtons: true,
            width: 610
        });

        if (preview.isConfirmed && rechargeWhatsapp !== '') {
            window.open(`https://wa.me/${rechargeWhatsapp}?text=${encodeURIComponent(message)}`, '_blank', 'noopener');
        } else if (preview.isDenied) {
            try {
                await copyText(message);
                await Swal.fire({icon: 'success', title: 'Solicitud copiada', text: 'El mensaje está listo para pegarse en WhatsApp.', timer: 1700, showConfirmButton: false});
            } catch (error) {
                await Swal.fire('No se pudo copiar', 'Selecciona el mensaje y cópialo manualmente.', 'error');
            }
        }
    };

    const historyRows = [...document.querySelectorAll('[data-wallet-history-row]')];
    const historyPerPage = byId('walletHistoryPerPage');
    const historySummary = byId('walletHistorySummary');
    const historyPagination = byId('walletHistoryPagination');
    let historyPage = 1;

    const renderHistory = () => {
        const total = historyRows.length;
        const raw = historyPerPage?.value || '100';
        const perPage = raw === 'all' ? Math.max(total, 1) : Math.max(1, Number(raw) || 100);
        const pages = Math.max(1, Math.ceil(total / perPage));
        historyPage = Math.min(Math.max(historyPage, 1), pages);
        const start = total ? (historyPage - 1) * perPage : 0;
        const end = total ? Math.min(start + perPage, total) : 0;

        historyRows.forEach((row, index) => {
            row.hidden = index < start || index >= end;
        });
        if (historySummary) {
            historySummary.textContent = `Mostrando ${total ? start + 1 : 0}–${end} de ${total} registros`;
        }
        if (!historyPagination) return;
        if (total === 0 || pages <= 1) {
            historyPagination.innerHTML = '';
            return;
        }

        const buttons = [];
        buttons.push(`<button type="button" data-history-page="prev" ${historyPage === 1 ? 'disabled' : ''} aria-label="Página anterior"><i class="fas fa-chevron-left"></i></button>`);
        for (let page = 1; page <= pages; page++) {
            if (pages <= 5 || page === 1 || page === pages || Math.abs(page - historyPage) <= 1) {
                buttons.push(`<button type="button" data-history-page="${page}" class="${page === historyPage ? 'is-active' : ''}">${page}</button>`);
            } else if (page === historyPage - 2 || page === historyPage + 2) {
                buttons.push('<span>…</span>');
            }
        }
        buttons.push(`<button type="button" data-history-page="next" ${historyPage === pages ? 'disabled' : ''} aria-label="Página siguiente"><i class="fas fa-chevron-right"></i></button>`);
        historyPagination.innerHTML = buttons.join('');
    };

    historyPerPage?.addEventListener('change', () => {
        historyPage = 1;
        renderHistory();
    });
    historyPagination?.addEventListener('click', event => {
        const button = event.target.closest('[data-history-page]');
        if (!button || button.disabled) return;
        const target = button.dataset.historyPage;
        if (target === 'prev') historyPage -= 1;
        else if (target === 'next') historyPage += 1;
        else historyPage = Number(target) || 1;
        renderHistory();
    });
    renderHistory();

    byId('requestWalletRecharge')?.addEventListener('click', requestRecharge);
    byId('requestWalletRechargeSecondary')?.addEventListener('click', requestRecharge);
    byId('walletRequestRechargeFromRenew')?.addEventListener('click', () => {
        closeRenewModal();
        requestRecharge();
    });
})();
</script>

<?php require_once __DIR__ . '/admin_footer.php'; ?>
