<?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');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
auth_ensure_schema($db);
$alert = '';
$alertType = 'success';
function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
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';
    $apiUrlHidden = trim((string)($_POST['api_url'] ?? ''));
    $apiUrlSigma = trim((string)($_POST['api_url_sigma'] ?? ''));
    $apiUrl = $provider === 'fastplay' ? 'https://api.painelcliente.com' : ($apiUrlSigma !== '' ? $apiUrlSigma : $apiUrlHidden);
    $apiToken = trim((string)($_POST['api_token'] ?? ''));
    $apiSecret = trim((string)($_POST['api_secret'] ?? ''));
    $apiBouquet = $provider === 'fastplay' ? '1,2,3,4' : '';
    $fastplayAdultos = $provider === 'fastplay' ? 1 : 0;
    try {
        $st = $db->prepare('UPDATE config_test SET enabled=?, auto_mac_enabled=?, provider=?, api_url=?, api_token=?, api_secret=?, api_bouquet=?, fastplay_adultos=? WHERE id=1');
        $st->execute([$enabled, $autoMac, $provider, $apiUrl, $apiToken, $apiSecret, $apiBouquet, $fastplayAdultos]);
        $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';
$apiUrlAtual = trim((string)($cfg['api_url'] ?? ''));
if ($providerAtual === 'fastplay') $apiUrlAtual = 'https://api.painelcliente.com';
$apiBouquetAtual = trim((string)($cfg['api_bouquet'] ?? ''));
if ($providerAtual === 'fastplay') $apiBouquetAtual = '1,2,3,4';
include './includes/header.php';
?>

<style>
.dns-wrap{
    width:100%;
    max-width:none;
    margin:0;
    padding:0 18px;
}
.dns-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
    margin-bottom:18px;
}
.dns-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:18px 22px;
}
.dns-title{
    display:flex;
    align-items:center;
    gap:14px;
}
.dns-title .ic{
    width:44px;
    height:44px;
    min-width:44px;
    border-radius:14px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    display:flex;
    align-items:center;
    justify-content:center;
}
.dns-title .ic i{
    font-size:24px;
    color:#198754;
}
.dns-title h5{
    margin:0;
    font-weight:900;
}
.dns-title span{
    display:block;
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.badge-soft{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    color:#198754;
    font-weight:900;
    white-space:nowrap;
}
.input-radius{
    border-radius:14px !important;
    min-height:48px;
}
.textarea-radius{
    border-radius:14px !important;
}
.save-btn{
    border-radius:14px;
    height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.table-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
}
.table thead th{
    font-weight:900;
    white-space:nowrap;
}
.table td{
    vertical-align:middle;
}
.action-btn{
    border-radius:12px;
    font-weight:800;
    margin:2px 0;
}
.img-link{
    font-weight:900;
    text-decoration:none;
}
.status-on{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:999px;
    padding:5px 10px;
    background:rgba(25,135,84,.12);
    color:#198754;
    font-weight:900;
}
.status-off{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:999px;
    padding:5px 10px;
    background:rgba(220,53,69,.12);
    color:#dc3545;
    font-weight:900;
}
@media(max-width:575px){
    .dns-wrap{
        padding:0 8px;
    }
    .dns-header{
        align-items:flex-start;
        padding:16px;
    }
    .dns-title .ic{
        width:40px;
        height:40px;
        min-width:40px;
    }
    .dns-title .ic i{
        font-size:22px;
    }
    .dns-title h5{
        font-size:18px;
    }
    .badge-soft{
        padding:7px 10px;
        font-size:12px;
    }
    .save-btn{
        width:100%;
    }
}

/* SCROLLBAR CINZA - PC E MOBILE */
html{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

body{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

*::-webkit-scrollbar{
  width: 10px;
  height: 10px;
}

*::-webkit-scrollbar-track{
  background: #1f1f1f;
  border-radius: 999px;
}

*::-webkit-scrollbar-thumb{
  background: linear-gradient(180deg, #b8b8b8, #7c7c7c);
  border-radius: 999px;
  border: 2px solid #1f1f1f;
}

*::-webkit-scrollbar-thumb:hover{
  background: linear-gradient(180deg, #d0d0d0, #909090);
}

.table-responsive{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

@media (max-width: 768px){
  *::-webkit-scrollbar{
    width: 7px;
    height: 7px;
  }
}
</style>
<style>
body,.page-wrapper,.page-content{background:#ffffff!important}.test-wrap{display:grid;grid-template-columns:1fr 1fr;gap:18px}.test-card{background:linear-gradient(145deg,rgba(18,18,18,.96),rgba(28,28,34,.96));border:1px solid rgba(255,255,255,.08);border-radius:18px;box-shadow:0 20px 50px rgba(0,0,0,.22);overflow:hidden}.test-card .test-head{padding:22px 24px;border-bottom:1px solid rgba(255,255,255,.08);display:flex;align-items:center;gap:14px}.test-icon{width:46px;height:46px;border-radius:16px;background:rgba(220,53,69,.14);color:#ff5263;display:flex;align-items:center;justify-content:center;font-size:24px}.test-title{margin:0;color:#fff;font-weight:700}.test-sub{margin:4px 0 0;color:#aeb6c2;font-size:13px}.test-body{padding:24px}.provider-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:18px}.provider-pill{cursor:pointer;border:1px solid rgba(255,255,255,.1);border-radius:16px;padding:16px;background:rgba(255,255,255,.04);transition:.2s}.provider-pill.active{border-color:#ff5263;background:rgba(220,53,69,.14)}.provider-pill input{display:none}.provider-pill strong{display:block;color:#fff}.provider-pill span{display:block;color:#aeb6c2;font-size:12px;margin-top:4px}.soft-box{border:1px solid rgba(255,255,255,.08);border-radius:16px;background:rgba(255,255,255,.035);padding:16px;margin-bottom:16px}.form-label{color:#e7ebf0;font-weight:600}.form-control,.form-select{background:#101217!important;border:1px solid rgba(255,255,255,.12)!important;color:#fff!important;border-radius:12px!important}.form-control:focus,.form-select:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.18)!important;border-color:#ff5263!important}.hint{color:#9aa4b2;font-size:12px;margin-top:6px}.save-row{display:flex;gap:12px;align-items:center;justify-content:flex-end;margin-top:18px}.status-dot{width:10px;height:10px;border-radius:50%;background:#28d17c;display:inline-block;margin-right:8px}.pane{display:none}.pane.active{display:block}@media(max-width:991px){.test-wrap{grid-template-columns:1fr}.provider-grid{grid-template-columns:1fr}}
</style>
<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="api_url_sigma" id="apiUrlSigma" value="<?= $providerAtual === 'sigma' ? h($apiUrlAtual) : '' ?>" placeholder="https://seudominio.com/api/teste"></div>
                            <div class="hint">No Sigma, o painel envia nome, WhatsApp e MAC para essa URL.</div>
                        </div>
                        <div id="paneFastplay" class="pane <?= $providerAtual === 'fastplay' ? 'active' : '' ?>">
                            <input type="hidden" name="api_url_fastplay" id="apiUrlFastplay" value="https://api.painelcliente.com">
                            <input type="hidden" name="api_bouquet" id="apiBouquet" value="1,2,3,4">
                            <input type="hidden" name="fastplay_adultos" id="fastplayAdultos" value="1">
                            <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</label><input class="form-control" name="api_token" value="<?= h($cfg['api_token'] ?? '') ?>" placeholder="token"></div>
                            <div class="mb-3"><label class="form-label">Secret</label><input class="form-control" name="api_secret" value="<?= h($cfg['api_secret'] ?? '') ?>" placeholder="secret"></div>
                        </div>
                        <input type="hidden" name="api_url" id="api_url_hidden" value="<?= h($apiUrlAtual) ?>">
                        <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>
<script>
document.addEventListener('DOMContentLoaded',function(){
    const pills=[...document.querySelectorAll('.provider-pill')];
    const sigma=document.getElementById('paneSigma');
    const fastplay=document.getElementById('paneFastplay');
    const hidden=document.getElementById('api_url_hidden');
    const sigmaUrl=document.getElementById('apiUrlSigma');
    const fastplayUrl=document.getElementById('apiUrlFastplay');
    const enabled=document.getElementById('enabledSwitch');
    const enabledText=document.getElementById('enabledText');
    const adultos=document.getElementById('fastplayAdultos');
    const bouquet=document.getElementById('apiBouquet');
    function selected(){const r=document.querySelector('input[name="provider"]:checked');return r?r.value:'sigma'}
    function sync(){const p=selected();pills.forEach(x=>x.classList.toggle('active',x.dataset.provider===p));sigma.classList.toggle('active',p==='sigma');fastplay.classList.toggle('active',p==='fastplay');hidden.value=p==='fastplay'?fastplayUrl.value.trim():sigmaUrl.value.trim()}
    pills.forEach(p=>p.addEventListener('click',function(){const r=p.querySelector('input');if(r)r.checked=true;sync()}));
    if(sigmaUrl)sigmaUrl.addEventListener('input',sync);if(fastplayUrl)fastplayUrl.addEventListener('input',sync);
    enabled.addEventListener('change',function(){enabledText.textContent=enabled.checked?'Teste ativo no aplicativo':'Teste desativado no aplicativo'});
    if(adultos&&bouquet&&adultos.type!=='hidden')adultos.addEventListener('change',function(){if((bouquet.value.trim()===''||bouquet.value.trim()==='1,2,3'||bouquet.value.trim()==='1,2,3,4')) bouquet.value=adultos.checked?'1,2,3,4':'1,2,3'});
    document.getElementById('formConfigTeste').addEventListener('submit',sync);
    sync();
});
</script>
<?php include './includes/footer.php'; ?>
