<?php
require_once __DIR__ . '/includes/header.php';

$message = '';
$message_type = '';
$pdo = db();

function trial_page_date($value): string {
    if (empty($value)) return '-';
    $ts = strtotime((string)$value);
    if (!$ts) return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    return date('d/m/Y H:i', $ts);
}

function trial_input_date($value): string {
    if (empty($value)) return '';
    $ts = strtotime((string)$value);
    if (!$ts) return '';
    return date('Y-m-d\TH:i', $ts);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'toggle_settings') {
        $settings = get_trial_settings();
        $enabled = ((int)($settings['is_enabled'] ?? 0) === 1) ? 0 : 1;
        $result = save_trial_settings($enabled, (string)($settings['m3u_url'] ?? ''), (int)($settings['duration_hours'] ?? 4));
        $message = $result['message'] ?? 'Configuracao salva.';
        $message_type = !empty($result['ok']) ? 'success' : 'error';
    }

    if ($action === 'save_settings') {
        $enabled = isset($_POST['is_enabled']) ? 1 : 0;
        $m3u_url = str_in($_POST['m3u_url'] ?? '');
        $duration = normalize_trial_duration($_POST['duration_hours'] ?? 4);

        $result = save_trial_settings($enabled, $m3u_url, $duration);
        $message = $result['message'] ?? 'Configuracao salva.';
        $message_type = !empty($result['ok']) ? 'success' : 'error';
    }

    if ($action === 'delete_trial') {
        $id = (int)($_POST['trial_id'] ?? 0);
        if ($id > 0) {
            $stmt = $pdo->prepare("DELETE FROM app_trial_devices WHERE id = ?");
            if ($stmt->execute([$id])) {
                $message = 'Teste deletado para este dispositivo.';
                $message_type = 'success';
            } else {
                $message = 'Erro ao deletar teste.';
                $message_type = 'error';
            }
        }
    }

    if ($action === 'update_trial_expiry') {
        $id = (int)($_POST['trial_id'] ?? 0);
        $expiresInput = trim((string)($_POST['expires_at'] ?? ''));

        if ($id <= 0 || $expiresInput === '') {
            $message = 'Informe uma data de vencimento valida.';
            $message_type = 'error';
        } else {
            $expires = DateTimeImmutable::createFromFormat('Y-m-d\TH:i', $expiresInput, new DateTimeZone('America/Sao_Paulo'));
            if (!$expires) {
                $message = 'Data de vencimento invalida.';
                $message_type = 'error';
            } else {
                $status = ($expires > trial_now()) ? 'active' : 'expired';
                $stmt = $pdo->prepare("UPDATE app_trial_devices SET expires_at = ?, status = ?, last_seen_at = ? WHERE id = ?");
                if ($stmt->execute([trial_datetime_to_db($expires), $status, trial_datetime_to_db(trial_now()), $id])) {
                    $message = 'Vencimento do teste atualizado.';
                    $message_type = 'success';
                } else {
                    $message = 'Erro ao atualizar vencimento.';
                    $message_type = 'error';
                }
            }
        }
    }

    if ($action === 'migrate_trial') {
        $id = (int)($_POST['trial_id'] ?? 0);
        $name = str_in($_POST['name'] ?? '');
        $m3u_url = str_in($_POST['m3u_url'] ?? '');
        $expires_at = str_in($_POST['expires_at'] ?? '');

        $result = migrate_trial_to_client($id, $name, $m3u_url, $expires_at);
        $message = $result['message'] ?? 'Cliente migrado.';
        $message_type = !empty($result['ok']) ? 'success' : 'error';
    }
}

$settings = get_trial_settings();
$trial_devices = get_trial_devices(120);
$duration_options = trial_duration_options();
?>

