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

// Configurações
$table_name = 'studiolivecode_chatbot';
$page_name = 'chatbot';

// Criar tabela se não existir
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    chatbot_link TEXT NOT NULL DEFAULT '',
    dns_url TEXT NOT NULL DEFAULT '',
    uid TEXT NOT NULL DEFAULT '',
    dns_uid TEXT NOT NULL DEFAULT '',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)";

// Executar SQL diretamente
$db_path = __DIR__ . '/.db.db';
$sqlite_db = new SQLite3($db_path);
$sqlite_db->exec($sql);
$sqlite_db->close();

// Inserir registro vazio se a tabela estiver vazia
$data = [
    'chatbot_link' => '',
    'dns_url' => '', 
    'uid' => '',
    'dns_uid' => ''
];

$db->insertIfEmpty($table_name, $data);

// Buscar todos os registros (sempre terá apenas 1)
$res = $db->select($table_name, '*', '', '');

// Buscar DNS disponíveis para o select
$dns_list = $db->select('dns', '*', '', '');

// Processar atualização
if(isset($_POST['submit'])){
    unset($_POST['submit']);
    $updateData = $_POST;
    
    // Buscar dados da DNS selecionada
    if(isset($updateData['dns_url']) && !empty($updateData['dns_url'])){
        $selected_dns = $db->select('dns', '*', 'url = :url', '', [':url' => $updateData['dns_url']]);
        if(!empty($selected_dns)){
            // Pegar o UID da DNS selecionada
            $updateData['uid'] = $selected_dns[0]['uid'];
            $updateData['dns_uid'] = $selected_dns[0]['uid'];
        }
    }
    
    $db->update($table_name, $updateData, 'id = :id',[':id' => 1]);
    echo "<script>window.location.href='". $page_name.".php'</script>";
}
?>

<!-- Form Start -->
<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h2 class="mb-4">Configuração do Chatbot</h6>
                    <form method="post">
                        <div class="mb-3">
                            <label for="chatbot_link" class="form-label">Link do Chatbot</label>
                            <input type="text" 
                                   name="chatbot_link" 
                                   class="form-control" 
                                   value="<?= $res[0]['chatbot_link'] ?>" 
                                   placeholder="https://link_chatbot.top/api/chatbot/token478798719879822"
                                   required>
                            <div class="form-text">
                                Link completo do chatbot
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="dns_url" class="form-label">Escolha a DNS</label>
                            <select class="form-select" name="dns_url" required>
                                <option value="">Selecione uma DNS</option>
                                <?php foreach ($dns_list as $dns) { 
                                    $selected = ($dns['url'] == $res[0]['dns_url']) ? 'selected' : '';
                                ?>
                                <option value="<?= $dns['url'] ?>" <?= $selected ?>>
                                    <?= $dns['title'] ?> - <?= $dns['url'] ?>
                                </option>
                                <?php } ?>
                            </select>
                            <div class="form-text">
                                Ao salvar, o sistema pegará o UID desta DNS automaticamente
                            </div>
                        </div>
                        
                        <button type="submit" name="submit" class="btn btn-primary">Salvar Configurações</button>
                        
                        <?php if(!empty($res[0]['chatbot_link']) && !empty($res[0]['dns_url']) && !empty($res[0]['uid'])) { ?>
                        <div class="mt-4 p-3 bg-dark rounded">
                            <h6>Dados que serão retornados no JSON:</h6>
                            <div class="mt-3">
                                <p><strong>Link do Chatbot:</strong> <?= $res[0]['chatbot_link'] ?></p>
                                <p><strong>DNS URL:</strong> <?= $res[0]['dns_url'] ?></p>
                                <p><strong>UID (da DNS):</strong> <?= $res[0]['uid'] ?></p>
                            </div>
                            <pre class="text-white mt-3 mb-0">{
    "chatbot_link": "<?= $res[0]['chatbot_link'] ?>",
    "dns_url": "<?= $res[0]['dns_url'] ?>",
    "uid": "<?= $res[0]['uid'] ?>"
}</pre>
                        </div>
                        <?php } ?>
                    </form>
            </div>
        </div>
    </div>
</div>
<!-- Form End -->

<!-- Footer Start -->
<?php include ('includes/footer.php');?>
<!-- Footer End -->
</body>
</html>