<?php
session_start();

// 1. Verificação de sessão rigorosa
if (!isset($_SESSION['id']) || !$_SESSION['admin']) {
    header("Location: login.php");
    exit();
}

include 'auth.php';

// Caminhos dos arquivos (Mantidos)
$file_trial = 'trial_mode';
$file_dns = 'app_dns';
$file_url = 'app_url';

$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Lógica de Salvamento
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['btn-save'])) {
    $trial_val = isset($_POST['trial']) ? 'trial' : '';
    file_put_contents($file_trial, $trial_val);   
    
    if(isset($_POST['app_dns'])) file_put_contents($file_dns, trim($_POST['app_dns']));
    if(isset($_POST['app_url'])) file_put_contents($file_url, trim($_POST['app_url']));
    
    $_SESSION['flash_msg'] = "Configurações do Bot Atualizadas!";
    header("Location: $base_file");
    exit();
}

// Carregar Dados
$app_dns = @file_get_contents($file_dns) ?: '';
$app_url = @file_get_contents($file_url) ?: '';
$mode = @file_get_contents($file_trial) ?: '';
$checked = ($mode === 'trial') ? "checked" : "";

include "includes/header.php";
?>

<style>
    /* RESET E SEGURANÇA DE LARGURA */
    * { box-sizing: border-box; }

    /* DESIGN SYSTEM ULTRA DARK INDIGO */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #f8fafc !important;
        overflow-x: hidden;
    }
    .navbar, .lua-icon, .fa-moon, .fa-sun { display: none !important; }

    .container-fluid { padding: 15px !important; }

    /* CARD PRINCIPAL CENTRALIZADO */
    .lux-card {
        background: #0f172a !important; 
        border: 1px solid #1e293b !important;
        border-radius: 30px; 
        padding: 35px;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
        max-width: 600px; 
        margin: 20px auto 40px auto;
        width: 100%;
        animation: fadeUp 0.6s ease-out;
    }

    @keyframes fadeUp {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .lux-header { text-align: center; margin-bottom: 40px; }
    .lux-header i { 
        font-size: 3rem; color: #6366f1; 
        filter: drop-shadow(0 0 15px rgba(99, 102, 241, 0.4));
        margin-bottom: 15px;
    }
    .lux-header h1 { font-weight: 900; font-size: 1.8rem; letter-spacing: -1px; margin: 0; color: #fff; }
    .lux-header p { color: #64748b; font-size: 0.9rem; margin-top: 5px; }

    /* CONTAINER DO SWITCH */
    .switch-wrapper {
        background: #070e1b; 
        border: 1px solid #1e293b;
        padding: 25px; 
        border-radius: 20px;
        display: flex; 
        justify-content: space-between; 
        align-items: center;
        margin-bottom: 30px; 
        transition: 0.3s;
        width: 100%;
    }
    .switch-wrapper:hover { border-color: #6366f1; }
    .switch-info h4 { margin: 0; font-weight: 800; font-size: 1rem; color: #fff; }
    .switch-info p { margin: 0; font-size: 0.75rem; color: #64748b; }

    /* INPUTS LUX */
    .label-lux {
        display: block; color: #6366f1; font-size: 0.7rem;
        font-weight: 900; text-transform: uppercase; letter-spacing: 1.5px;
        margin-bottom: 10px; margin-left: 5px;
    }
    .input-lux {
        width: 100%; 
        background: #070e1b !important; 
        border: 1px solid #1e293b !important;
        color: #fff !important; 
        padding: 18px; 
        border-radius: 16px; 
        font-size: 1rem; 
        margin-bottom: 25px; 
        transition: 0.3s;
        display: block;
    }
    .input-lux:focus { border-color: #6366f1 !important; box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1); outline: none; }

    /* BOTÕES */
    .btn-save-lux {
        width: 100%; 
        background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%) !important;
        color: #fff !important; 
        padding: 20px; 
        border: none; 
        border-radius: 18px;
        font-weight: 800; 
        text-transform: uppercase; 
        cursor: pointer;
        box-shadow: 0 10px 25px rgba(99, 102, 241, 0.3); 
        transition: 0.3s;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }
    .btn-save-lux:hover { transform: translateY(-3px); box-shadow: 0 15px 30px rgba(99, 102, 241, 0.4); }
    .btn-save-lux:active { transform: scale(0.98); }

    .btn-back-lux {
        display: block; 
        text-align: center; 
        margin-top: 25px;
        color: #64748b; 
        font-weight: 700; 
        font-size: 0.8rem; 
        text-decoration: none !important;
    }

    /* CUSTOM SWITCH */
    .switch { position: relative; display: inline-block; width: 55px; height: 30px; flex-shrink: 0; }
    .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: 34px;
    }
    .slider:before {
        position: absolute; content: ""; height: 22px; width: 22px; left: 4px; bottom: 4px;
        background-color: #fff; transition: .4s; border-radius: 50%;
        box-shadow: 0 2px 5px rgba(0,0,0,0.3);
    }
    input:checked + .slider { background-color: #6366f1; }
    input:checked + .slider:before { transform: translateX(25px); }
</style>

<div class="container-fluid">
    <div class="lux-card">
        <div class="lux-header">
            <i class="fas fa-robot"></i>
            <h1>ChatBot Intel</h1>
            <p>Configurações de Automação e Webhook</p>
        </div>

        <form method="POST" action="<?= $base_file ?>">
            <input type="hidden" name="token" value="<?php echo $_SESSION['admin_token'] ?? ''; ?>">
            
            <div class="switch-wrapper">
                <div class="switch-info">
                    <h4>Teste Automático</h4>
                    <p>Habilitar trial para novos usuários</p>
                </div>
                <label class="switch">
                    <input type="checkbox" name="trial" id="trial_toggle" value="trial" <?= $checked ?>>
                    <span class="slider"></span>
                </label>
            </div>

            <div id="trial_fields" style="display: <?= ($mode === 'trial' ? 'block' : 'none') ?>;">
                <label class="label-lux">DNS do Aplicativo</label>
                <input type="text" class="input-lux" name="app_dns" placeholder="http://meu-dns.com:80" value="<?= htmlspecialchars($app_dns) ?>">

                <label class="label-lux">URL do ChatBot (Webhook)</label>
                <input type="text" class="input-lux" name="app_url" placeholder="https://api.meubot.com/webhook" value="<?= htmlspecialchars($app_url) ?>">
            </div>

            <button type="submit" name="btn-save" class="btn-save-lux">
                <i class="fas fa-sync-alt"></i> Atualizar Sistema
            </button>

            <a href="index.php" class="btn-back-lux">
                <i class="fas fa-chevron-left"></i> VOLTAR AO PAINEL
            </a>
        </form>
    </div>
</div>

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

<script>
    // Controle dinâmico dos campos com animação suave
    $('#trial_toggle').change(function() {
        if(this.checked) {
            $('#trial_fields').stop().slideDown(400);
        } else {
            $('#trial_fields').stop().slideUp(400);
        }
    });

    // Notificação de Sucesso
    <?php if (isset($_SESSION['flash_msg'])): ?>
        Swal.fire({
            icon: 'success',
            title: 'Sincronizado!',
            text: '<?= $_SESSION['flash_msg'] ?>',
            background: '#0f172a',
            color: '#fff',
            confirmButtonColor: '#6366f1',
            timer: 3000
        });
        <?php unset($_SESSION['flash_msg']); ?>
    <?php endif; ?>
</script>

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