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

if (!tiene_permiso('gestionar_pruebas')) {
    header('Location: index.php?status=error&msg=' . urlencode('No tienes permiso para ver esta página.'));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'liberar_prueba') {
    Security::headers(true);
    Security::requireCsrf();

    $trackingId = filter_input(INPUT_POST, 'tracking_id', FILTER_VALIDATE_INT) ?: 0;
    $userId = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT) ?: 0;
    $email = strtolower(trim((string) ($_POST['email'] ?? '')));
    $ipAddress = trim((string) ($_POST['ip_address'] ?? ''));

    try {
        $conditions = [];
        $params = [];
        if ($trackingId > 0) { $conditions[] = 'id = ?'; $params[] = $trackingId; }
        if ($userId > 0) { $conditions[] = 'id_usuario_registrado = ?'; $params[] = $userId; }
        if ($email !== '') { $conditions[] = 'LOWER(TRIM(identificador_correo)) = ?'; $params[] = $email; }
        if ($ipAddress !== '' && $ipAddress !== '0.0.0.0') { $conditions[] = 'ip_address = ?'; $params[] = $ipAddress; }
        if (!$conditions) {
            throw new RuntimeException('No se recibió un identificador válido para liberar.');
        }

        $stmt = $pdo->prepare('DELETE FROM pruebas_gratuitas WHERE ' . implode(' OR ', $conditions));
        $stmt->execute($params);
        if ($ipAddress !== '' && $ipAddress !== '0.0.0.0') {
            Security::clearRateLimit('register:' . $ipAddress);
        }

        Security::json([
            'success' => true,
            'message' => $stmt->rowCount() > 0
                ? 'Se eliminó el bloqueo histórico de la prueba. La cuenta y su suscripción no fueron eliminadas.'
                : 'La cuenta de prueba no tenía un bloqueo histórico pendiente. Se limpió el límite temporal de su IP cuando fue posible.',
        ]);
    } catch (Throwable $e) {
        Security::json(['success' => false, 'message' => $e->getMessage()], 422);
    }
}

$errorMessage = '';
$trackingRows = [];
$trialAccounts = [];

try {
    $trackingRows = $pdo->query(
        "SELECT pt.id AS tracking_id, pt.ip_address, LOWER(TRIM(pt.identificador_correo)) AS email,
                pt.id_usuario_registrado AS user_id, pt.fecha_registro,
                u.nombre_usuario, u.correo AS user_email
         FROM pruebas_gratuitas pt
         LEFT JOIN usuarios u ON u.id = pt.id_usuario_registrado
         ORDER BY pt.fecha_registro DESC"
    )->fetchAll(PDO::FETCH_ASSOC);

    $trialAccounts = $pdo->query(
        "SELECT u.id AS user_id, u.nombre_usuario, LOWER(TRIM(u.correo)) AS email,
                COALESCE(NULLIF(TRIM(u.ip_registro), ''), '0.0.0.0') AS ip_address,
                s.id AS subscription_id, s.fecha_inicio, s.fecha_fin, s.estado, s.ciclo_facturacion,
                p.nombre_plan
         FROM usuarios u
         JOIN suscripciones s ON s.id = (
             SELECT sx.id
             FROM suscripciones sx
             JOIN planes px ON px.id = sx.id_plan
             WHERE sx.id_admin = u.id
               AND (LOWER(TRIM(sx.estado)) = 'prueba'
                    OR LOWER(TRIM(COALESCE(sx.ciclo_facturacion, ''))) = 'prueba'
                    OR LOWER(TRIM(px.nombre_plan)) = 'gratis')
             ORDER BY sx.id DESC
             LIMIT 1
         )
         JOIN planes p ON p.id = s.id_plan
         WHERE u.correo IS NOT NULL AND TRIM(u.correo) <> ''
         ORDER BY s.fecha_inicio DESC, s.id DESC"
    )->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    error_log('gestionar_pruebas carga: ' . $e->getMessage());
    $errorMessage = 'No se pudieron cargar las pruebas. Revisa que las tablas pruebas_gratuitas, suscripciones, usuarios y planes estén actualizadas.';
}

