<?php
$db_file = __DIR__ . '/api/db_planos.db';
$msg_file = __DIR__ . '/api/mensagem2.txt'; // Caminho do arquivo de texto

try {
    $pdo = new PDO("sqlite:" . $db_file);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("CREATE TABLE IF NOT EXISTS planos (id INTEGER PRIMARY KEY, titulo TEXT, qrcode_url TEXT, valor TEXT, cor_texto TEXT DEFAULT '#ffffff', cor_titulo TEXT DEFAULT '#ffffff')");
    
    $cols = $pdo->query("PRAGMA table_info(planos)")->fetchAll(PDO::FETCH_COLUMN, 1);
    if (!in_array('cor_titulo', $cols)) { $pdo->exec("ALTER TABLE planos ADD COLUMN cor_titulo TEXT DEFAULT '#ffffff'"); }
} catch(PDOException $e) { die("Erro: " . $e->getMessage()); }

// Lógica para Salvar
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Salvar Planos
    for ($i = 1; $i <= 3; $i++) {
        $pdo->prepare("UPDATE planos SET titulo=?, qrcode_url=?, valor=?, cor_texto=?, cor_titulo=? WHERE id=?")
            ->execute([$_POST["titulo_$i"], $_POST["qr_$i"], $_POST["valor_$i"], $_POST["cor_val_$i"], $_POST["cor_tit_$i"], $i]);
    }

    // Salvar Mensagem (Texto|Cor|Efeito)
    if (isset($_POST['texto_msg'])) {
        $texto = $_POST['texto_msg'];
        $cor = $_POST['cor_msg'];
        $efeito = isset($_POST['efeito_msg']) ? 'blink' : 'none';
        $dados_msg = $texto . '|' . $cor . '|' . $efeito;
        file_put_contents($msg_file, $dados_msg);
    }

    $mensagem = "Alterações aplicadas com sucesso!";
}

