<?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;
    $chatbot_link = $_POST['chatbot_link'] ?? '';
    $dns_id = $_POST['dns_id'] ?? '';
    $status = $_POST['status'] ?? 'Ativo';

    try {
        if ($action === 'add') {
            $stmt = $conn->prepare("INSERT INTO chatbot_slc_max (chatbot_link, dns_id, status) VALUES (?, ?, ?)");
            $stmt->execute([$chatbot_link, $dns_id, $status]);
            echo json_encode(['status' => 'success', 'message' => '✅ Chatbot adicionado com sucesso!']);
        } elseif ($action === 'edit') {
            $stmt = $conn->prepare("UPDATE chatbot_slc_max SET chatbot_link=?, dns_id=?, status=?, updated_at=CURRENT_TIMESTAMP WHERE id=?");
            $stmt->execute([$chatbot_link, $dns_id, $status, $id]);
            echo json_encode(['status' => 'success', 'message' => '📝 Chatbot atualizado com sucesso!']);
        } elseif ($action === 'delete') {
            $stmt = $conn->prepare("DELETE FROM chatbot_slc_max 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_slc_max 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>📅 Criado em</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['dns_id']) {
                        $dns_name = $dns['title'];
                        break;
                    }
                }

                $statusEmoji = $bot['status'] === 'Ativo' ? '🟢' : '🔴';
                $page_content .= '
                <tr>
                    <td>'.$bot['id'].'</td>
                    <td>'.$bot['chatbot_link'].'</td>
                    <td>🌐 '.$dns_name.'</td>
                    <td>'.$statusEmoji.' '.$bot['status'].'</td>
                    <td>'.$bot['created_at'].'</td>
                    <td>
                        <button class="btn btn-sm btn-warning editBtn" data-id="'.$bot['id'].'" data-link="'.$bot['chatbot_link'].'" data-dns="'.$bot['dns_id'].'" data-status="'.$bot['status'].'">✏️ 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="chatbot_link" class="swal2-input" placeholder="🔗 Chatbot Link">
                <select id="dns_id" class="swal2-input">
                    <option value="">🌐 Selecione um DNS</option>
                    '.addslashes($dns_options_html).'
                </select>
            `,
            confirmButtonText: "💾 Salvar",
            showCancelButton: true,
            cancelButtonText: "❌ Cancelar",
            preConfirm: () => {
                const chatbot_link = $("#chatbot_link").val();
                const dns_id = $("#dns_id").val();
                if (!chatbot_link || !dns_id) {
                    Swal.showValidationMessage("⚠️ Preencha todos os campos!");
                    return false;
                }
                return { chatbot_link, dns_id };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.post(window.location.href, {
                    action: "add",
                    chatbot_link: result.value.chatbot_link,
                    dns_id: result.value.dns_id
                }, 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 link = $(this).data("link");
        const dns = $(this).data("dns");
        const status = $(this).data("status");

        Swal.fire({
            title: "✏️ Editar Chatbot",
            html: `
                <input id="chatbot_link" class="swal2-input" value="${link}" placeholder="🔗 Chatbot Link">
                <select id="dns_id" 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: () => {
                $("#dns_id").val(dns);
            },
            confirmButtonText: "💾 Salvar",
            showCancelButton: true,
            cancelButtonText: "❌ Cancelar",
            preConfirm: () => {
                return {
                    chatbot_link: $("#chatbot_link").val(),
                    dns_id: $("#dns_id").val(),
                    status: $("#status").val()
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.post(window.location.href, {
                    action: "edit",
                    id: id,
                    chatbot_link: result.value.chatbot_link,
                    dns_id: result.value.dns_id,
                    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';
?>
