<?php 
session_start();
// include 'auth.php'; 

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}

$json_dir = __DIR__ . '/api';
$json_path = $json_dir . '/panaci_config.json';

if (!file_exists($json_dir)) mkdir($json_dir, 0755, true);

// Inicializa o JSON com os campos necessários (sem logo)
if (!file_exists($json_path)) {
    $initial = [
        "webview_status" => "off",
        "popup_title" => "Bem-vindo",
        "popup_description" => "Sua mensagem aqui",
        "title_color" => "#ffffff",
        "desc_color" => "#cccccc"
    ];
    file_put_contents($json_path, json_encode($initial, JSON_PRETTY_PRINT));
}

$panaci_data = json_decode(file_get_contents($json_path), true);
$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Processar o formulário
if (isset($_POST['submit_panaci'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        die("Erro de Token.");
    }
    
    $panaci_data["webview_status"] = $_POST['status'];
    $panaci_data["popup_title"] = $_POST['title'];
    $panaci_data["popup_description"] = $_POST['description'];
    $panaci_data["title_color"] = $_POST['title_color'];
    $panaci_data["desc_color"] = $_POST['desc_color'];

    // Removemos a lógica de upload da logo conforme solicitado
    
    if(file_put_contents($json_path, json_encode($panaci_data, JSON_PRETTY_PRINT))) {
        $_SESSION['msg_success'] = "Configurações Salvas! O Pop-up sumirá em 10s no App.";
    } else {
        $_SESSION['msg_error'] = "Erro ao gravar JSON.";
    }
    
    header("Location: $base_file"); exit;
}

include ('includes/header.php');
?>

<style>
    * { box-sizing: border-box; }
    html, body { background-color: #020617 !important; font-family: 'Inter', sans-serif; color: white; }
    .container-lux { display: flex; justify-content: center; padding: 20px; }
    .form-lux { background: #070e1b; border-radius: 28px; padding: 30px; border: 1px solid #1e293b; max-width: 600px; width: 100%; box-shadow: 0 20px 50px rgba(0,0,0,0.6); }
    .label-lux { color: #4facfe; font-size: 0.75rem; font-weight: 800; margin-bottom: 8px; display: block; text-transform: uppercase; }
    .input-lux, .select-lux { width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important; color: #fff !important; padding: 15px; border-radius: 15px; margin-bottom: 20px; }
    .color-group { display: flex; gap: 20px; margin-bottom: 20px; }
    .color-item { flex: 1; }
    .input-color { width: 100%; height: 50px; border: none; border-radius: 10px; cursor: pointer; background: none; }
    .btn-save-lux { width: 100%; background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%); color: #fff; padding: 18px; border-radius: 18px; font-weight: 800; border: none; cursor: pointer; transition: 0.3s; }
</style>

<div class="container-lux">
    <div class="form-lux">
        <h2 style="font-weight: 900; margin-bottom: 5px;">🚀 Painel Pop-up Automático</h2>
        <p style="color: #64748b; margin-bottom: 25px;">O pop-up será exibido por 10 segundos e fechará sozinho.</p>

        <form method="post">
            <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">

            <label class="label-lux">Status do Pop-up</label>
            <select name="status" class="select-lux">
                <option value="on" <?= $panaci_data['webview_status'] == 'on' ? 'selected' : '' ?>>ATIVADO (Exibir 10 segundos)</option>
                <option value="off" <?= $panaci_data['webview_status'] == 'off' ? 'selected' : '' ?>>DESATIVADO (Oculto)</option>
            </select>

            <label class="label-lux">Título do Alerta</label>
            <input type="text" name="title" class="input-lux" value="<?= htmlspecialchars($panaci_data['popup_title']) ?>">

            <label class="label-lux">Mensagem de Descrição</label>
            <textarea name="description" class="input-lux" rows="3"><?= htmlspecialchars($panaci_data['popup_description']) ?></textarea>

            <div class="color-group">
                <div class="color-item">
                    <label class="label-lux">Cor do Título</label>
                    <input type="color" name="title_color" class="input-color" value="<?= $panaci_data['title_color'] ?>">
                </div>
                <div class="color-item">
                    <label class="label-lux">Cor da Descrição</label>
                    <input type="color" name="desc_color" class="input-color" value="<?= $panaci_data['desc_color'] ?>">
                </div>
            </div>

            <button type="submit" name="submit_panaci" class="btn-save-lux">Salvar e Atualizar App</button>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    <?php if (isset($_SESSION['msg_success'])): ?>
        Swal.fire({ icon: 'success', title: 'Sucesso!', text: '<?= $_SESSION['msg_success'] ?>', background: '#070e1b', color: '#fff' });
        <?php unset($_SESSION['msg_success']); ?>
    <?php endif; ?>
</script>

<?php include ('includes/footer.php'); ?>
