<?php


//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->


error_reporting(E_ALL);
ini_set('display_errors', 1);

// =======================================================
// Caminhos dos bancos
// =======================================================
$db_path = __DIR__ . "/api/db/eonbrybot.db";
$main_db_path = __DIR__ . "/a/.eggziedb.db"; // novo banco secundário

// =======================================================
// BANCO PRINCIPAL (BOT CONFIGURAÇÃO)
// =======================================================
if (!file_exists($db_path)) {
    $db = new SQLite3($db_path);
    $db->exec("CREATE TABLE bot (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        bot_url TEXT,
        bot_dns TEXT,
        bot_status TEXT,
        bot_name TEXT
    )");
    $db->exec("INSERT INTO bot (bot_url, bot_dns, bot_status, bot_name)
               VALUES ('', '', '0', 'SLC IBO')");
} else {
    $db = new SQLite3($db_path);
}

$db->exec("CREATE TABLE IF NOT EXISTS bot (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    bot_url TEXT,
    bot_dns TEXT,
    bot_status TEXT,
    bot_name TEXT
)");

$res = $db->query("SELECT * FROM bot WHERE id = 1");
if (!$res->fetchArray(SQLITE3_ASSOC)) {
    $db->exec("INSERT INTO bot (bot_url, bot_dns, bot_status, bot_name)
               VALUES ('', '', '0', 'SLC IBO')");
}

// =======================================================
// BANCO SECUNDÁRIO (a/.eggziedb.db)
// =======================================================
if (!file_exists($main_db_path)) {
    $main_db = new SQLite3($main_db_path);

    // Cria estrutura base tipo StudioLiveCode
    $main_db->exec("CREATE TABLE IF NOT EXISTS revenda (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        nome TEXT NOT NULL,
        usuario TEXT NOT NULL,
        senha TEXT NOT NULL,
        registro TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        macs INTEGER DEFAULT 0,
        extra TEXT,
        id_ref INTEGER
    )");

    $main_db->exec("CREATE TABLE IF NOT EXISTS sub_revenda (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        nome TEXT NOT NULL,
        usuario TEXT NOT NULL,
        senha TEXT NOT NULL,
        registro TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        macs INTEGER DEFAULT 0,
        registrado_por TEXT,
        extra TEXT,
        id_ref INTEGER
    )");

    $main_db->exec("CREATE TABLE IF NOT EXISTS ibo (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        mac_address VARCHAR(100),
        username VARCHAR(100),
        password VARCHAR(100),
        expire_date VARCHAR(100),
        url VARCHAR(200),
        title VARCHAR(100),
        created_at VARCHAR(100),
        seller TEXT,
        extra TEXT
    )");

    $main_db->exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_mac_address ON ibo(mac_address)");

    $main_db->exec("CREATE TABLE IF NOT EXISTS theme (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name VARCHAR(100),
        url VARCHAR(200)
    )");

    // Inserir um tema padrão se estiver vazio
    $count = $main_db->querySingle("SELECT COUNT(*) FROM theme");
    if ($count == 0) {
        $main_db->exec("INSERT INTO theme (name, url)
                        VALUES ('Default', 'https://studiolivecode.com.br/assets/front/img/6529ab52dfeaf.png')");
    }
} else {
    $main_db = new SQLite3($main_db_path);
}

// =======================================================
// SALVAR BOT
// =======================================================
$showSuccess = false;

if (isset($_POST['submit'])) {
    $bot_url = SQLite3::escapeString($_POST['bot_url']);
    $bot_dns = SQLite3::escapeString($_POST['bot_dns']);
    $bot_status = SQLite3::escapeString($_POST['bot_status']);
    $bot_name = SQLite3::escapeString($_POST['bot_name']);

    $stmt = $db->prepare("UPDATE bot 
        SET bot_url = :url, bot_dns = :dns, bot_status = :status, bot_name = :name 
        WHERE id = 1");
    $stmt->bindValue(':url', $bot_url, SQLITE3_TEXT);
    $stmt->bindValue(':dns', $bot_dns, SQLITE3_TEXT);
    $stmt->bindValue(':status', $bot_status, SQLITE3_TEXT);
    $stmt->bindValue(':name', $bot_name, SQLITE3_TEXT);
    $stmt->execute();

    $showSuccess = true;
}

// =======================================================
// CARREGAR BOT
// =======================================================
$res = $db->query("SELECT * FROM bot WHERE id = 1");
$row = $res->fetchArray(SQLITE3_ASSOC);

$bot_url = $row['bot_url'] ?? '';
$bot_dns = $row['bot_dns'] ?? '';
$bot_status = $row['bot_status'] ?? '0';
$bot_name = $row['bot_name'] ?? 'SLC IBO';

include 'includes/header.php';
?>

<!-- ===================== ESTILO ===================== -->
<style>
:root {
    --primary: #00D4FF;
    --primary-dark: #0099CC;
    --secondary: #FF6B9D;
    --accent: #00FF88;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --text-secondary: #B0B7C3;
    --border: rgba(255,255,255,0.1);
    --glow: 0 0 20px rgba(0, 212, 255, 0.3);
}
body {
    background: var(--surface);
    color: var(--text-primary);
    font-family: "Inter", sans-serif;
    padding: 30px;
}
.card {
    background: var(--surface-light);
    border: 1px solid var(--border);
    border-radius: 20px;
    box-shadow: 0 8px 40px rgba(0,0,0,0.4);
    overflow: hidden;
    position: relative;
}
.card::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary), var(--accent), var(--secondary));
    animation: borderGlow 3s ease-in-out infinite;
}
@keyframes borderGlow { 0%,100%{opacity:0.7;} 50%{opacity:1;} }
.card h4 {
    font-weight: 700;
    color: var(--primary);
}
label { color: var(--text-secondary); font-weight: 500; }
.form-control, .form-select {
    background: var(--surface-lighter)!important;
    border: 1px solid var(--border)!important;
    color: var(--text-primary)!important;
    border-radius: 12px!important;
    padding: 14px 18px!important;
}
.btn-primary {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark))!important;
    border: none!important;
    border-radius: 12px!important;
    box-shadow: var(--glow)!important;
    padding: 12px 24px!important;
    font-weight: 600!important;
    text-transform: uppercase;
}
.btn-primary:hover {
    transform: translateY(-3px)!important;
    box-shadow: 0 8px 25px rgba(0,212,255,0.5)!important;
}
footer {
    margin-top: 50px;
    text-align: center;
    color: var(--text-secondary);
    font-size: 0.9rem;
    opacity: 0.6;
}
</style>