$records = [];
$recordIndex = [];
foreach ($trackingRows as $row) {
    $email = strtolower(trim((string) ($row['email'] ?: $row['user_email'] ?? '')));
    $userId = (int) ($row['user_id'] ?? 0);
    $key = $userId > 0 ? 'user:' . $userId : 'email:' . $email;
    if ($key === 'email:') $key = 'tracking:' . (int) $row['tracking_id'];
    $recordIndex[$key] = count($records);
    $records[] = [
        'tracking_id' => (int) $row['tracking_id'],
        'user_id' => $userId,
        'subscription_id' => 0,
        'name' => trim((string) ($row['nombre_usuario'] ?? '')),
        'email' => $email,
        'ip_address' => trim((string) ($row['ip_address'] ?? '0.0.0.0')) ?: '0.0.0.0',
        'plan' => '',
        'state' => '',
        'cycle' => '',
        'start_date' => null,
        'end_date' => null,
        'registered_at' => $row['fecha_registro'] ?? null,
        'kind' => 'history',
    ];
}

foreach ($trialAccounts as $row) {
    $email = strtolower(trim((string) ($row['email'] ?? '')));
    $userId = (int) ($row['user_id'] ?? 0);
    $key = $userId > 0 ? 'user:' . $userId : 'email:' . $email;
    $data = [
        'user_id' => $userId,
        'subscription_id' => (int) ($row['subscription_id'] ?? 0),
        'name' => trim((string) ($row['nombre_usuario'] ?? '')),
        'email' => $email,
        'ip_address' => trim((string) ($row['ip_address'] ?? '0.0.0.0')) ?: '0.0.0.0',
        'plan' => trim((string) ($row['nombre_plan'] ?? 'Gratis')),
        'state' => trim((string) ($row['estado'] ?? 'prueba')),
        'cycle' => trim((string) ($row['ciclo_facturacion'] ?? 'prueba')),
        'start_date' => $row['fecha_inicio'] ?? null,
        'end_date' => $row['fecha_fin'] ?? null,
        'kind' => 'current',
    ];
    if (isset($recordIndex[$key])) {
        $index = $recordIndex[$key];
        $records[$index] = array_merge($records[$index], $data, ['tracking_id' => (int) $records[$index]['tracking_id'], 'registered_at' => $records[$index]['registered_at']]);
    } else {
        $recordIndex[$key] = count($records);
        $records[] = array_merge(['tracking_id' => 0, 'registered_at' => null], $data);
    }
}

usort($records, static function(array $a, array $b): int {
    $dateA = strtotime((string) ($a['start_date'] ?: $a['registered_at'] ?: '1970-01-01')) ?: 0;
    $dateB = strtotime((string) ($b['start_date'] ?: $b['registered_at'] ?: '1970-01-01')) ?: 0;
    return $dateB <=> $dateA;
});

$currentCount = count(array_filter($records, static fn(array $row): bool => $row['kind'] === 'current'));
$blockedCount = count(array_filter($records, static fn(array $row): bool => (int) $row['tracking_id'] > 0));
$linkedCount = count(array_filter($records, static fn(array $row): bool => (int) $row['user_id'] > 0));
$planNames = array_values(array_unique(array_filter(array_map(static fn(array $row): string => (string) $row['plan'], $records))));
sort($planNames, SORT_NATURAL | SORT_FLAG_CASE);

$titulo_pagina = 'Liberar Pruebas Gratuitas';
require_once 'admin_header.php';
require_once __DIR__ . '/includes/superadmin_ui_helpers.php';
?>
<div class="sa-page">
<?php
sa_render_module_hero([
    'icon'=>'fa-flask-vial',
    'eyebrow'=>'CONTROL DE PRUEBAS',
    'title'=>'Liberar pruebas',
    'description'=>'',
    'count'=>count($records),
]);
sa_render_summary_cards([
    ['label'=>'Registros visibles','value'=>count($records),'icon'=>'fa-flask','hint'=>'Pruebas e historial detectado'],
    ['label'=>'Pruebas actuales','value'=>$currentCount,'icon'=>'fa-hourglass-half','tone'=>'is-blue','hint'=>'Suscripciones o plan Gratis'],
    ['label'=>'Con bloqueo','value'=>$blockedCount,'icon'=>'fa-lock','tone'=>'is-amber','hint'=>'Pueden ser liberadas'],
    ['label'=>'Usuarios vinculados','value'=>$linkedCount,'icon'=>'fa-user-check','tone'=>'is-green','hint'=>'Cuentas existentes'],
]);
?>
<?php if ($errorMessage !== ''): ?><div class="sa-alert sa-alert--danger"><i class="fas fa-triangle-exclamation"></i><div><?= sa_e($errorMessage) ?></div></div><?php endif; ?>

