<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

include 'session_check.php';

$db_file = __DIR__ . "/ibo_panel.db";
$conn = new PDO("sqlite:$db_file");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$page_title = "🤖 Gerenciar Chatbots";

// 🔹 Obter lista de DNS para o <select>
$dns_stmt = $conn->query("SELECT id, title FROM dns ORDER BY title ASC");
$dns_list = $dns_stmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    $action = $_POST['action'] ?? '';
    $id = $_POST['id'] ?? null;
    $bot_url = $_POST['bot_url'] ?? '';
    $bot_dns = $_POST['bot_dns'] ?? '';
    $status = $_POST['status'] ?? 'Ativo';
    $bot_name = $_POST['bot_name'] ?? 'Chatbot';

    try {
        if ($action === 'add') {
            $stmt = $conn->prepare("INSERT INTO chatbot (bot_url, bot_dns, bot_status, bot_name) VALUES (?, ?, ?, ?)");
            $stmt->execute([$bot_url, $bot_dns, $status === 'Ativo' ? 1 : 0, $bot_name]);
            echo json_encode(['status' => 'success', 'message' => '✅ Chatbot adicionado com sucesso!']);
        } elseif ($action === 'edit') {
            $stmt = $conn->prepare("UPDATE chatbot SET bot_url=?, bot_dns=?, bot_status=?, bot_name=? WHERE id=?");
            $stmt->execute([$bot_url, $bot_dns, $status === 'Ativo' ? 1 : 0, $bot_name, $id]);
            echo json_encode(['status' => 'success', 'message' => '📝 Chatbot atualizado com sucesso!']);
        } elseif ($action === 'delete') {
            $stmt = $conn->prepare("DELETE FROM chatbot WHERE id=?");
            $stmt->execute([$id]);
            echo json_encode(['status' => 'success', 'message' => '🗑️ Chatbot removido com sucesso!']);
        } else {
            echo json_encode(['status' => 'error', 'message' => '⚠️ Ação inválida.']);
        }
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => '❌ Erro: ' . $e->getMessage()]);
    }
    exit;
}

// Obter lista de chatbots
$stmt = $conn->query("SELECT * FROM chatbot ORDER BY id DESC");
$chatbots = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 🔹 Criar o <select> DNS em HTML
$dns_options_html = '';
foreach ($dns_list as $dns) {
    $dns_options_html .= '<option value="' . $dns['id'] . '">🌐 ' . htmlspecialchars($dns['title']) . '</option>';
}

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

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="card-title">🤖 Gerenciar Chatbots</h3>
        <button id="addChatbotBtn" class="btn btn-primary">➕ Adicionar Chatbot</button>
    </div>
    <div class="card-body">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>🆔 ID</th>
                    <th>🔗 Chatbot Link</th>
                    <th>🌐 DNS</th>
                    <th>⚙️ Status</th>
                    <th>📛 Nome</th>
                    <th>🛠️ Ações</th>
                </tr>
            </thead>
            <tbody>';
            foreach ($chatbots as $bot) {
                // Buscar título do DNS relacionado
                $dns_name = '';
                foreach ($dns_list as $dns) {
                    if ($dns['id'] == $bot['bot_dns']) {
                        $dns_name = $dns['title'];
                        break;
                    }
                }

                $statusEmoji = $bot['bot_status'] == 1 ? '🟢' : '🔴';
                $statusText = $bot['bot_status'] == 1 ? 'Ativo' : 'Inativo';
                $page_content .= '
                <tr>
                    <td>'.$bot['id'].'</td>
                    <td>'.$bot['bot_url'].'</td>
                    <td>🌐 '.$dns_name.'</td>
                    <td>'.$statusEmoji.' '.$statusText.'</td>
                    <td>'.$bot['bot_name'].'</td>
                    <td>
                        <button class="btn btn-sm btn-warning editBtn" 
                            data-id="'.$bot['id'].'" 
                            data-url="'.$bot['bot_url'].'" 
                            data-dns="'.$bot['bot_dns'].'" 
                            data-status="'.$statusText.'" 
                            data-name="'.$bot['bot_name'].'">✏️ Editar</button>
                        <button class="btn btn-sm btn-danger deleteBtn" data-id="'.$bot['id'].'">🗑️ Excluir</button>
                    </td>
                </tr>';
            }
$page_content .= '
            </tbody>
        </table>
    </div>
</div>

