<?php

declare(strict_types=1);

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

Security::headers(false);

if (($_SESSION['admin']['rol'] ?? '') !== 'Superadmin') {
    header('Location: index.php?status=warning&msg=' . urlencode('El módulo de créditos está disponible únicamente para el Superadmin.'));
    exit;
}

function afenixx_credit_schema_ready(PDO $pdo): bool
{
    $required = ['configuracion_sistema', 'monederos', 'movimientos_credito'];
    $placeholders = implode(',', array_fill(0, count($required), '?'));
    $stmt = $pdo->prepare(
        "SELECT table_name FROM information_schema.tables "
        . "WHERE table_schema = DATABASE() AND table_name IN ($placeholders)"
    );
    $stmt->execute($required);
    return count($stmt->fetchAll(PDO::FETCH_COLUMN)) === count($required);
}

function afenixx_credit_has_column(PDO $pdo, string $table, string $column): bool
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*) FROM information_schema.COLUMNS
         WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?'
    );
    $stmt->execute([$table, $column]);
    return (int) $stmt->fetchColumn() > 0;
}

$service = new WalletSubscriptionService($pdo);
$schemaReady = false;
$incomeTrackingReady = false;
$flash = $_SESSION['credit_wallet_flash'] ?? null;
unset($_SESSION['credit_wallet_flash']);
$message = is_array($flash) && ($flash['type'] ?? '') === 'success' ? (string) ($flash['message'] ?? '') : '';
$error = is_array($flash) && ($flash['type'] ?? '') === 'error' ? (string) ($flash['message'] ?? '') : '';
$currency = $ui_currency ?? 'PEN';
$users = [];
$movements = [];
$totalBalance = 0.0;
$walletsWithBalance = 0;

