<?php
include __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../api/_security_store.php';

$appUrl = '';
$https = false;
$notice = '';
$error = '';

if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
    $https = true;
}

if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string)$_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') {
    $https = true;
}

$scheme = $https ? 'https' : 'http';
$host = isset($_SERVER['HTTP_HOST']) ? (string)$_SERVER['HTTP_HOST'] : '';

if (isset($BASE_URL) && trim((string)$BASE_URL) !== '') {
    $basePath = trim((string)$BASE_URL);
    if (preg_match('/^https?:\/\//i', $basePath)) {
        $appUrl = rtrim($basePath, '/');
    } else {
        $appUrl = rtrim($scheme . '://' . $host . '/' . ltrim($basePath, '/'), '/');
    }
} else {
    $appUrl = rtrim($scheme . '://' . $host, '/');
}

function app_page_seed(string $value): string
{
    $out = '';
    $len = strlen($value);
    for ($i = 0; $i < $len; $i++) {
        $out .= chr(ord($value[$i]) ^ 90);
    }
    return base64_encode($out);
}

$currentToken = security_store_token();
$currentSeed = app_page_seed($appUrl);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? 'save'));
    $token = $action === 'generate' ? security_store_generate_token() : (string)($_POST['app_token'] ?? '');

    if (security_store_save_token($token)) {
        $currentToken = security_store_token();
        $notice = 'Token atualizado com sucesso. Copie o JSON abaixo para o app em src/main/assets/app.json e gere uma nova APK.';
    } else {
        $error = 'Token inválido. Use no mínimo 24 caracteres, sem espaços.';
    }
}