<section class="sa-records-panel">
    <header class="sa-records-panel__header"><div class="sa-records-panel__heading"><span class="sa-records-panel__icon"><i class="fas fa-list-ul"></i></span><div><h2>Registros de pruebas utilizadas</h2><p>La lista se obtiene directamente de las suscripciones en prueba y del historial de bloqueos; por eso también muestra pruebas antiguas que no fueron registradas en la tabla de control.</p></div></div></header>
    <div class="sa-records-filters">
        <div class="sa-filter-field"><label for="trialSearch"><i class="fas fa-magnifying-glass"></i> Buscar</label><div class="sa-filter-control"><i class="fas fa-magnifying-glass"></i><input id="trialSearch" type="search" placeholder="Nombre, correo, IP o plan"></div></div>
        <div class="sa-filter-field"><label for="trialType"><i class="fas fa-filter"></i> Tipo</label><select id="trialType"><option value="">Todos</option><option value="current">Pruebas actuales</option><option value="history">Solo historial</option></select></div>
        <div class="sa-filter-field"><label for="trialBlock"><i class="fas fa-lock"></i> Bloqueo</label><select id="trialBlock"><option value="">Todos</option><option value="blocked">Con bloqueo</option><option value="free">Sin bloqueo</option></select></div>
        <div class="sa-filter-field"><label for="trialPlan"><i class="fas fa-layer-group"></i> Plan</label><select id="trialPlan"><option value="">Todos</option><?php foreach ($planNames as $planName): ?><option value="<?= sa_e($planName) ?>"><?= sa_e($planName) ?></option><?php endforeach; ?></select></div>
        <div class="sa-filter-field"><label for="trialPerPage"><i class="fas fa-list-ol"></i> Mostrar</label><select id="trialPerPage"><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="sa-filter-actions"><button type="button" id="clearTrialFilters" class="sa-btn sa-btn--secondary"><i class="fas fa-eraser"></i> Limpiar</button></div>
    </div>
    <div class="sa-records-counter-row"><span><?= number_format(count($records)) ?> registros de prueba</span><span id="trialPageSummary" class="sa-records-counter"></span></div>
    <div class="sa-records-table-wrap">
        <table id="trialTable" class="sa-records-table">
            <thead><tr><th>Usuario e identificador</th><th>IP registrada</th><th>Plan y estado</th><th>Vigencia</th><th>Control</th><th class="is-center">Acciones</th></tr></thead>
            <tbody>
            <?php foreach ($records as $record):
                $isBlocked = (int) $record['tracking_id'] > 0;
                $isCurrent = $record['kind'] === 'current';
                $displayName = $record['name'] !== '' ? $record['name'] : 'Sin nombre asociado';
                $displayEmail = $record['email'] !== '' ? $record['email'] : 'Identificador no disponible';
                $plan = $record['plan'] !== '' ? $record['plan'] : 'Historial de prueba';
                $state = $record['state'] !== '' ? ucfirst(mb_strtolower($record['state'], 'UTF-8')) : 'Histórico';
                $start = $record['start_date'] ? date('d/m/Y', strtotime((string) $record['start_date'])) : '—';
                $end = $record['end_date'] ? date('d/m/Y', strtotime((string) $record['end_date'])) : '—';
            ?>
                <tr data-af-row data-type="<?= $isCurrent ? 'current' : 'history' ?>" data-block="<?= $isBlocked ? 'blocked' : 'free' ?>" data-plan="<?= sa_e($record['plan']) ?>" data-search="<?= sa_e($displayName . ' ' . $displayEmail . ' ' . $record['ip_address'] . ' ' . $plan . ' ' . $state) ?>">
                    <td><span class="sa-table-primary"><i class="fas fa-user"></i> <?= sa_e($displayName) ?></span><span class="sa-table-secondary"><?= sa_e($displayEmail) ?></span></td>
                    <td><span class="sa-badge sa-badge--blue"><i class="fas fa-network-wired"></i><?= sa_e($record['ip_address']) ?></span></td>
                    <td><span class="sa-table-primary"><?= sa_e($plan) ?></span><span class="sa-table-secondary"><?= sa_e($state) ?><?= $record['cycle'] !== '' ? ' · ' . sa_e(ucfirst($record['cycle'])) : '' ?></span></td>
                    <td><span class="sa-table-primary"><?= sa_e($start) ?> → <?= sa_e($end) ?></span><span class="sa-table-secondary"><?= $isCurrent ? 'Vigencia de la suscripción' : 'Sin suscripción de prueba vigente' ?></span></td>
                    <td><?php if ($isBlocked): ?><span class="sa-badge sa-badge--warning"><i class="fas fa-lock"></i> Bloqueada</span><span class="sa-table-secondary">Desde <?= $record['registered_at'] ? date('d/m/Y H:i', strtotime((string) $record['registered_at'])) : 'fecha no disponible' ?></span><?php else: ?><span class="sa-badge sa-badge--success"><i class="fas fa-lock-open"></i> Sin bloqueo</span><span class="sa-table-secondary">La prueba se muestra desde Suscripciones</span><?php endif; ?></td>
                    <td class="is-center"><div class="sa-record-actions"><button type="button" class="sa-icon-action sa-icon-action--renew js-release-trial" title="Liberar bloqueo de prueba" data-tracking-id="<?= (int) $record['tracking_id'] ?>" data-user-id="<?= (int) $record['user_id'] ?>" data-email="<?= sa_e($record['email']) ?>" data-ip="<?= sa_e($record['ip_address']) ?>" data-name="<?= sa_e($displayName) ?>"><i class="fas fa-unlock"></i></button></div></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <div id="trialEmpty" class="sa-inline-empty" hidden><i class="fas fa-flask"></i><strong>No hay pruebas que coincidan</strong><span>Modifica los filtros o revisa las suscripciones con plan Gratis.</span></div>
    </div>
    <footer class="sa-records-footer"><span class="sa-records-footer__note">Liberar elimina el bloqueo histórico por identificador o IP; no elimina la cuenta ni modifica la vigencia de su suscripción.</span><div id="trialPagination" class="sa-pagination"></div></footer>