try {
    $schemaReady = afenixx_credit_schema_ready($pdo);
    $incomeTrackingReady = $schemaReady
        && afenixx_credit_has_column($pdo, 'pagos', 'tipo_ingreso')
        && afenixx_credit_has_column($pdo, 'pagos', 'credito_otorgado')
        && afenixx_credit_has_column($pdo, 'pagos', 'id_movimiento_credito');
} catch (Throwable $e) {
    error_log('No se pudo comprobar el esquema de créditos: ' . $e->getMessage());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Security::requireCsrf();
    if (!$schemaReady) {
        $error = 'No están disponibles las tablas requeridas para créditos y monederos. Revisa la base de datos antes de registrar recargas.';
    } else {
        try {
            $userId = filter_input(INPUT_POST, 'id_usuario', FILTER_VALIDATE_INT);
            $creditRaw = str_replace(',', '.', trim((string) ($_POST['monto'] ?? '')));
            $receivedRaw = str_replace(',', '.', trim((string) ($_POST['monto_recibido'] ?? '0')));
            $creditAmount = filter_var($creditRaw, FILTER_VALIDATE_FLOAT);
            $receivedAmount = $receivedRaw === '' ? 0.0 : filter_var($receivedRaw, FILTER_VALIDATE_FLOAT);
            $description = trim((string) ($_POST['descripcion'] ?? 'Recarga administrativa'));

            if (!$userId || $creditAmount === false || $creditAmount <= 0) {
                throw new InvalidArgumentException('Selecciona un Admin e ingresa un saldo a acreditar mayor que cero.');
            }
            if ($receivedAmount === false || $receivedAmount < 0) {
                throw new InvalidArgumentException('El dinero recibido debe ser cero o un importe válido.');
            }
            $creditAmount = round((float) $creditAmount, 2);
            $receivedAmount = round((float) $receivedAmount, 2);
            if ($description === '') {
                $description = 'Recarga administrativa';
            }
            if ($receivedAmount > 0 && !$incomeTrackingReady) {
                throw new RuntimeException('Importa primero el SQL V10 para registrar el dinero recibido como ingreso.');
            }

            $checkUser = $pdo->prepare(
                "SELECT u.id, r.nombre_rol,
                        (SELECT s.id FROM suscripciones s
                         WHERE s.id_admin = u.id
                         ORDER BY CASE WHEN s.estado IN ('activa','prueba') THEN 0 ELSE 1 END, s.id DESC
                         LIMIT 1) AS id_suscripcion
                 FROM usuarios u
                 JOIN roles r ON r.id = u.id_rol
                 WHERE u.id = ?
                 LIMIT 1"
            );
            $checkUser->execute([$userId]);
            $recipient = $checkUser->fetch(PDO::FETCH_ASSOC);
            if (!$recipient) {
                throw new RuntimeException('El usuario seleccionado ya no existe.');
            }
            if (mb_strtolower(trim((string) ($recipient['nombre_rol'] ?? '')), 'UTF-8') !== 'admin') {
                throw new RuntimeException('Las recargas comerciales solo pueden asignarse a cuentas con rol Admin.');
            }
            if ($receivedAmount > 0 && (int) ($recipient['id_suscripcion'] ?? 0) <= 0) {
                throw new RuntimeException('El Admin no tiene una suscripción asociada para registrar el ingreso.');
            }

            $pdo->beginTransaction();
            $movementId = $service->addCredit(
                (int) $userId,
                $creditAmount,
                'recarga',
                function_exists('mb_substr') ? mb_substr($description, 0, 255) : substr($description, 0, 255),
                (int) ($_SESSION['admin']['uid'] ?? 0)
            );

            if ($receivedAmount > 0) {
                $paymentKey = 'credit_' . bin2hex(random_bytes(20));
                $paymentNotes = sprintf(
                    '%s Dinero recibido: %.2f PEN. Saldo acreditado: %.2f PEN.',
                    $description,
                    $receivedAmount,
                    $creditAmount
                );
                $payment = $pdo->prepare(
                    "INSERT INTO pagos
                        (id_suscripcion, monto, credito_otorgado, id_movimiento_credito,
                         ciclo, tipo_ingreso, moneda, fecha_pago, metodo_pago, notas,
                         clave_idempotencia, estado_pago, registrado_por_admin_id)
                     VALUES (?, ?, ?, ?, 'manual', 'recarga_saldo', 'PEN', NOW(),
                             'recarga_saldo', ?, ?, 'confirmado', ?)"
                );
                $payment->execute([
                    (int) $recipient['id_suscripcion'],
                    $receivedAmount,
                    $creditAmount,
                    $movementId,
                    $paymentNotes,
                    $paymentKey,
                    (int) ($_SESSION['admin']['uid'] ?? 0),
                ]);
            }

            $pdo->commit();
            $_SESSION['credit_wallet_flash'] = [
                'type' => 'success',
                'message' => $receivedAmount > 0
                    ? 'Se acreditó ' . number_format($creditAmount, 2) . ' ' . $currency
                        . ' y se registró un ingreso real de ' . number_format($receivedAmount, 2) . ' ' . $currency . '.'
                    : 'Se acreditó ' . number_format($creditAmount, 2) . ' ' . $currency . ' sin registrar ingreso de dinero.',
            ];
            header('Location: gestionar_creditos.php');
            exit;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = $e->getMessage();
        }
    }
}

if ($schemaReady) {
    try {
        $currency = $service->getCurrency();
        $users = $pdo->query(
            "SELECT u.id, u.nombre_usuario, u.correo, COALESCE(m.saldo, 0) AS saldo, "
            . "m.fecha_actualizacion AS saldo_actualizado, p.nombre_plan, "
            . "s.ciclo_facturacion, s.fecha_fin, s.estado AS estado_suscripcion, "
            . "ref.nombre_usuario AS nombre_referidor "
            . "FROM usuarios u "
            . "JOIN roles r ON r.id = u.id_rol AND r.nombre_rol IN ('Admin', 'Ayudante de Superadmin') "
            . "LEFT JOIN monederos m ON m.id_usuario = u.id "
            . "LEFT JOIN planes p ON p.id = u.id_plan "
            . "LEFT JOIN (SELECT id_admin, MAX(id) AS id_ultima FROM suscripciones GROUP BY id_admin) ult ON ult.id_admin = u.id "
            . "LEFT JOIN suscripciones s ON s.id = ult.id_ultima "
            . "LEFT JOIN usuarios ref ON ref.id = u.id_referidor "
            . "ORDER BY u.nombre_usuario ASC, u.correo ASC"
        )->fetchAll(PDO::FETCH_ASSOC);

        $movements = $pdo->query(
            "SELECT mc.id, mc.tipo, mc.monto, mc.descripcion, mc.fecha_creacion, "
            . "u.nombre_usuario, u.correo, cr.nombre_usuario AS creador "
            . "FROM movimientos_credito mc "
            . "JOIN usuarios u ON u.id = mc.id_usuario "
            . "LEFT JOIN usuarios cr ON cr.id = mc.creado_por "
            . "ORDER BY mc.id DESC"
        )->fetchAll(PDO::FETCH_ASSOC);

        foreach ($users as $user) {
            $balance = (float) $user['saldo'];
            $totalBalance += $balance;
            if ($balance > 0) {
                $walletsWithBalance++;
            }
        }
    } catch (Throwable $e) {
        error_log('Error cargando el módulo de créditos: ' . $e->getMessage());
        $error = 'No se pudo cargar el historial de créditos. Revisa que la migración esté completa.';
        $users = [];
        $movements = [];
    }
}