<style>
    .trial-page { width: 100%; }
    .trial-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 18px;
        margin-bottom: 24px;
        padding: 26px 30px;
        border: 1px solid var(--border-color, rgba(255, 205, 205, .16));
        border-radius: 22px;
        background: rgba(39, 2, 2, .78);
    }
    .trial-header h1 { margin: 0; font-size: 32px; color: #fff; }
    .trial-header p { margin: 8px 0 0; color: var(--text-secondary, #f6c7c7); }
    .trial-header-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; justify-content: flex-end; }
    .trial-badge {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 999px;
        padding: 10px 16px;
        font-weight: 900;
        white-space: nowrap;
    }
    .trial-badge.on { background: rgba(28, 214, 120, .15); color: #28f08b; }
    .trial-badge.off { background: rgba(255, 77, 109, .15); color: #ff7b95; }
    .trial-card {
        border: 1px solid var(--border-color, rgba(255, 205, 205, 0.16));
        border-radius: 22px;
        background: rgba(49, 3, 3, .78);
        padding: 28px 32px;
        box-shadow: var(--shadow, 0 22px 65px rgba(0, 0, 0, .38));
        margin-bottom: 24px;
    }
    .trial-form { display: grid; gap: 20px; }
    .trial-field { display: grid; gap: 9px; }
    .trial-field label { color: #fff; font-weight: 800; }
    .trial-field input,
    .trial-field textarea,
    .trial-field select {
        width: 100%;
        border: 1px solid rgba(255, 205, 205, 0.22);
        border-radius: 15px;
        background: rgba(28, 0, 0, 0.68);
        color: #fff;
        padding: 15px 17px;
        font-size: 15px;
        font-family: inherit;
        outline: none;
    }
    .trial-field textarea { min-height: 110px; resize: vertical; }
    .trial-field select option { background: #2c0000; color: #fff; }
    .trial-field input:focus,
    .trial-field textarea:focus,
    .trial-field select:focus {
        border-color: var(--primary-solid, #ff2c2c);
        box-shadow: 0 0 0 3px rgba(255, 44, 44, 0.18);
    }
    .trial-toggle {
        display: inline-flex;
        align-items: center;
        gap: 12px;
        color: #fff;
        font-weight: 800;
    }
    .trial-toggle input { width: 24px; height: 24px; accent-color: #ff2c2c; }
    .btn-trial,
    .btn-edit,
    .btn-migrate,
    .btn-delete,
    .btn-cancel {
        border: 0;
        border-radius: 12px;
        color: #fff;
        font-weight: 900;
        padding: 11px 15px;
        cursor: pointer;
        font-family: inherit;
        text-decoration: none;
    }
    .btn-trial,
    .btn-edit,
    .btn-migrate { background: linear-gradient(135deg, #ff5c5c 0%, #ff2c2c 100%); }
    .btn-delete { background: rgba(255, 77, 109, .18); }
    .btn-cancel {
        border: 1px solid rgba(255, 205, 205, 0.18);
        background: rgba(255, 255, 255, .06);
    }
    .trial-alert {
        border-radius: 16px;
        padding: 14px 16px;
        margin-bottom: 18px;
        font-weight: 800;
    }
    .trial-alert.success { background: rgba(28, 214, 120, .14); border: 1px solid rgba(28, 214, 120, .28); color: #5dffa4; }
    .trial-alert.error { background: rgba(255, 77, 109, .14); border: 1px solid rgba(255, 77, 109, .28); color: #ff8ca1; }
    .trial-table-wrap { overflow-x: auto; border-radius: 18px; border: 1px solid rgba(255, 205, 205, 0.14); }
    .trial-table { width: 100%; min-width: 900px; border-collapse: collapse; color: #fff; }
    .trial-table th {
        background: rgba(150, 22, 22, 0.88);
        padding: 16px 18px;
        text-align: left;
        white-space: nowrap;
    }
    .trial-table td {
        padding: 16px 18px;
        border-bottom: 1px solid rgba(255, 205, 205, 0.12);
        vertical-align: middle;
    }
    .trial-table tr:last-child td { border-bottom: 0; }
    .device-text {
        display: inline-block;
        max-width: 250px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #ff7878;
        font-family: Consolas, "Courier New", monospace;
        font-weight: 800;
    }
    .expiry-input { min-width: 190px; }
    .row-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
    .trial-modal {
        position: fixed;
        inset: 0;
        z-index: 9999;
        display: none;
        align-items: center;
        justify-content: center;
        padding: 24px;
        background: rgba(5, 0, 15, .72);
    }
    .trial-modal.is-open { display: flex; }
    .trial-modal-box {
        width: min(560px, 100%);
        max-height: min(90vh, 820px);
        overflow-y: auto;
        border: 1px solid rgba(255, 205, 205, 0.18);
        border-radius: 20px;
        background: #310303;
        box-shadow: 0 24px 80px rgba(0, 0, 0, .5);
        padding: 24px;
        color: #fff;
    }
    .trial-modal-box h2 { margin: 0 0 8px; font-size: 24px; }
    .trial-modal-box p { margin: 0 0 18px; color: var(--text-secondary, #f6c7c7); }
    .trial-modal-actions {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-top: 6px;
        flex-wrap: wrap;
    }
    .pill {
        display: inline-flex;
        border-radius: 999px;
        padding: 8px 12px;
        font-size: 13px;
        font-weight: 900;
        white-space: nowrap;
    }
    .pill-active { background: rgba(28, 214, 120, .15); color: #28f08b; }
    .pill-expired { background: rgba(255, 77, 109, .15); color: #ff7b95; }
    .empty-state { padding: 44px 20px; text-align: center; color: var(--text-secondary, #f6c7c7); }
    .empty-state h3 { margin-bottom: 8px; color: #fff; }
    .plan-selector {
        display: grid;
        grid-template-columns: repeat(3, minmax(0, 1fr));
        gap: 10px;
    }
    .plan-option { cursor: pointer; }
    .plan-option input { position: absolute; opacity: 0; pointer-events: none; }
    .plan-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        min-height: 78px;
        gap: 5px;
        padding: 12px 8px;
        border-radius: 12px;
        border: 2px solid rgba(255, 255, 255, .14);
        background: rgba(28, 0, 0, 0.68);
        color: #f6c7c7;
        text-align: center;
    }
    .plan-box strong { color: #fff; }
    .plan-box small { color: #e89c9c; font-size: 12px; }
    .plan-option input:checked + .plan-box {
        border-color: #f75555;
        background: rgba(247, 85, 85, 0.16);
        box-shadow: 0 0 0 3px rgba(247, 85, 85, 0.16);
    }
    @media (max-width: 720px) {
        .trial-header { align-items: flex-start; flex-direction: column; padding: 22px; }
        .trial-header-actions { justify-content: flex-start; }
        .trial-card { padding: 22px; }
        .plan-selector { grid-template-columns: 1fr; }
    }
</style>

<div class="trial-page">
    <div class="trial-header">
        <div>
            <h2>Teste Automatico</h2>
        
        </div>
        <div class="trial-header-actions">
            <?php if ((int)($settings['is_enabled'] ?? 0) === 1): ?>
                <span class="trial-badge on">Habilitado</span>
                <form method="post">
                    <input type="hidden" name="action" value="toggle_settings">
                    <button type="submit" class="btn-delete">Desativar</button>
                </form>
            <?php else: ?>
                <span class="trial-badge off">Desabilitado</span>
                <form method="post">
                    <input type="hidden" name="action" value="toggle_settings">
                    <button type="submit" class="btn-trial">Ativar</button>
                </form>
            <?php endif; ?>
            <button type="button" class="btn-edit js-open-modal" data-modal="trialConfigModal">Configurar Teste</button>
        </div>
    </div>

    <?php if ($message !== ''): ?>
        <div class="trial-alert <?php echo htmlspecialchars($message_type, ENT_QUOTES, 'UTF-8'); ?>">
            <?php echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8'); ?>
        </div>
    <?php endif; ?>

    <div class="trial-card">
        <div class="trial-header" style="padding:0;border:0;background:transparent;box-shadow:none;margin-bottom:18px;">
            <div>
           

            </div>
        </div>

        <?php if (count($trial_devices) > 0): ?>
            <div class="trial-table-wrap">
                <table class="trial-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Android ID</th>
                            <th>Vencimento</th>
                            <th>Status</th>
                            <th>Acao</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($trial_devices as $trial): ?>
                            <?php $active = trial_is_active($trial); ?>
                            <tr>
                                <td><?php echo (int)$trial['id']; ?></td>
                                <td>
                                    <span class="device-text" title="<?php echo htmlspecialchars($trial['device_id'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                                        <?php echo htmlspecialchars($trial['device_id'] ?? '', ENT_QUOTES, 'UTF-8'); ?>
                                    </span>
                                </td>
                                <td><?php echo trial_page_date($trial['expires_at'] ?? ''); ?></td>
                                <td>
                                    <?php if ($active): ?>
                                        <span class="pill pill-active">Ativo</span>
                                    <?php else: ?>
                                        <span class="pill pill-expired">Vencido</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="row-actions">
                                        <button
                                            type="button"
                                            class="btn-edit js-edit-trial"
                                            data-id="<?php echo (int)$trial['id']; ?>"
                                            data-expires="<?php echo htmlspecialchars(trial_input_date($trial['expires_at'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"
                                        >Editar</button>
                                        <button
                                            type="button"
                                            class="btn-migrate js-migrate-trial"
                                            data-id="<?php echo (int)$trial['id']; ?>"
                                            data-m3u="<?php echo htmlspecialchars($trial['m3u_url'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                        >Migrar Cliente</button>
                                        <form method="post" onsubmit="return confirm('Deletar teste deste dispositivo?');">
                                            <input type="hidden" name="action" value="delete_trial">
                                            <input type="hidden" name="trial_id" value="<?php echo (int)$trial['id']; ?>">
                                            <button type="submit" class="btn-delete">Deletar</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <h3>Nenhum teste.</h3>

            </div>
        <?php endif; ?>
    </div>
</div>

<div class="trial-modal" id="trialConfigModal" aria-hidden="true">
    <div class="trial-modal-box">
        <h2>Configurar Teste</h2>
        <p>Defina a lista M3U e o tempo entregue ao primeiro acesso do aparelho.</p>
        <form method="post" class="trial-form">
            <input type="hidden" name="action" value="save_settings">
            <label class="trial-toggle">
                <input type="checkbox" name="is_enabled" value="1" <?php echo ((int)($settings['is_enabled'] ?? 0) === 1) ? 'checked' : ''; ?>>
                <span>Habilitar teste automatico</span>
            </label>
            <div class="trial-field">
                <label for="m3u_url">URL da lista M3U de teste</label>
                <textarea id="m3u_url" name="m3u_url" placeholder="http://servidor.com/get.php?username=usuario&password=senha&type=m3u_plus&output=mpegts"><?php echo htmlspecialchars($settings['m3u_url'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
            </div>
            <div class="trial-field">
                <label for="duration_hours">Tempo de teste</label>
                <select id="duration_hours" name="duration_hours">
                    <?php foreach ($duration_options as $hours => $label): ?>
                        <option value="<?php echo (int)$hours; ?>" <?php echo ((int)($settings['duration_hours'] ?? 4) === (int)$hours) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="trial-modal-actions">
                <button type="button" class="btn-cancel js-close-modal">Cancelar</button>
                <button type="submit" class="btn-edit">Salvar</button>
            </div>
        </form>
    </div>
</div>

<div class="trial-modal" id="trialEditModal" aria-hidden="true">
    <div class="trial-modal-box">
        <h2>Editar vencimento</h2>
        <p>Altere a data para simular teste ativo ou vencido.</p>
        <form method="post" class="trial-form">
            <input type="hidden" name="action" value="update_trial_expiry">
            <input type="hidden" name="trial_id" id="trialModalId" value="">
            <div class="trial-field">
                <label for="trialModalExpires">Vencimento</label>
                <input type="datetime-local" name="expires_at" id="trialModalExpires" class="expiry-input" required>
            </div>
            <div class="trial-modal-actions">
                <button type="button" class="btn-cancel js-close-modal">Cancelar</button>
                <button type="submit" class="btn-edit">Salvar</button>
            </div>
        </form>
    </div>
</div>

<div class="trial-modal" id="trialMigrateModal" aria-hidden="true">
    <div class="trial-modal-box">
        <h2>Migrar Cliente</h2>
        <p>Crie o cliente final e vincule automaticamente este Android ID.</p>
        <form method="post" class="trial-form">
            <input type="hidden" name="action" value="migrate_trial">
            <input type="hidden" name="trial_id" id="migrateTrialId" value="">
            <div class="trial-field">
                <label for="migrateName">Nome do cliente</label>
                <input type="text" id="migrateName" name="name" placeholder="Ex: Joao Silva">
            </div>
            <div class="trial-field">
                <label for="migrateM3u">URL da lista M3U final</label>
                <textarea id="migrateM3u" name="m3u_url" required></textarea>
            </div>
            <div class="trial-field">
                <label for="migrateExpires">Data de vencimento</label>
                <input type="date" id="migrateExpires" name="expires_at" required>
            </div>
            <div class="trial-modal-actions">
                <button type="button" class="btn-cancel js-close-modal">Cancelar</button>
                <button type="submit" class="btn-migrate">Salvar Cliente</button>
            </div>
        </form>
    </div>
</div>

<script>
    (function () {
        function openModal(id) {
            const modal = document.getElementById(id);
            if (!modal) return;
            modal.classList.add('is-open');
            modal.setAttribute('aria-hidden', 'false');
            const firstInput = modal.querySelector('input:not([type="hidden"]), textarea, select');
            if (firstInput) firstInput.focus();
        }

        function closeModal(modal) {
            if (!modal) return;
            modal.classList.remove('is-open');
            modal.setAttribute('aria-hidden', 'true');
        }

        document.querySelectorAll('.js-open-modal').forEach(function (button) {
            button.addEventListener('click', function () {
                openModal(button.getAttribute('data-modal') || '');
            });
        });

        document.querySelectorAll('.js-edit-trial').forEach(function (button) {
            button.addEventListener('click', function () {
                document.getElementById('trialModalId').value = button.getAttribute('data-id') || '';
                document.getElementById('trialModalExpires').value = button.getAttribute('data-expires') || '';
                openModal('trialEditModal');
            });
        });

        document.querySelectorAll('.js-migrate-trial').forEach(function (button) {
            button.addEventListener('click', function () {
                document.getElementById('migrateTrialId').value = button.getAttribute('data-id') || '';
                document.getElementById('migrateM3u').value = button.getAttribute('data-m3u') || '';
                document.getElementById('migrateName').value = '';
                openModal('trialMigrateModal');
            });
        });

        document.querySelectorAll('.js-close-modal').forEach(function (button) {
            button.addEventListener('click', function () {
                closeModal(button.closest('.trial-modal'));
            });
        });

        document.querySelectorAll('.trial-modal').forEach(function (modal) {
            modal.addEventListener('click', function (event) {
                if (event.target === modal) closeModal(modal);
            });
        });

        document.addEventListener('keydown', function (event) {
            if (event.key !== 'Escape') return;
            document.querySelectorAll('.trial-modal.is-open').forEach(closeModal);
        });
    })();
</script>

</main>
</body>
</html>
