<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include(__DIR__ . '/includes/functions.php');
include 'session_check.php';

$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
$page_title = 'AES do App';

simpleEnsureKeyappTable($db);

$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $panelUrl = isset($_POST['panel_url']) ? trim($_POST['panel_url']) : '';
    $aesKey = isset($_POST['aes_key']) ? trim($_POST['aes_key']) : '';

    if ($panelUrl === '' || $aesKey === '') {
        $error_message = 'Preencha a URL do painel e a AES.';
    } else {
        simpleSaveKeyappConfig($db, $panelUrl, $aesKey);
        $success_message = 'Configuração salva com sucesso.';
    }
}

$config = simpleGetKeyappConfig($db);
$currentUrl = isset($config['panel_url']) ? $config['panel_url'] : '';
$currentAes = isset($config['aes_key']) ? $config['aes_key'] : '';

$page_content = '
<div class="container mt-5">
    <div class="card mb-5 mb-xl-12">
        <div class="card-body py-12">
            <h2 class="mb-4">Configuração simples do app</h2>
            <p class="text-muted mb-8">
                1. Cole a URL do painel no campo abaixo.<br>
                2. Clique em <strong>Gerar AES</strong>.<br>
                3. Salve.<br>
                4. No app, procure <strong>SUA_PANEL_URL</strong> e <strong>SUA_AES</strong> e cole os valores.
            </p>';

if (!empty($success_message)) {
    $page_content .= '<div class="alert alert-success">' . htmlspecialchars($success_message) . '</div>';
}

if (!empty($error_message)) {
    $page_content .= '<div class="alert alert-danger">' . htmlspecialchars($error_message) . '</div>';
}

$page_content .= '
            <form method="POST" action="">
                <div class="mb-6">
                    <label for="panel_url" class="form-label fw-semibold">URL do painel</label>
                    <input
                        type="text"
                        class="form-control"
                        name="panel_url"
                        id="panel_url"
                        placeholder="https://maxvizionpro.painelmaster.lol/ibo4/api/"
                        value="' . htmlspecialchars($currentUrl) . '">
                </div>

                <div class="mb-6">
                    <label for="aes_key" class="form-label fw-semibold">AES do app</label>
                    <div class="input-group">
                        <input
                            type="text"
                            class="form-control"
                            name="aes_key"
                            id="aes_key"
                            placeholder="Clique em Gerar AES"
                            value="' . htmlspecialchars($currentAes) . '">
                        <button type="button" class="btn btn-light-primary" onclick="gerarAes()">Gerar AES</button>
                    </div>
                    <div class="form-text">Pode usar esta mesma chave no app procurando por <strong>SUA_AES</strong>.</div>
                </div>

                <div class="mb-6">
                    <label class="form-label fw-semibold">O que colar no app</label>
                    <div class="border rounded p-4 bg-light">
                        <div><strong>SUA_PANEL_URL</strong> = <span id="preview_url">' . htmlspecialchars($currentUrl) . '</span></div>
                        <div class="mt-2"><strong>SUA_AES</strong> = <span id="preview_aes">' . htmlspecialchars($currentAes) . '</span></div>
                    </div>
                </div>

                <div class="text-center mt-6">
                    <button type="submit" class="btn btn-primary">Salvar configuração</button>
                </div>
            </form>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
function gerarAes() {
    const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let out = "";
    for (let i = 0; i < 32; i++) {
        out += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    document.getElementById("aes_key").value = out;
    document.getElementById("preview_aes").textContent = out;
}

document.getElementById("panel_url")?.addEventListener("input", function (e) {
    document.getElementById("preview_url").textContent = e.target.value;
});

document.getElementById("aes_key")?.addEventListener("input", function (e) {
    document.getElementById("preview_aes").textContent = e.target.value;
});
</script>