$titulo_pagina = 'Créditos y monederos';
require_once 'admin_header.php';
?>
<link rel="stylesheet" href="../assets/css/superadmin-commercial.css?v=1.0.0">
<div class="super-commercial-ui px-4 md:px-6 pb-8">
  <div class="sc-shell">
    <?php if (!$schemaReady): ?><div class="sc-alert error"><i class="fas fa-database"></i><div><strong>Módulo pendiente de instalación</strong><br>La recarga permanece deshabilitada hasta que existan las tablas <code>configuracion_sistema</code>, <code>monederos</code> y <code>movimientos_credito</code>.</div></div><?php endif; ?>
    <?php if ($message !== ''): ?><div class="sc-alert success"><i class="fas fa-circle-check"></i><div><strong>Recarga completada</strong><br><?= htmlspecialchars($message) ?></div></div><?php endif; ?>
    <?php if ($error !== ''): ?><div class="sc-alert error"><i class="fas fa-triangle-exclamation"></i><div><strong>No se pudo completar la operación</strong><br><?= htmlspecialchars($error) ?></div></div><?php endif; ?>
    <section class="sc-card sc-hero">
      <div class="sc-hero-main"><span class="sc-icon"><i class="fas fa-wallet"></i></span><div><div class="sc-eyebrow">Saldo y movimientos</div><h1 class="sc-title">Créditos</h1><p class="sc-copy">Administra los monederos de los usuarios, registra recargas y conserva un historial auditable de cada movimiento.</p></div></div>
      <div class="sc-actions"><button type="button" id="openCreditModalBtn" class="sc-btn-primary" <?= !$schemaReady ? 'disabled' : '' ?>><i class="fas fa-plus"></i> Recargar saldo</button></div>
    </section>
    <section class="sc-stats">
      <article class="sc-stat"><span class="sc-stat-icon"><i class="fas fa-coins"></i></span><div><div class="sc-stat-label">Saldo emitido</div><div class="sc-stat-value"><?= number_format($totalBalance,2) ?></div><div class="sc-stat-note"><?= htmlspecialchars($currency) ?> disponibles</div></div></article>
      <article class="sc-stat"><span class="sc-stat-icon green"><i class="fas fa-wallet"></i></span><div><div class="sc-stat-label">Monederos con saldo</div><div class="sc-stat-value"><?= number_format($walletsWithBalance) ?></div><div class="sc-stat-note">Usuarios con crédito positivo</div></div></article>
      <article class="sc-stat"><span class="sc-stat-icon blue"><i class="fas fa-receipt"></i></span><div><div class="sc-stat-label">Movimientos</div><div class="sc-stat-value"><?= count($movements) ?></div><div class="sc-stat-note">Registros disponibles</div></div></article>
      <article class="sc-stat"><span class="sc-stat-icon amber"><i class="fas fa-money-bill"></i></span><div><div class="sc-stat-label">Moneda global</div><div class="sc-stat-value" style="font-size:18px"><?= htmlspecialchars($currency) ?></div><div class="sc-stat-note">Usada en saldos y renovaciones</div></div></article>
    </section>
    <section class="sc-card sc-records wallet-admin-section">
      <div class="sc-records-head"><span class="sc-section-icon"><i class="fas fa-users-gear"></i></span><div><h2 class="sc-records-title">Saldos de administradores</h2><p class="sc-records-copy">Revisa en un solo lugar el saldo, plan, vigencia y referente de cada Admin.</p></div></div>
      <div class="sc-toolbar wallet-toolbar">
        <div class="wallet-search"><label class="sc-label" for="walletAdminSearch"><i class="fas fa-search"></i>Buscar</label><div class="sc-search"><i class="fas fa-search"></i><input type="search" id="walletAdminSearch" class="sc-field" placeholder="Nombre, correo, plan o referente"></div></div>
        <div><label class="sc-label" for="walletBalanceFilter"><i class="fas fa-wallet"></i>Saldo</label><select id="walletBalanceFilter" class="sc-field"><option value="">Todos</option><option value="positive">Con saldo</option><option value="zero">Sin saldo</option></select></div>
        <div class="wallet-toolbar-end"><div><label class="sc-label" for="walletPageLength"><i class="fas fa-list-ol"></i>Mostrar</label><select id="walletPageLength" class="sc-field"><option value="100" selected>100 registros</option><option value="200">200 registros</option><option value="400">400 registros</option><option value="-1">Todos</option></select></div><button type="button" id="clearWalletFilters" class="sc-btn-secondary"><i class="fas fa-eraser"></i> Limpiar</button></div>
      </div>
      <div class="sc-summary"><span><?= count($users) ?> Admins registrados</span><span id="walletInfo">Mostrando 0–0 de 0 registros</span></div>
      <div class="sc-table-wrap"><table id="walletBalancesTable"><thead><tr><th>Admin</th><th>Plan</th><th>Vigencia</th><th>Referente</th><th class="text-right">Saldo</th><th>Actualizado</th><th>Acciones</th></tr></thead><tbody>
      <?php foreach($users as $user): $balance=(float)$user['saldo']; $endDate=!empty($user['fecha_fin'])?strtotime((string)$user['fecha_fin']):false; ?>
        <tr data-balance="<?= htmlspecialchars((string)$balance) ?>">
          <td><strong><?= htmlspecialchars($user['nombre_usuario']) ?></strong><div class="sc-muted"><?= htmlspecialchars($user['correo']) ?></div></td>
          <td><strong><?= htmlspecialchars((string)($user['nombre_plan'] ?: 'Sin plan')) ?></strong><div class="sc-muted"><?= htmlspecialchars(ucfirst((string)($user['ciclo_facturacion'] ?: 'sin modalidad'))) ?></div></td>
          <td><?php if($endDate): ?><strong><?= date('d/m/Y',$endDate) ?></strong><div class="sc-muted"><?= htmlspecialchars(ucfirst((string)($user['estado_suscripcion'] ?: 'sin estado'))) ?></div><?php else: ?><span class="sc-muted">Sin vigencia</span><?php endif; ?></td>
          <td><?= htmlspecialchars((string)($user['nombre_referidor'] ?: 'Superadmin / directo')) ?></td>
          <td class="text-right" data-order="<?= htmlspecialchars((string)$balance) ?>"><strong class="wallet-balance <?= $balance>0?'is-positive':'is-zero' ?>"><?= htmlspecialchars($currency) ?> <?= number_format($balance,2) ?></strong></td>
          <td><?= !empty($user['saldo_actualizado'])?date('d/m/Y H:i',strtotime((string)$user['saldo_actualizado'])):'Sin movimientos' ?></td>
          <td><div class="sc-actions-row"><button type="button" class="sc-action wallet-recharge-btn" title="Recargar saldo" data-id="<?= (int)$user['id'] ?>"><i class="fas fa-plus"></i></button><button type="button" class="sc-action wallet-movements-btn" title="Ver movimientos" data-email="<?= htmlspecialchars($user['correo'],ENT_QUOTES) ?>"><i class="fas fa-receipt"></i></button></div></td>
        </tr>
      <?php endforeach; ?>
      </tbody></table></div>
      <div class="sc-table-foot"><span>El saldo disponible se utiliza para renovaciones y transferencias autorizadas.</span><div id="walletPagination" class="sc-pagination"></div></div>
    </section>

    <section class="sc-card sc-records" id="creditMovementSection">
      <div class="sc-records-head"><span class="sc-section-icon"><i class="fas fa-list"></i></span><div><h2 class="sc-records-title">Historial de créditos</h2><p class="sc-records-copy">Consulta recargas, bonos, consumos y ajustes asociados a cada usuario.</p></div></div>
      <div class="sc-toolbar cols-4">
        <div><label class="sc-label" for="creditMovementSearch"><i class="fas fa-search"></i>Buscar</label><div class="sc-search"><i class="fas fa-search"></i><input type="search" id="creditMovementSearch" class="sc-field" placeholder="Usuario, correo, concepto o creador"></div></div>
        <div><label class="sc-label" for="creditTypeFilter"><i class="fas fa-tags"></i>Tipo</label><select id="creditTypeFilter" class="sc-field"><option value="">Todos los tipos</option><?php $creditTypes=[]; foreach($movements as $m){$creditTypes[$m['tipo']]=$m['tipo'];} ksort($creditTypes); foreach($creditTypes as $type): ?><option value="<?= htmlspecialchars(ucfirst(str_replace('_',' ',$type))) ?>"><?= htmlspecialchars(ucfirst(str_replace('_',' ',$type))) ?></option><?php endforeach; ?></select></div>
        <div><label class="sc-label" for="creditPageLength"><i class="fas fa-list-ol"></i>Mostrar</label><select id="creditPageLength" class="sc-field"><option value="100" selected>100 registros</option><option value="200">200 registros</option><option value="400">400 registros</option><option value="-1">Todos</option></select></div>
        <div class="sc-filter-actions"><button type="button" id="clearCreditFilters" class="sc-btn-secondary"><i class="fas fa-eraser"></i> Limpiar</button></div>
      </div>
      <div class="sc-summary"><span><?= count($movements) ?> movimientos registrados</span><span id="creditInfo">Mostrando 0–0 de 0 registros</span></div>
      <div class="sc-table-wrap"><table id="creditMovementsTable"><thead><tr><th>Fecha</th><th>Usuario</th><th>Tipo</th><th>Concepto</th><th>Registrado por</th><th class="text-right">Monto</th></tr></thead><tbody>
      <?php foreach($movements as $movement): $amount=(float)$movement['monto']; $typeLabel=ucfirst(str_replace('_',' ',$movement['tipo'])); ?>
        <tr><td class="whitespace-nowrap"><?= date('d/m/Y H:i',strtotime($movement['fecha_creacion'])) ?></td><td><strong><?= htmlspecialchars($movement['nombre_usuario']) ?></strong><div class="sc-muted"><?= htmlspecialchars($movement['correo']) ?></div></td><td><span class="sc-pill blue"><?= htmlspecialchars($typeLabel) ?></span></td><td><?= htmlspecialchars($movement['descripcion']) ?></td><td><?= htmlspecialchars($movement['creador'] ?: 'Sistema') ?></td><td class="text-right font-bold <?= $amount>=0?'text-emerald-600':'text-rose-600' ?>"><?= $amount>=0?'+':'' ?><?= number_format($amount,2) ?> <?= htmlspecialchars($currency) ?></td></tr>
      <?php endforeach; ?>
      </tbody></table></div>
      <div class="sc-table-foot"><span>Los movimientos conservan la trazabilidad del usuario beneficiario, el concepto y el responsable que realizó el registro.</span><div id="creditPagination" class="sc-pagination"></div></div>
    </section>
  </div>