$planos = $pdo->query("SELECT * FROM planos ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);

// Ler mensagem atual
$msg_atual = ["texto" => "", "cor" => "#ffffff", "efeito" => "none"];
if (file_exists($msg_file)) {
    $conteudo = explode('|', file_get_contents($msg_file));
    $msg_atual['texto'] = $conteudo[0] ?? "";
    $msg_atual['cor'] = $conteudo[1] ?? "#ffffff";
    $msg_atual['efeito'] = $conteudo[2] ?? "none";
}

include "includes/header.php"; 
?>

<style>
    /* ... Seus estilos anteriores mantidos ... */
    * { box-sizing: border-box; }
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #e2e8f0 !important;
        overflow-x: hidden;
    }
    .lua-icon, .fa-moon, .fa-sun, .navbar, #dark-mode-switch { display: none !important; }
    .container-fluid { padding: 15px !important; }
    .btn-back-nav {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        color: #64748b;
        text-decoration: none !important;
        font-size: 0.85rem;
        font-weight: 600;
        margin-bottom: 20px;
        max-width: 650px;
        margin-left: auto;
        margin-right: auto;
    }
    .premium-card {
        background: #070e1b !important;
        border: 1px solid #1e293b !important;
        border-radius: 20px;
        padding: 25px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.3);
        max-width: 650px;
        margin: 0 auto 20px auto;
        width: 100%;
        animation: slideUp 0.4s ease-out;
    }
    @keyframes slideUp { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
    .card-header-premium { 
        margin-bottom: 20px; border-bottom: 1px solid rgba(255,255,255,0.05); 
        padding-bottom: 10px; display: flex; justify-content: space-between; align-items: center;
    }
    .card-header-premium h2 { font-size: 1.1rem; font-weight: 800; color: #3b82f6; margin: 0; text-transform: uppercase; }
    label { display: block; color: #3b82f6; font-size: 0.7rem; font-weight: 800; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px; }
    .form-input { 
        width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important; 
        color: #fff !important; padding: 12px; border-radius: 12px; font-size: 0.9rem; margin-bottom: 15px; transition: 0.3s;
    }
    .form-input:focus { border-color: #3b82f6 !important; outline: none; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); }
    .color-row { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px; }
    input[type="color"] { height: 45px; padding: 2px; cursor: pointer; background: #0f172a !important; border: 1px solid #1e293b !important; }
    .btn-save-container { max-width: 650px; margin: 10px auto 40px auto; }
    .btn-premium-save {
        width: 100%; background: #3b82f6 !important; color: #fff !important; padding: 18px; border-radius: 15px; 
        font-weight: 800; text-transform: uppercase; border: none; cursor: pointer; display: flex; 
        align-items: center; justify-content: center; gap: 10px; transition: 0.3s;
    }
    .header-main-title { text-align: center; margin-bottom: 30px; }
    .header-main-title h1 { font-size: 1.5rem; font-weight: 800; color: #fff; margin-bottom: 5px; }
    .header-main-title p { color: #64748b; font-size: 0.85rem; }

    /* ESTILO ESPECÍFICO PARA A ÁREA DE MENSAGEM */
    .msg-section { border: 1px solid #3b82f6 !important; background: #0f172a !important; }
    .switch-container { display: flex; align-items: center; gap: 10px; margin-top: 10px; }
    .switch { position: relative; display: inline-block; width: 40px; height: 20px; }
    .switch input { opacity: 0; width: 0; height: 0; }
    .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #1e293b; transition: .4s; border-radius: 20px; }
    .slider:before { position: absolute; content: ""; height: 14px; width: 14px; left: 3px; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%; }
    input:checked + .slider { background-color: #3b82f6; }
    input:checked + .slider:before { transform: translateX(20px); }
</style>

<div class="container-fluid">
    <div style="max-width: 650px; margin: 0 auto;">
        <a href="index.php" class="btn-back-nav">
            <i class="fas fa-chevron-left"></i> Voltar ao Painel
        </a>
    </div>

    <div class="header-main-title">
        <h1>Configuração da API</h1>
        <p>Personalize os planos e a mensagem do Webview</p>
    </div>

    <form method="POST" id="formPlanos">
        <?php foreach($planos as $p): ?>
        <div class="premium-card">
            <div class="card-header-premium">
                <h2>Plano <?= $p['id'] ?></h2>
                <i class="fas fa-shopping-cart" style="color: #1e293b;"></i>
            </div>
            <label>Título Informativo</label>
            <input type="text" class="form-input" name="titulo_<?= $p['id'] ?>" value="<?= htmlspecialchars($p['titulo']) ?>">

            <div class="color-row">
                <div>
                    <label>Cor do Título</label>
                    <input type="color" class="form-input" name="cor_tit_<?= $p['id'] ?>" value="<?= $p['cor_titulo'] ?>">
                </div>
                <div>
                    <label>Cor do Valor</label>
                    <input type="color" class="form-input" name="cor_val_<?= $p['id'] ?>" value="<?= $p['cor_texto'] ?>">
                </div>
            </div>

            <label>Link Direto do QR CODE (URL)</label>
            <input type="text" class="form-input" name="qr_<?= $p['id'] ?>" value="<?= htmlspecialchars($p['qrcode_url']) ?>">

            <label>Valor em Texto</label>
            <input type="text" class="form-input" name="valor_<?= $p['id'] ?>" value="<?= htmlspecialchars($p['valor']) ?>">
        </div>
        <?php endforeach; ?>

        <div class="premium-card msg-section">
            <div class="card-header-premium">
                <h2 style="color: #10b981;">Mensagem do Webview</h2>
                <i class="fas fa-comment-dots" style="color: #10b981;"></i>
            </div>

            <label>Texto da Mensagem (Exibido no App)</label>
            <input type="text" class="form-input" name="texto_msg" value="<?= htmlspecialchars($msg_atual['texto']) ?>" placeholder="Digite o texto aqui...">

            <div class="color-row">
                <div>
                    <label>Cor do Texto (RGB)</label>
                    <input type="color" class="form-input" name="cor_msg" value="<?= $msg_atual['cor'] ?>">
                </div>
                <div>
                    <label>Efeito de Texto</label>
                    <div class="switch-container">
                        <span style="font-size: 0.75rem; color: #64748b;">Piscar Texto</span>
                        <label class="switch">
                            <input type="checkbox" name="efeito_msg" <?= $msg_atual['efeito'] == 'blink' ? 'checked' : '' ?>>
                            <span class="slider"></span>
                        </label>
                    </div>
                </div>
            </div>
            <p style="font-size: 0.65rem; color: #64748b; margin-top: -5px;">* Esta mensagem aparecerá centralizada no Webview.</p>
        </div>

        <div class="btn-save-container">
            <button type="submit" class="btn-premium-save">
                <i class="fas fa-save"></i> Atualizar Tudo (Planos + Mensagem)
            </button>
        </div>
    </form>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<?php if(isset($mensagem)): ?>
<script>
    Swal.fire({ icon: 'success', title: 'Sucesso!', text: '<?= $mensagem ?>', background: '#070e1b', color: '#fff', confirmButtonColor: '#3b82f6' });
</script>
<?php endif; ?>

<?php include "includes/footer.php"; ?>