</section>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const list = new AfenixAdmin.UnifiedList({table:'#trialTable',search:'#trialSearch',perPage:'#trialPerPage',filters:[{selector:'#trialType',data:'type'},{selector:'#trialBlock',data:'block'},{selector:'#trialPlan',data:'plan'}],summary:'#trialPageSummary',pagination:'#trialPagination',empty:'#trialEmpty'});
    document.getElementById('clearTrialFilters')?.addEventListener('click',()=>{['trialSearch','trialType','trialBlock','trialPlan'].forEach(id=>document.getElementById(id).value='');document.getElementById('trialPerPage').value='100';list.currentPage=1;list.render();});

    document.getElementById('trialTable')?.addEventListener('click', async event => {
        const button = event.target.closest('.js-release-trial');
        if (!button) return;
        const result = await Swal.fire({title:'¿Liberar esta prueba?',html:`Se limpiará el bloqueo histórico asociado a <strong>${button.dataset.name}</strong>.<br><small>La cuenta y la suscripción seguirán existiendo.</small>`,icon:'warning',showCancelButton:true,confirmButtonText:'Sí, liberar',cancelButtonText:'Cancelar',confirmButtonColor:'#dc2626'});
        if (!result.isConfirmed) return;
        try {
            const body = new URLSearchParams({action:'liberar_prueba',tracking_id:button.dataset.trackingId||'0',user_id:button.dataset.userId||'0',email:button.dataset.email||'',ip_address:button.dataset.ip||'',_csrf:<?= json_encode(Security::csrfToken()) ?>});
            const response = await AfenixAdmin.request('gestionar_pruebas.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','X-Requested-With':'XMLHttpRequest'},body});
            await Swal.fire('Prueba liberada',response.message,'success');
            location.reload();
        } catch (error) {
            Swal.fire('No se pudo liberar',error.message,'error');
        }
    });
});
</script>
<?php require_once 'admin_footer.php'; ob_end_flush(); ?>

<!-- AFENIXX-V12-ASSETS -->
<link rel="stylesheet" href="../assets/css/afenixx_v12.css?v=2026.07.24-v12">
<script src="../assets/js/afenixx_v12.js?v=2026.07.24-v12"></script>