</div>

<div id="creditModal" class="super-commercial-ui sc-modal fixed inset-0 hidden items-center justify-center z-[2147483000] px-3 py-4">
  <div class="sc-modal-shell">
    <div class="sc-modal-head">
      <div class="sc-modal-main">
        <span class="sc-modal-icon"><i class="fas fa-wallet"></i></span>
        <div>
          <div class="sc-modal-kicker">Créditos · formulario</div>
          <div class="sc-modal-title">Recargar saldo</div>
          <p class="sc-modal-copy">Busca al Admin y separa el dinero realmente recibido del saldo que entregarás.</p>
        </div>
      </div>
      <button type="button" class="sc-modal-close close-credit-modal"><i class="fas fa-times"></i></button>
    </div>
    <form method="post" id="creditRechargeForm" class="contents" autocomplete="off">
      <?= Security::csrfField() ?>
      <div class="sc-modal-body">
        <div class="sc-note"><i class="fas fa-circle-info"></i><span>El saldo acreditado aumenta el monedero. Solo el dinero realmente recibido se registra como ingreso en Pagos.</span></div>
        <div class="credit-admin-picker">
          <label class="sc-label" for="creditAdminSearch"><i class="fas fa-search"></i>Buscar Admin</label>
          <div class="sc-search"><i class="fas fa-search"></i><input type="search" id="creditAdminSearch" class="sc-field" placeholder="Escribe nombre o correo" <?= !$schemaReady?'disabled':'' ?>></div>
          <div id="creditAdminSearchMeta" class="credit-admin-search-meta"><?= count($users) ?> Admins disponibles</div>
        </div>
        <div>
          <label class="sc-label" for="id_usuario"><i class="fas fa-user-check"></i>Admin beneficiario *</label>
          <select name="id_usuario" id="id_usuario" required class="sc-field" <?= !$schemaReady?'disabled':'' ?>>
            <option value="">Seleccionar Admin</option>
            <?php foreach($users as $user): ?>
              <option value="<?= (int)$user['id'] ?>"><?= htmlspecialchars($user['nombre_usuario'].' · '.$user['correo'].' · '.$currency.' '.number_format((float)$user['saldo'],2)) ?></option>
            <?php endforeach; ?>
          </select>
          <div class="sc-help">El saldo actual aparece al final de cada opción.</div>
        </div>
        <div class="sc-grid-2">
          <div><label class="sc-label" for="monto"><i class="fas fa-wallet"></i>Saldo a acreditar (<?= htmlspecialchars($currency) ?>) *</label><input name="monto" id="monto" type="number" min="0.01" step="0.01" inputmode="decimal" required class="sc-field" placeholder="130.00" <?= !$schemaReady?'disabled':'' ?>><div class="sc-help">Importe que aparecerá en el monedero del Admin.</div></div>
          <div><label class="sc-label" for="monto_recibido"><i class="fas fa-money-bill-wave"></i>Dinero realmente recibido (<?= htmlspecialchars($currency) ?>)</label><input name="monto_recibido" id="monto_recibido" type="number" min="0" step="0.01" inputmode="decimal" class="sc-field" placeholder="100.00" <?= !$schemaReady?'disabled':'' ?>><div class="sc-help">Este importe se mostrará como ingreso en Gestionar pagos.</div></div>
        </div>
        <div id="creditBreakdown" class="credit-breakdown"><span><i class="fas fa-gift"></i> Bonificación o diferencia</span><strong>0.00 <?= htmlspecialchars($currency) ?></strong></div>
        <div><label class="sc-label" for="descripcion"><i class="fas fa-align-left"></i>Concepto *</label><input name="descripcion" id="descripcion" maxlength="255" value="Recarga administrativa" class="sc-field" <?= !$schemaReady?'disabled':'' ?>></div>
      </div>
      <div class="sc-modal-foot"><button type="button" class="sc-btn-secondary close-credit-modal">Cancelar</button><button type="submit" class="sc-btn-primary" <?= !$schemaReady?'disabled':'' ?>><i class="fas fa-plus"></i> Agregar crédito</button></div>
    </form>
  </div>
