<?php
session_start();
if (!isset($_SESSION['panel_user'])) { header('Location: index.php'); exit; }
if (($_SESSION['tipo_user'] ?? '') !== 'admin') { header('Location: dashboard.php'); exit; }
require_once dirname(__DIR__) . '/api/_auth_common.php';
$db = new PDO('sqlite:' . dirname(__DIR__) . '/api/db.db', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_TIMEOUT => 10,
]);
$db->exec('PRAGMA busy_timeout = 15000');
auth_ensure_schema($db);
$alert = '';
$alertType = 'success';
function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

$cfgBefore = $db->query('SELECT * FROM config_test WHERE id=1 LIMIT 1')->fetch(PDO::FETCH_ASSOC) ?: [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $enabled = isset($_POST['enabled']) ? 1 : 0;
    $autoMac = isset($_POST['auto_mac_enabled']) ? 1 : 0;
    $provider = strtolower(trim((string)($_POST['provider'] ?? 'sigma')));
    if (!in_array($provider, ['sigma', 'fastplay'], true)) $provider = 'sigma';

    $sigmaApiUrl = trim((string)($_POST['sigma_api_url'] ?? ($cfgBefore['sigma_api_url'] ?? $cfgBefore['api_url'] ?? '')));
    $sigmaToken = trim((string)($_POST['sigma_token'] ?? ($cfgBefore['sigma_token'] ?? '')));
    $fastplayToken = trim((string)($_POST['fastplay_token'] ?? ($cfgBefore['fastplay_token'] ?? '')));
    $fastplaySecret = trim((string)($_POST['fastplay_secret'] ?? ($cfgBefore['fastplay_secret'] ?? '')));
    $fastplayBouquets = '1,2,3,4';

    $legacyApiUrl = $provider === 'fastplay' ? 'https://api.painelcliente.com' : $sigmaApiUrl;
    $legacyApiToken = $provider === 'fastplay' ? $fastplayToken : $sigmaToken;
    $legacyApiSecret = $provider === 'fastplay' ? $fastplaySecret : '';
    $legacyBouquets = $provider === 'fastplay' ? $fastplayBouquets : '';

    if ($provider === 'sigma' && $sigmaApiUrl === '') {
        $alertType = 'danger';
        $alert = 'Informe a URL da API Sigma.';
    } elseif ($provider === 'fastplay' && ($fastplayToken === '' || $fastplaySecret === '')) {
        $alertType = 'danger';
        $alert = 'Informe o token e o secret do FastPlay.';
    } else {
        try {
            $st = $db->prepare('UPDATE config_test SET enabled=?, auto_mac_enabled=?, provider=?, api_url=?, api_token=?, api_secret=?, api_bouquet=?, fastplay_adultos=0, sigma_api_url=?, sigma_token=?, fastplay_token=?, fastplay_secret=?, fastplay_bouquets=? WHERE id=1');
            $st->execute([$enabled, $autoMac, $provider, $legacyApiUrl, $legacyApiToken, $legacyApiSecret, $legacyBouquets, $sigmaApiUrl, $sigmaToken, $fastplayToken, $fastplaySecret, $fastplayBouquets]);
            $db->prepare('UPDATE app_config SET test_button_enabled=?, updated_at=datetime("now") WHERE id=1')->execute([$enabled]);
            $alert = 'Configuração de teste salva com sucesso.';
        } catch (Throwable $e) {
            $alertType = 'danger';
            $alert = 'Erro ao salvar configuração do teste.';
        }
    }
}
$cfg = $db->query('SELECT * FROM config_test WHERE id=1 LIMIT 1')->fetch(PDO::FETCH_ASSOC) ?: [];
$providerAtual = strtolower(trim((string)($cfg['provider'] ?? 'sigma')));
if (!in_array($providerAtual, ['sigma', 'fastplay'], true)) $providerAtual = 'sigma';
$sigmaApiUrlAtual = trim((string)($cfg['sigma_api_url'] ?? ''));
if ($sigmaApiUrlAtual === '' && $providerAtual === 'sigma') $sigmaApiUrlAtual = trim((string)($cfg['api_url'] ?? ''));
$sigmaTokenAtual = trim((string)($cfg['sigma_token'] ?? ''));
if ($sigmaTokenAtual === '' && $providerAtual === 'sigma') $sigmaTokenAtual = trim((string)($cfg['api_token'] ?? ''));
$fastplayTokenAtual = trim((string)($cfg['fastplay_token'] ?? ''));
if ($fastplayTokenAtual === '' && $providerAtual === 'fastplay') $fastplayTokenAtual = trim((string)($cfg['api_token'] ?? ''));
$fastplaySecretAtual = trim((string)($cfg['fastplay_secret'] ?? ''));
if ($fastplaySecretAtual === '' && $providerAtual === 'fastplay') $fastplaySecretAtual = trim((string)($cfg['api_secret'] ?? ''));
require_once __DIR__ . '/../includes/header.php';
?>
<div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
            <div>
                <h4 class="mb-1 text-white">Teste Grátis</h4>
                <p class="mb-0 text-secondary">Configure a geração de teste para Sigma ou FastPlay e libere o acesso do app automaticamente.</p>
            </div>
        </div>
        <?php if ($alert): ?><div class="alert alert-<?= h($alertType) ?>"><?= h($alert) ?></div><?php endif; ?>
        <form method="post" id="formConfigTeste">
            <div class="test-wrap">
                <div class="test-card">
                    <div class="test-head">
                        <div class="test-icon"><i class='bx bx-bolt-circle'></i></div>
                        <div><h5 class="test-title">Status do teste</h5><p class="test-sub">Controle o botão no app e o teste automático por MAC.</p></div>
                    </div>
                    <div class="test-body">
                        <div class="soft-box">
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" name="enabled" id="enabledSwitch" <?= ((int)($cfg['enabled'] ?? 1) === 1) ? 'checked' : '' ?>>
                                <label class="form-check-label text-white" for="enabledSwitch"><span class="status-dot"></span><span id="enabledText"><?= ((int)($cfg['enabled'] ?? 1) === 1) ? 'Teste ativo no aplicativo' : 'Teste desativado no aplicativo' ?></span></label>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="auto_mac_enabled" id="autoMac" <?= ((int)($cfg['auto_mac_enabled'] ?? 0) === 1) ? 'checked' : '' ?>>
                                <label class="form-check-label text-white" for="autoMac">Gerar teste automático quando o login MAC estiver ativo</label>
                            </div>
                        </div>
                        <div class="provider-grid">
                            <label class="provider-pill <?= $providerAtual === 'sigma' ? 'active' : '' ?>" data-provider="sigma"><input type="radio" name="provider" value="sigma" <?= $providerAtual === 'sigma' ? 'checked' : '' ?>><strong>Sigma</strong><span>Usa a rota antiga do gerador de teste.</span></label>
                            <label class="provider-pill <?= $providerAtual === 'fastplay' ? 'active' : '' ?>" data-provider="fastplay"><input type="radio" name="provider" value="fastplay" <?= $providerAtual === 'fastplay' ? 'checked' : '' ?>><strong>FastPlay</strong><span>POST /trial_create/{token} com secret e bouquets.</span></label>
                        </div>
                        <div class="soft-box mb-0">
                            <div class="d-flex align-items-center gap-2 text-white mb-2"><i class='bx bx-info-circle'></i><strong>Fluxo do aplicativo</strong></div>
                            <div class="text-secondary small">Depois que o teste for criado, o app recebe usuário e senha e valida pelo mesmo caminho do login manual antes de abrir a Home.</div>
                        </div>
                    </div>
                </div>
                <div class="test-card">
                    <div class="test-head">
                        <div class="test-icon"><i class='bx bx-server'></i></div>
                        <div><h5 class="test-title">Dados da API</h5><p class="test-sub">Preencha os dados oficiais do provedor selecionado.</p></div>
                    </div>
                    <div class="test-body">
                        <div id="paneSigma" class="pane <?= $providerAtual === 'sigma' ? 'active' : '' ?>">
                            <div class="mb-3"><label class="form-label">URL da API Sigma</label><input class="form-control" name="sigma_api_url" id="apiUrlSigma" value="<?= h($sigmaApiUrlAtual) ?>" placeholder="https://seudominio.com/api/teste"></div>
                            <div class="mb-3"><label class="form-label">Token Sigma</label><input class="form-control" type="password" name="sigma_token" value="<?= h($sigmaTokenAtual) ?>" placeholder="Token Bearer (opcional, conforme sua API)" autocomplete="new-password"></div>
                            <div class="hint">O painel envia nome, WhatsApp e MAC em JSON. Quando preenchido, o token é enviado no cabeçalho Authorization: Bearer.</div>
                        </div>
                        <div id="paneFastplay" class="pane <?= $providerAtual === 'fastplay' ? 'active' : '' ?>">
                            <input type="hidden" id="apiUrlFastplay" value="https://api.painelcliente.com">
                            <div class="soft-box">
                                <div class="d-flex align-items-center gap-2 text-white mb-2"><i class='bx bx-lock-alt'></i><strong>FastPlay oficial configurado</strong></div>
                                <div class="text-secondary small">URL base fixa: <strong>https://api.painelcliente.com</strong></div>
                                <div class="text-secondary small mt-1">Bouquets enviados automaticamente: <strong>1,2,3,4</strong></div>
                            </div>
                            <div class="mb-3"><label class="form-label">Token FastPlay</label><input class="form-control" type="password" name="fastplay_token" value="<?= h($fastplayTokenAtual) ?>" placeholder="token" autocomplete="new-password"></div>
                            <div class="mb-3"><label class="form-label">Secret FastPlay</label><input class="form-control" type="password" name="fastplay_secret" value="<?= h($fastplaySecretAtual) ?>" placeholder="secret" autocomplete="new-password"></div>
                        </div>
                        <div class="save-row"><button type="submit" class="btn btn-primary px-4"><i class='bx bx-save me-1'></i>Salvar</button></div>
                    </div>
                </div>
            </div>
        </form>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
