<?php
/*
 * 💬 @ Configurador de ChatBot 
 * 🚀 @ Versão: 1.0.0
 * 📅 @ Atualizado: <?= date('d/m/Y') ?>
 */

include 'includes/header.php';

// Conectar ao banco de dados
$db = new SQLite3('./api/studiolivecode.db');

// Criar tabela chatbot se não existir
$table_name = "chatbot";
$db->exec("CREATE TABLE IF NOT EXISTS " . $table_name . "(id INTEGER PRIMARY KEY AUTOINCREMENT, bot_url TEXT, bot_dns TEXT, bot_status TEXT, bot_name TEXT)");

// Verificar e inserir registro inicial
$res = $db->query("SELECT COUNT(*) as count FROM " . $table_name);
$row = $res->fetchArray();
$numRows = $row["count"];

if ($numRows == 0) {
    $db->exec("INSERT INTO " . $table_name . "(id, bot_url, bot_dns, bot_status, bot_name) VALUES(1, '', '', '0', 'SLC IBO')");
}

// Recuperar configurações atuais
$res = $db->query("SELECT * FROM " . $table_name . " WHERE id=1");
$row = $res->fetchArray();
$bot_url = $row["bot_url"];
$bot_dns = $row["bot_dns"];
$bot_status = $row["bot_status"];
$bot_name = $row["bot_name"];

// Processar formulário
if (isset($_POST["submit"])) {
    $db->exec("UPDATE " . $table_name . " SET bot_url='" . $_POST["bot_url"] . "', bot_dns='" . $_POST["bot_dns"] . "', bot_status='" . $_POST["bot_status"] . "', bot_name='" . $_POST["bot_name"] . "' WHERE id=1");
    echo "<script>window.location.href = 'chatbot.php?r=atualizado';</script>";
    exit;
}

// Recuperar DNS disponíveis
$dns_res = $db->query("SELECT * FROM dns");
$dns_options = [];
while ($dns_row = $dns_res->fetchArray()) {
    $dns_options[] = $dns_row;
}
?>

<style>
    .chatbot-card {
        border-radius: 15px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    }
    
    .chatbot-header {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        border-radius: 15px 15px 0 0 !important;
        color: white;
    }
    
    .status-active {
        color: #1cc88a !important;
        font-weight: bold;
    }
    
    .status-inactive {
        color: #e74a3b !important;
        font-weight: bold;
    }
    
    .form-icon {
        font-size: 1.2rem;
        margin-right: 10px;
        color: #4e73df;
    }
</style>

<div class="container-fluid">
    <?php if (isset($_GET['r'])): ?>
        <?php $result = $_GET['r']; ?>
        <?php switch ($result):
            case "atualizado": ?>
                <script>
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 3000,
                        timerProgressBar: true,
                        didOpen: (toast) => {
                            toast.addEventListener('mouseenter', Swal.stopTimer)
                            toast.addEventListener('mouseleave', Swal.resumeTimer)
                        }
                    });
                    Toast.fire({
                        icon: 'success',
                        title: '✅ Configurações do ChatBot atualizadas com sucesso!'
                    });
                </script>
                <?php break; ?>
        <?php endswitch; ?>
    <?php endif; ?>

    <h1 class="h3 mb-4 text-gray-800"><i class="fas fa-robot"></i> Configuração do ChatBot</h1>

    <div class="row">
        <div class="col-lg-12">
            <div class="card chatbot-card">
                <div class="card-header py-3 chatbot-header">
                    <h6 class="m-0 font-weight-bold"><i class="fas fa-cog"></i> Configurações do ChatBot</h6>
                </div>
                <div class="card-body">
                    <form method="post">
                        <div class="form-group mb-4">
                            <label for="bot_status"><i class="fas fa-power-off form-icon"></i><strong>Status do ChatBot</strong></label>
                            <div class="d-flex align-items-center">
                                <select name="bot_status" class="form-control">
                                    <option value="1" <?= $bot_status == 1 ? "selected" : "" ?>>🟢 Ativo</option>
                                    <option value="0" <?= $bot_status == 0 ? "selected" : "" ?>>🔴 Inativo</option>
                                </select>
                                <span class="ml-3 <?= $bot_status == 1 ? 'status-active' : 'status-inactive' ?>">
                                    <?= $bot_status == 1 ? "ATIVO" : "INATIVO" ?>
                                </span>
                            </div>
                        </div>
                        
                        <div class="form-group mb-4">
                            <label><i class="fas fa-link form-icon"></i><strong>URL do ChatBot</strong></label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fas fa-external-link-alt"></i></span>
                                </div>
                                <input type="text" class="form-control" name="bot_url" value="<?= htmlspecialchars($bot_url) ?>" placeholder="https://seusite.com/chatbot">
                            </div>
                            <small class="form-text text-muted">Insira o link completo do seu ChatBot</small>
                        </div>
                        
                        <div class="form-group mb-4">
                            <label><i class="fas fa-server form-icon"></i><strong>Servidor DNS</strong></label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fas fa-network-wired"></i></span>
                                </div>
                                <select name="bot_dns" class="form-control">
                                    <?php foreach ($dns_options as $dns): ?>
                                        <option value="<?= $dns['id'] ?>" <?= $bot_dns == $dns['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($dns['title']) ?> (<?= htmlspecialchars($dns['url']) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-group mb-4">
                            <label><i class="fas fa-signature form-icon"></i><strong>Nome do ChatBot</strong></label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fas fa-robot"></i></span>
                                </div>
                                <input type="text" class="form-control" name="bot_name" value="<?= htmlspecialchars($bot_name) ?>" placeholder="Ex: Suporte Automático">
                            </div>
                        </div>
                        
                        <div class="text-right mt-5">
                            <button type="submit" name="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-save"></i> 💾 Salvar Configurações
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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