</div>

<style>
.credit-admin-picker{display:grid;gap:6px}
.credit-admin-search-meta{color:#64748b;font-size:10px;font-weight:750}
.credit-admin-search-meta.is-empty{color:#b91c1c}
.wallet-admin-section{margin-bottom:18px}
.wallet-toolbar{display:grid;grid-template-columns:minmax(260px,1.35fr) minmax(150px,.55fr) minmax(300px,auto);gap:12px;align-items:end}
.wallet-toolbar-end{display:flex;justify-content:flex-end;align-items:end;gap:10px}
.wallet-toolbar-end>div{width:150px}
.wallet-balance{display:inline-flex;padding:6px 9px;border-radius:9px;font-size:12px;white-space:nowrap}
.wallet-balance.is-positive{color:#166534;background:#dcfce7}
.wallet-balance.is-zero{color:#64748b;background:#f1f5f9}
.sc-actions-row{display:flex;gap:6px;justify-content:flex-end}
.credit-breakdown{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:11px 13px;border:1px solid #dbeafe;background:#eff6ff;border-radius:12px;color:#1e3a8a;font-size:12px}.credit-breakdown strong{font-size:14px}.credit-breakdown.is-negative{border-color:#fecaca;background:#fef2f2;color:#991b1b}
@media(max-width:980px){.wallet-toolbar{grid-template-columns:1fr 180px}.wallet-toolbar-end{grid-column:1/-1}.wallet-toolbar-end>div{width:180px}}
@media(max-width:640px){.wallet-toolbar{grid-template-columns:1fr}.wallet-toolbar-end{grid-column:auto;display:grid;grid-template-columns:1fr auto}.wallet-toolbar-end>div{width:auto}}
</style>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(function(){
    let walletBalanceMode='';
    $.fn.dataTable.ext.search.push(function(settings,data,index){
        if(settings.nTable.id!=='walletBalancesTable'||!walletBalanceMode)return true;
        const row=settings.aoData[index]?.nTr;
        const balance=parseFloat(row?.dataset?.balance||'0');
        return walletBalanceMode==='positive'?balance>0:balance<=0;
    });
    const walletTable=$('#walletBalancesTable').DataTable({dom:'t',language:{url:'//cdn.datatables.net/plug-ins/1.11.3/i18n/es_es.json'},pageLength:100,lengthMenu:[[100,200,400,-1],[100,200,400,'Todos']],order:[[4,'desc']],autoWidth:false,columnDefs:[{orderable:false,targets:[6]}]});
    function renderWalletPagination(){
        const info=walletTable.page.info(),total=info.recordsDisplay||0,start=total?info.start+1:0,end=total?info.end:0,pages=info.pages||0,current=info.page||0;
        $('#walletInfo').text(`Mostrando ${start}–${end} de ${total} registros`);
        let html=`<button class="sc-page" data-page="prev" ${current===0||!pages?'disabled':''}><i class="fas fa-chevron-left"></i></button>`;
        if(!pages)html+='<button class="sc-page active" disabled>1</button>';
        else for(let page=0;page<pages;page++){if(pages<=5||page===0||page===pages-1||Math.abs(page-current)<=1)html+=`<button class="sc-page ${page===current?'active':''}" data-page="${page}">${page+1}</button>`;else if(page===current-2||page===current+2)html+='<span>…</span>'}
        html+=`<button class="sc-page" data-page="next" ${current>=pages-1||!pages?'disabled':''}><i class="fas fa-chevron-right"></i></button>`;
        $('#walletPagination').html(html);
    }
    $('#walletAdminSearch').on('input',function(){walletTable.search(this.value).draw()});
    $('#walletBalanceFilter').on('change',function(){walletBalanceMode=this.value;walletTable.draw()});
    $('#walletPageLength').on('change',function(){walletTable.page.len(parseInt(this.value,10)).draw()});
    $('#clearWalletFilters').on('click',function(){$('#walletAdminSearch,#walletBalanceFilter').val('');$('#walletPageLength').val('100');walletBalanceMode='';walletTable.search('').page.len(100).draw()});
    walletTable.on('draw page.dt search.dt length.dt',renderWalletPagination);renderWalletPagination();
    $('#walletPagination').on('click','.sc-page',function(){if(this.disabled)return;const page=$(this).data('page');if(page==='prev')walletTable.page('previous').draw('page');else if(page==='next')walletTable.page('next').draw('page');else walletTable.page(parseInt(page,10)).draw('page')});

    const table=$('#creditMovementsTable').DataTable({
        dom:'t',
        language:{url:'//cdn.datatables.net/plug-ins/1.11.3/i18n/es_es.json'},
        pageLength:100,
        lengthMenu:[[100,200,400,-1],[100,200,400,'Todos']],
        order:[],
        autoWidth:false
    });

    function render(){
        const info=table.page.info(),total=info.recordsDisplay||0,start=total?info.start+1:0,end=total?info.end:0,pages=info.pages||0,current=info.page||0;
        $('#creditInfo').text(`Mostrando ${start}–${end} de ${total} registros`);
        let html=`<button class="sc-page" data-page="prev" ${current===0||!pages?'disabled':''}><i class="fas fa-chevron-left"></i></button>`;
        if(!pages)html+='<button class="sc-page active" disabled>1</button>';
        else for(let page=0;page<pages;page++){
            if(pages<=5||page===0||page===pages-1||Math.abs(page-current)<=1)html+=`<button class="sc-page ${page===current?'active':''}" data-page="${page}">${page+1}</button>`;
            else if(page===current-2||page===current+2)html+='<span>…</span>';
        }
        html+=`<button class="sc-page" data-page="next" ${current>=pages-1||!pages?'disabled':''}><i class="fas fa-chevron-right"></i></button>`;
        $('#creditPagination').html(html);
    }

    $('#creditMovementSearch').on('input',function(){table.search(this.value).draw()});
    $('#creditTypeFilter').on('change',function(){table.column(2).search(this.value?`^${this.value}$`:'',true,false).draw()});
    $('#creditPageLength').on('change',function(){table.page.len(parseInt(this.value,10)).draw()});
    $('#clearCreditFilters').on('click',function(){
        $('#creditMovementSearch').val('');
        $('#creditTypeFilter').val('');
        table.search('').columns().search('').draw();
    });
    table.on('draw page.dt search.dt length.dt',render);
    render();

    $('#creditPagination').on('click','.sc-page',function(){
        if(this.disabled)return;
        const page=$(this).data('page');
        if(page==='prev')table.page('previous').draw('page');
        else if(page==='next')table.page('next').draw('page');
        else table.page(parseInt(page,10)).draw('page');
    });

    const adminSelect=document.getElementById('id_usuario');
    const adminSearch=document.getElementById('creditAdminSearch');
    const adminMeta=document.getElementById('creditAdminSearchMeta');
    const adminOptions=adminSelect
        ? Array.from(adminSelect.options).slice(1).map(option=>({
            value:option.value,
            label:option.textContent||'',
            search:(option.textContent||'').toLocaleLowerCase('es')
        }))
        : [];

    function renderAdminOptions(){
        if(!adminSelect)return;
        const query=String(adminSearch?.value||'').trim().toLocaleLowerCase('es');
        const selected=adminSelect.value;
        const matches=adminOptions.filter(option=>!query||option.search.includes(query));
        adminSelect.innerHTML='';
        const placeholder=document.createElement('option');
        placeholder.value='';
        placeholder.textContent=matches.length?'Seleccionar Admin':'Sin coincidencias';
        adminSelect.appendChild(placeholder);
        matches.forEach(data=>{
            const option=document.createElement('option');
            option.value=data.value;
            option.textContent=data.label;
            option.selected=data.value===selected;
            adminSelect.appendChild(option);
        });
        if(adminMeta){
            adminMeta.textContent=query
                ? `${matches.length} coincidencia${matches.length===1?'':'s'}`
                : `${adminOptions.length} Admins disponibles`;
            adminMeta.classList.toggle('is-empty',matches.length===0);
        }
    }

    adminSearch?.addEventListener('input',renderAdminOptions);

    function updateCreditBreakdown(){
        const credited=Number(document.getElementById('monto')?.value||0);
        const received=Number(document.getElementById('monto_recibido')?.value||0);
        const difference=credited-received;
        const box=document.getElementById('creditBreakdown');
        if(!box)return;
        box.classList.toggle('is-negative',difference<0);
        box.querySelector('span').innerHTML=difference>=0
            ? '<i class="fas fa-gift"></i> Bonificación o diferencia'
            : '<i class="fas fa-triangle-exclamation"></i> Dinero recibido sobre el saldo';
        box.querySelector('strong').textContent=`${difference.toLocaleString('es-PE',{minimumFractionDigits:2,maximumFractionDigits:2})} <?= htmlspecialchars($currency) ?>`;
    }
    $('#monto,#monto_recibido').on('input',updateCreditBreakdown);

    $('#creditRechargeForm').on('submit',function(){
        const button=$(this).find('button[type="submit"]');
        button.prop('disabled',true).html('<i class="fas fa-spinner fa-spin"></i> Registrando…');
    });

    const modal=$('#creditModal');
    function close(){
        $('body').removeClass('overflow-hidden sc-commercial-modal-open');
        modal.addClass('hidden').removeClass('flex');
    }
    function openCreditModal(preselectedId=''){
        if(document.getElementById('openCreditModalBtn')?.disabled)return;
        if(adminSearch)adminSearch.value='';
        if(adminSelect)adminSelect.value='';
        const creditInput=document.getElementById('monto');
        const receivedInput=document.getElementById('monto_recibido');
        if(creditInput)creditInput.value='';
        if(receivedInput)receivedInput.value='';
        updateCreditBreakdown();
        renderAdminOptions();
        if(preselectedId&&adminSelect)adminSelect.value=String(preselectedId);
        $('body').addClass('overflow-hidden sc-commercial-modal-open');
        modal.removeClass('hidden').addClass('flex');
        setTimeout(()=>preselectedId?document.getElementById('monto')?.focus():adminSearch?.focus(),60);
    }
    $('#openCreditModalBtn').on('click',()=>openCreditModal());
    $('#walletBalancesTable').on('click','.wallet-recharge-btn',function(){openCreditModal($(this).data('id'))});
    $('#walletBalancesTable').on('click','.wallet-movements-btn',function(){
        const email=String($(this).data('email')||'');
        $('#creditMovementSearch').val(email);
        table.search(email).draw();
        document.getElementById('creditMovementSection')?.scrollIntoView({behavior:'smooth',block:'start'});
    });
    $('.close-credit-modal').on('click',close);
    modal.on('click',function(event){if(event.target===this)close()});
    $(document).on('keydown.creditModal',function(event){if(event.key==='Escape')close()});
});
</script>
<?php require_once 'admin_footer.php'; ?>