<div class="container mt-5">
  <div class="card p-5">
    <h4 class="mb-4">⚙️ Configuração do Bot</h4>
    <form method="post" action="chat.php">
      <div class="mb-3">
        <label class="form-label"><strong>Status</strong></label>
        <select name="bot_status" class="form-select">
          <option value="1" <?= $bot_status == '1' ? 'selected' : '' ?>>Ativo</option>
          <option value="0" <?= $bot_status == '0' ? 'selected' : '' ?>>Inativo</option>
        </select>
      </div>
      <div class="mb-3">
        <label class="form-label"><strong>Link do Chatbot</strong></label>
        <input type="text" class="form-control" name="bot_url"
               value="<?= htmlspecialchars($bot_url) ?>" placeholder="https://example.com/chatbot">
      </div>
      <div class="mb-3">
        <label class="form-label"><strong>DNS do Servidor</strong></label>
        <input type="text" class="form-control" name="bot_dns"
               value="<?= htmlspecialchars($bot_dns) ?>" placeholder="dns.exemplo.com">
      </div>
      <div class="mb-3">
        <label class="form-label"><strong>Nome da Lista</strong></label>
        <input type="text" class="form-control" name="bot_name"
               value="<?= htmlspecialchars($bot_name) ?>" placeholder="Nome da Lista">
      </div>
      <button type="submit" name="submit" class="btn btn-primary mt-3">
        <i class='bx bx-check'></i> Salvar Configuração
      </button>
    </form>
  </div>
</div>

<?php if ($showSuccess): ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
  icon: 'success',
  title: 'Configurações salvas com sucesso!',
  timer: 2500,
  showConfirmButton: false,
  toast: true,
  position: 'bottom-end'
});
</script>
<?php endif; ?>

<footer>© <?= date('Y'); ?> Painel EonBryBot — Todos os direitos reservados</footer>

</body>
</html>