$appJsonPayload = [
    'seed_v2' => $currentSeed,
    'app_token' => $currentToken,
    'token_name' => 'X-App-Token'
];
$appJsonText = json_encode($appJsonPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
.dns-wrap{width:100%;max-width:none;margin:0;padding:0 18px}.dns-card{border-radius:18px;overflow:hidden;width:100%;background:#121212;border:1px solid rgba(255,255,255,.12);box-shadow:0 18px 50px rgba(0,0,0,.35)}.dns-header{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:18px 22px;border-bottom:1px solid rgba(255,255,255,.10)}.dns-title{display:flex;align-items:center;gap:14px}.dns-title .ic{width:44px;height:44px;min-width:44px;border-radius:14px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.20);display:flex;align-items:center;justify-content:center}.dns-title .ic i{font-size:24px;color:#fff}.dns-title h5{margin:0;font-weight:900;color:#fff}.dns-title small{color:rgba(255,255,255,.65);font-weight:700}.badge-soft{display:inline-flex;align-items:center;gap:7px;padding:8px 12px;border-radius:999px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.18);color:#fff;font-weight:900;white-space:nowrap}.hex-box,.json-box{background:rgba(0,0,0,.42);border:1px solid rgba(255,255,255,.15);border-radius:14px;padding:14px 16px;font-weight:900;word-break:break-all;min-height:50px;color:#ffc107}.json-box{white-space:pre-wrap;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;color:#fff;font-size:13px}.copy-btn,.save-btn{border-radius:14px;height:44px;font-weight:900}.form-control.secure-input{height:48px;border-radius:14px;background:rgba(0,0,0,.40);border:1px solid rgba(255,255,255,.18);color:#fff;font-weight:800}.form-control.secure-input:focus{background:rgba(0,0,0,.55);border-color:#fff;color:#fff;box-shadow:0 0 0 .2rem rgba(255,255,255,.10)}.secure-label{font-weight:900;color:#fff;margin-bottom:8px}.help-text{color:rgba(255,255,255,.62);font-weight:700}.alert{border-radius:14px;font-weight:800}@media(max-width:575px){.dns-wrap{padding:0 8px}.dns-header{align-items:flex-start;padding:16px;flex-direction:column}.dns-title .ic{width:40px;height:40px;min-width:40px}.dns-title .ic i{font-size:22px}.copy-btn,.save-btn{width:100%;margin-top:8px}}
</style>

<div class="dns-wrap">
    <div class="card radius-10 dns-card">
        <div class="card-header bg-transparent dns-header">
            <div class="dns-title">
                <div class="ic"><i class="bi bi-shield-lock"></i></div>
                <div>
                    <h5>API do Aplicativo</h5>
                    <small>Token do app e seed do painel</small>
                </div>
            </div>
            <div class="dns-actions">
                <span class="badge-soft"><i class="bi bi-lock-fill"></i> Produção</span>
            </div>
        </div>

        <div class="card-body">
            <?php if ($notice !== ''): ?>
                <div class="alert alert-success"><?= htmlspecialchars($notice, ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>
            <?php if ($error !== ''): ?>
                <div class="alert alert-danger"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>

            <div class="row g-3 mb-4">
                <div class="col-12 col-xl-8">
                    <form method="post">
                        <label class="secure-label">Token da API do app</label>
                        <input type="text" name="app_token" class="form-control secure-input" value="<?= htmlspecialchars($currentToken, ENT_QUOTES, 'UTF-8') ?>" autocomplete="off" spellcheck="false">
                        <div class="help-text mt-2">Esse token precisa ser igual no painel e no arquivo <b>src/main/assets/app.json</b> do aplicativo.</div>
                        <div class="d-flex flex-wrap gap-2 mt-3">
                            <button type="submit" name="action" value="save" class="btn btn-light save-btn"><i class="bi bi-save"></i> Salvar token</button>
                            <button type="submit" name="action" value="generate" class="btn btn-outline-light save-btn"><i class="bi bi-arrow-repeat"></i> Gerar novo token</button>
                        </div>
                    </form>
                </div>
                <div class="col-12 col-xl-4">
                    <label class="secure-label">Token atual</label>
                    <div id="currentToken" class="hex-box"></div>
                    <button type="button" onclick="copyText('currentToken')" class="btn btn-primary copy-btn mt-3"><i class="bi bi-clipboard-check"></i> Copiar token</button>
                </div>
            </div>

            <label class="secure-label">Seed da URL do painel</label>
            <div id="seedcode" class="hex-box mb-3 text-warning"></div>
            <button type="button" onclick="copyText('seedcode')" class="btn btn-primary copy-btn mb-4"><i class="bi bi-clipboard-check"></i> Copiar seed</button>

            <label class="secure-label">Conteúdo para assets/app.json</label>
            <div id="appJsonBox" class="json-box mb-3"></div>
            <button type="button" onclick="copyText('appJsonBox')" class="btn btn-light copy-btn"><i class="bi bi-filetype-json"></i> Copiar app.json</button>
        </div>
    </div>
</div>

<script>
window.APP_URL_VALUE = <?= json_encode((string)$appUrl, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
window.APP_TOKEN_VALUE = <?= json_encode((string)$currentToken, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
window.APP_JSON_VALUE = <?= json_encode((string)$appJsonText, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
</script>
<script src="./assets/js/app-seed.js"></script>
<script>
(function(){
    function encodeSeed(value){
        var key=90,out='';
        for(var i=0;i<value.length;i++){out+=String.fromCharCode(value.charCodeAt(i)^key)}
        return btoa(out);
    }
    function setText(id,value){var el=document.getElementById(id);if(el){el.innerText=value||''}}
    setText('seedcode',window.APP_URL_VALUE?encodeSeed(String(window.APP_URL_VALUE).trim()):'');
    setText('currentToken',window.APP_TOKEN_VALUE||'');
    setText('appJsonBox',window.APP_JSON_VALUE||'');
})();
function copyText(id){
    var el=document.getElementById(id);
    var txt=el?String(el.innerText||'').trim():'';
    if(!txt){Swal.fire('Vazio','Nada para copiar.','warning');return;}
    navigator.clipboard.writeText(txt).then(function(){Swal.fire('Copiado','','success');});
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