<script>
$(document).ready(function() {

    // ➕ Adicionar Chatbot
    $("#addChatbotBtn").click(function() {
        Swal.fire({
            title: "🆕 Adicionar Chatbot",
            html: `
                <input id="bot_url" class="swal2-input" placeholder="🔗 Chatbot Link">
                <input id="bot_name" class="swal2-input" placeholder="📛 Nome do Chatbot">
                <select id="bot_dns" class="swal2-input">
                    <option value="">🌐 Selecione um DNS</option>
                    '.addslashes($dns_options_html).'
                </select>
                <select id="status" class="swal2-input">
                    <option value="Ativo" selected>🟢 Ativo</option>
                    <option value="Inativo">🔴 Inativo</option>
                </select>
            `,
            confirmButtonText: "💾 Salvar",
            showCancelButton: true,
            cancelButtonText: "❌ Cancelar",
            preConfirm: () => {
                const bot_url = $("#bot_url").val();
                const bot_dns = $("#bot_dns").val();
                const bot_name = $("#bot_name").val();
                if (!bot_url || !bot_dns || !bot_name) {
                    Swal.showValidationMessage("⚠️ Preencha todos os campos!");
                    return false;
                }
                return { bot_url, bot_dns, bot_name, status: $("#status").val() };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.post(window.location.href, {
                    action: "add",
                    bot_url: result.value.bot_url,
                    bot_dns: result.value.bot_dns,
                    bot_name: result.value.bot_name,
                    status: result.value.status
                }, function(response) {
                    if (response.status === "success") {
                        Swal.fire("✅ Sucesso!", response.message, "success").then(() => location.reload());
                    } else {
                        Swal.fire("❌ Erro", response.message, "error");
                    }
                }, "json");
            }
        });
    });

    // ✏️ Editar Chatbot
    $(".editBtn").click(function() {
        const id = $(this).data("id");
        const url = $(this).data("url");
        const dns = $(this).data("dns");
        const status = $(this).data("status");
        const name = $(this).data("name");

        Swal.fire({
            title: "✏️ Editar Chatbot",
            html: `
                <input id="bot_url" class="swal2-input" value="${url}" placeholder="🔗 Chatbot Link">
                <input id="bot_name" class="swal2-input" value="${name}" placeholder="📛 Nome do Chatbot">
                <select id="bot_dns" class="swal2-input">
                    <option value="">🌐 Selecione um DNS</option>
                    '.addslashes($dns_options_html).'
                </select>
                <select id="status" class="swal2-input">
                    <option value="Ativo" ${status === "Ativo" ? "selected" : ""}>🟢 Ativo</option>
                    <option value="Inativo" ${status === "Inativo" ? "selected" : ""}>🔴 Inativo</option>
                </select>
            `,
            didOpen: () => {
                $("#bot_dns").val(dns);
            },
            confirmButtonText: "💾 Salvar",
            showCancelButton: true,
            cancelButtonText: "❌ Cancelar",
            preConfirm: () => {
                return {
                    bot_url: $("#bot_url").val(),
                    bot_dns: $("#bot_dns").val(),
                    bot_name: $("#bot_name").val(),
                    status: $("#status").val()
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.post(window.location.href, {
                    action: "edit",
                    id: id,
                    bot_url: result.value.bot_url,
                    bot_dns: result.value.bot_dns,
                    bot_name: result.value.bot_name,
                    status: result.value.status
                }, function(response) {
                    if (response.status === "success") {
                        Swal.fire("✅ Sucesso!", response.message, "success").then(() => location.reload());
                    } else {
                        Swal.fire("❌ Erro", response.message, "error");
                    }
                }, "json");
            }
        });
    });

    // 🗑️ Excluir Chatbot
    $(".deleteBtn").click(function() {
        const id = $(this).data("id");

        Swal.fire({
            title: "⚠️ Confirmar exclusão",
            text: "Tem certeza que deseja excluir este chatbot?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "🗑️ Sim, excluir",
            cancelButtonText: "❌ Cancelar"
        }).then((result) => {
            if (result.isConfirmed) {
                $.post(window.location.href, { action: "delete", id: id }, function(response) {
                    if (response.status === "success") {
                        Swal.fire("🗑️ Removido!", response.message, "success").then(() => location.reload());
                    } else {
                        Swal.fire("❌ Erro", response.message, "error");
                    }
                }, "json");
            }
        });
    });
});
</script>
';

include 'includes/layout.php';
?>
