<?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 === 'toggle_status') {
            $stmt = $conn->prepare("UPDATE chatbot SET bot_status = NOT bot_status WHERE id=?");
            $stmt->execute([$id]);
            echo json_encode(['status' => 'success', 'message' => 'Status alterado 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);
$total    = count($chatbots);

// Montar opções de DNS
$dns_options_html = '';
foreach ($dns_list as $dns) {
    $dns_options_html .= '<option value="' . $dns['id'] . '">' . htmlspecialchars($dns['title']) . '</option>';
}

// ── Montar cards dos chatbots ──────────────────────────────────────────────
$cards_html = '';
foreach ($chatbots as $bot) {
    $dns_name = '';
    foreach ($dns_list as $dns) {
        if ($dns['id'] == $bot['bot_dns']) { $dns_name = $dns['title']; break; }
    }

    $isActive   = $bot['bot_status'] == 1;
    $statusText = $isActive ? 'Ativo' : 'Inativo';
    $created    = date('d/m/Y', strtotime($bot['created_at'] ?? 'now'));

    $cards_html .= '
    <div class="col-xl-4 col-lg-6 col-md-6">
        <div class="bot-card" id="card_' . $bot['id'] . '">

            <div class="bot-card-header">
                <div class="bot-card-title">
                    <div class="bot-icon-wrap">
                        <i class="fa-solid fa-robot"></i>
                    </div>
                    <span>' . htmlspecialchars($bot['bot_name']) . '</span>
                </div>
                <span class="bot-status-badge ' . ($isActive ? 'badge-active' : 'badge-inactive') . '">
                    <i class="fa-solid fa-circle-dot"></i>
                    ' . $statusText . '
                </span>
            </div>

            <div class="bot-card-body">
                <div class="bot-field">
                    <span class="bot-field-label"><i class="fa-solid fa-link"></i> URL</span>
                    <div class="bot-url-row">
                        <span class="bot-url-text">' . htmlspecialchars($bot['bot_url']) . '</span>
                        <button class="btn-copy" title="Copiar URL"
                            onclick="copyToClipboard(\'' . htmlspecialchars($bot['bot_url'], ENT_QUOTES) . '\')">
                            <i class="fa-regular fa-copy"></i>
                        </button>
                    </div>
                </div>

                <div class="bot-field">
                    <span class="bot-field-label"><i class="fa-solid fa-globe"></i> DNS Associado</span>
                    <span class="bot-dns-badge">' . htmlspecialchars($dns_name) . '</span>
                </div>
            </div>

            <div class="bot-card-footer">
                <span class="bot-meta">ID #' . $bot['id'] . ' &nbsp;·&nbsp; ' . $created . '</span>
                <div class="bot-actions">
                    <button class="btn-edit-bot editBtn" title="Editar"
                        data-id="' . $bot['id'] . '"
                        data-url="' . htmlspecialchars($bot['bot_url'], ENT_QUOTES) . '"
                        data-dns="' . $bot['bot_dns'] . '"
                        data-status="' . $statusText . '"
                        data-name="' . htmlspecialchars($bot['bot_name'], ENT_QUOTES) . '">
                        <i class="fa-solid fa-pen-to-square"></i>
                    </button>
                    <button class="btn-toggle-bot toggleBtn
                        ' . ($isActive ? 'btn-toggle-off' : 'btn-toggle-on') . '" title="' . ($isActive ? 'Desativar' : 'Ativar') . '"
                        data-id="' . $bot['id'] . '"
                        data-current-status="' . $bot['bot_status'] . '">
                        <i class="fa-solid ' . ($isActive ? 'fa-pause' : 'fa-play') . '"></i>
                    </button>
                </div>
            </div>

        </div>
    </div>';
}

if ($cards_html === '') {
    $cards_html = '
    <div class="col-12">
        <div class="bot-empty">
            <i class="fa-solid fa-robot"></i>
            <p>Nenhum chatbot cadastrado ainda.</p>
        </div>
    </div>';
}

$page_content = '
<style>
/* ═══════════════════════════
   PAGE HEADER
═══════════════════════════ */
.mac-page-header {
    background: linear-gradient(135deg, #0d1117 0%, #1a2744 50%, #0d1117 100%);
    border: 1px solid rgba(99,179,237,0.12);
    border-radius: 16px;
    padding: 28px 32px;
    margin-bottom: 24px;
    margin-top: 24px;
    position: relative;
    overflow: hidden;
}
.mac-page-header::before {
    content: "";
    position: absolute;
    top: -60px; right: -60px;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(139,92,246,0.1) 0%, transparent 70%);
    pointer-events: none;
}
.mac-page-header::after {
    content: "";
    position: absolute;
    bottom: -40px; left: 30%;
    width: 150px; height: 150px;
    background: radial-gradient(circle, rgba(99,179,237,0.07) 0%, transparent 70%);
    pointer-events: none;
}
.mac-page-header h1 {
    color: #e2e8f0;
    font-size: 22px;
    font-weight: 700;
    margin: 0 0 6px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.mac-page-header h1 .icon-wrap {
    width: 40px; height: 40px;
    background: rgba(139,92,246,0.12);
    border: 1px solid rgba(139,92,246,0.22);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    color: #a78bfa;
    flex-shrink: 0;
}
.mac-page-header p {
    color: rgba(148,163,184,0.7);
    font-size: 13px;
    margin: 0;
}
.mac-stat-pill {
    background: rgba(139,92,246,0.08);
    border: 1px solid rgba(139,92,246,0.15);
    border-radius: 50px;
    padding: 6px 14px;
    color: #a78bfa;
    font-size: 12px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 6px;
    flex-shrink: 0;
}

/* ═══════════════════════════
   TOOLBAR
═══════════════════════════ */
.bot-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 20px;
}
.mac-search-wrap { position: relative; }
.mac-search-wrap i {
    position: absolute;
    left: 14px; top: 50%;
    transform: translateY(-50%);
    color: rgba(148,163,184,0.4);
    font-size: 14px;
    pointer-events: none;
}
.mac-search-wrap input {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.08) !important;
    border-radius: 10px !important;
    color: #e2e8f0 !important;
    padding: 9px 14px 9px 38px !important;
    font-size: 13px !important;
    width: 240px;
    transition: all 0.2s ease !important;
}
.mac-search-wrap input::placeholder { color: rgba(148,163,184,0.4) !important; }
.mac-search-wrap input:focus {
    border-color: rgba(139,92,246,0.4) !important;
    background: rgba(139,92,246,0.04) !important;
    box-shadow: 0 0 0 3px rgba(139,92,246,0.08) !important;
    outline: none !important;
}
.btn-add-mac {
    background: linear-gradient(135deg, #6d28d9, #a78bfa) !important;
    border: none !important;
    border-radius: 10px !important;
    color: #fff !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 9px 18px !important;
    display: flex; align-items: center; gap: 8px;
    transition: all 0.2s ease !important;
    box-shadow: 0 4px 12px rgba(139,92,246,0.25) !important;
    cursor: pointer;
}
.btn-add-mac:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(139,92,246,0.35) !important;
}

/* ═══════════════════════════
   BOT CARDS
═══════════════════════════ */
.bot-card {
    background: #161b22;
    border: 1px solid rgba(99,179,237,0.08);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(0,0,0,0.3);
    transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
    margin-bottom: 20px;
}
.bot-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 32px rgba(0,0,0,0.4);
    border-color: rgba(139,92,246,0.18);
}
.bot-card-header {
    background: linear-gradient(135deg, rgba(109,40,217,0.18) 0%, rgba(99,179,237,0.08) 100%);
    border-bottom: 1px solid rgba(255,255,255,0.06);
    padding: 16px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}
.bot-card-title {
    display: flex;
    align-items: center;
    gap: 10px;
    color: #e2e8f0;
    font-size: 14px;
    font-weight: 700;
    min-width: 0;
}
.bot-card-title span {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.bot-icon-wrap {
    width: 32px; height: 32px;
    background: rgba(139,92,246,0.15);
    border: 1px solid rgba(139,92,246,0.25);
    border-radius: 8px;
    display: flex; align-items: center; justify-content: center;
    font-size: 14px;
    color: #a78bfa;
    flex-shrink: 0;
}
.bot-status-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    border-radius: 50px;
    padding: 4px 10px;
    font-size: 11px;
    font-weight: 700;
    flex-shrink: 0;
    white-space: nowrap;
}
.badge-active {
    background: rgba(52,211,153,0.1);
    border: 1px solid rgba(52,211,153,0.2);
    color: #34d399;
}
.badge-inactive {
    background: rgba(248,113,113,0.1);
    border: 1px solid rgba(248,113,113,0.2);
    color: #f87171;
}
.bot-card-body {
    padding: 18px 20px;
    display: flex;
    flex-direction: column;
    gap: 14px;
}
.bot-field { display: flex; flex-direction: column; gap: 6px; }
.bot-field-label {
    color: rgba(148,163,184,0.5);
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.08em;
}
.bot-url-row {
    display: flex;
    align-items: center;
    gap: 8px;
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.06);
    border-radius: 8px;
    padding: 7px 10px;
}
.bot-url-text {
    flex: 1;
    font-family: monospace;
    font-size: 12px;
    color: #63b3ed;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.btn-copy {
    background: rgba(99,179,237,0.08);
    border: 1px solid rgba(99,179,237,0.15);
    border-radius: 6px;
    color: #63b3ed;
    font-size: 12px;
    width: 26px; height: 26px;
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
    cursor: pointer;
    transition: all 0.2s ease;
}
.btn-copy:hover {
    background: rgba(99,179,237,0.18);
    transform: scale(1.1);
}
.bot-dns-badge {
    background: rgba(139,92,246,0.08);
    border: 1px solid rgba(139,92,246,0.15);
    border-radius: 6px;
    padding: 4px 10px;
    font-size: 12px;
    font-weight: 600;
    color: #a78bfa;
    display: inline-block;
}
.bot-card-footer {
    background: rgba(255,255,255,0.02);
    border-top: 1px solid rgba(255,255,255,0.05);
    padding: 12px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}
.bot-meta {
    color: rgba(148,163,184,0.35);
    font-size: 11px;
}
.bot-actions { display: flex; gap: 8px; }
.btn-edit-bot {
    background: rgba(251,191,36,0.1) !important;
    border: 1px solid rgba(251,191,36,0.2) !important;
    color: #fbbf24 !important;
    border-radius: 8px !important;
    font-size: 13px !important;
    width: 32px; height: 32px;
    padding: 0 !important;
    display: inline-flex; align-items: center; justify-content: center;
    transition: all 0.2s ease !important;
    cursor: pointer;
}
.btn-edit-bot:hover {
    background: rgba(251,191,36,0.22) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(251,191,36,0.2) !important;
}
.btn-toggle-bot {
    border-radius: 8px !important;
    font-size: 13px !important;
    width: 32px; height: 32px;
    padding: 0 !important;
    display: inline-flex; align-items: center; justify-content: center;
    transition: all 0.2s ease !important;
    cursor: pointer;
}
.btn-toggle-off {
    background: rgba(248,113,113,0.1) !important;
    border: 1px solid rgba(248,113,113,0.2) !important;
    color: #f87171 !important;
}
.btn-toggle-off:hover {
    background: rgba(248,113,113,0.22) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(248,113,113,0.2) !important;
}
.btn-toggle-on {
    background: rgba(52,211,153,0.1) !important;
    border: 1px solid rgba(52,211,153,0.2) !important;
    color: #34d399 !important;
}
.btn-toggle-on:hover {
    background: rgba(52,211,153,0.22) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(52,211,153,0.2) !important;
}
.bot-empty {
    text-align: center;
    padding: 60px 20px;
    color: rgba(148,163,184,0.3);
}
.bot-empty i { font-size: 48px; margin-bottom: 16px; display: block; }
.bot-empty p { font-size: 14px; margin: 0; }

/* ═══════════════════════════
   MODAL
═══════════════════════════ */
#chatbotModal .modal-content {
    background: #161b22 !important;
    border: 1px solid rgba(139,92,246,0.12) !important;
    border-radius: 16px !important;
    box-shadow: 0 24px 64px rgba(0,0,0,0.6) !important;
}
#chatbotModal .modal-header {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06) !important;
    padding: 20px 24px !important;
}
#chatbotModal .modal-header h2 {
    color: #e2e8f0 !important;
    font-size: 16px !important;
    font-weight: 700;
    display: flex; align-items: center; gap: 10px;
    margin: 0;
}
#chatbotModal .modal-header h2::before {
    content: "";
    display: inline-block;
    width: 4px; height: 20px;
    background: linear-gradient(180deg, #a78bfa, #63b3ed);
    border-radius: 4px;
}
#chatbotModal .btn-close {
    filter: invert(1) opacity(0.4) !important;
    transition: opacity 0.2s ease !important;
}
#chatbotModal .btn-close:hover { opacity: 0.8 !important; filter: invert(1) opacity(0.8) !important; }
#chatbotModal .modal-body {
    padding: 24px !important;
    background: #161b22;
}
#chatbotModal .modal-body label {
    color: rgba(148,163,184,0.8) !important;
    font-size: 11px !important;
    font-weight: 700 !important;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    margin-bottom: 8px !important;
    display: block;
}
#chatbotModal .modal-body .form-control,
#chatbotModal .modal-body .form-select {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
    border-radius: 10px !important;
    color: #e2e8f0 !important;
    font-size: 13px !important;
    padding: 10px 14px !important;
    transition: all 0.2s ease !important;
}
#chatbotModal .modal-body .form-control::placeholder { color: rgba(148,163,184,0.3) !important; }
#chatbotModal .modal-body .form-control:focus,
#chatbotModal .modal-body .form-select:focus {
    border-color: rgba(139,92,246,0.4) !important;
    box-shadow: 0 0 0 3px rgba(139,92,246,0.08) !important;
    background: rgba(139,92,246,0.03) !important;
    outline: none !important;
}
#chatbotModal .modal-body .form-select option { background: #1e293b; color: #e2e8f0; }
#chatbotModal .modal-body .form-text {
    color: rgba(148,163,184,0.4) !important;
    font-size: 11px !important;
}
.status-radio-group {
    display: flex;
    gap: 12px;
}
.status-radio-item {
    flex: 1;
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 10px;
    padding: 10px 14px;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 8px;
}
.status-radio-item input { display: none; }
.status-radio-item.selected-active {
    background: rgba(52,211,153,0.08);
    border-color: rgba(52,211,153,0.3);
}
.status-radio-item.selected-inactive {
    background: rgba(248,113,113,0.08);
    border-color: rgba(248,113,113,0.3);
}
.status-radio-item span {
    font-size: 13px;
    font-weight: 600;
    color: rgba(148,163,184,0.7);
}
.status-radio-item.selected-active span { color: #34d399; }
.status-radio-item.selected-inactive span { color: #f87171; }
#chatbotModal .modal-footer {
    background: rgba(255,255,255,0.02);
    border-top: 1px solid rgba(255,255,255,0.06) !important;
    padding: 16px 24px !important;
    gap: 10px;
}
#chatbotModal .btn-light {
    background: rgba(255,255,255,0.06) !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
    color: rgba(148,163,184,0.8) !important;
    border-radius: 10px !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 9px 18px !important;
    transition: all 0.2s ease !important;
}
#chatbotModal .btn-light:hover {
    background: rgba(255,255,255,0.1) !important;
    color: #e2e8f0 !important;
}
#chatbotModal .btn-primary {
    background: linear-gradient(135deg, #6d28d9, #a78bfa) !important;
    border: none !important;
    border-radius: 10px !important;
    color: #fff !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 9px 20px !important;
    box-shadow: 0 4px 12px rgba(139,92,246,0.25) !important;
    transition: all 0.2s ease !important;
    display: flex; align-items: center; gap: 8px;
}
#chatbotModal .btn-primary:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(139,92,246,0.35) !important;
}
</style>

<!-- PAGE HEADER -->
<div class="mac-page-header d-flex align-items-center justify-content-between flex-wrap gap-3">
    <div>
        <h1>
            <span class="icon-wrap"><i class="fa-solid fa-robot"></i></span>
            Gerenciar Chatbots
        </h1>
        <p>Gerencie todos os seus chatbots e associe-os aos DNS configurados.</p>
    </div>
    <div class="mac-stat-pill">
        <i class="fa-solid fa-circle-dot"></i>
        <span>' . $total . '</span> chatbot' . ($total !== 1 ? 's' : '') . '
    </div>
</div>

<!-- TOOLBAR -->
<div class="bot-toolbar">
    <div class="mac-search-wrap">
        <i class="fa-solid fa-magnifying-glass"></i>
        <input type="text" id="search_bots" placeholder="Pesquisar chatbot..." />
    </div>
    <button class="btn-add-mac" id="addChatbotBtn">
        <i class="fa-solid fa-plus"></i> Adicionar
    </button>
</div>

<!-- GRID -->
<div class="row" id="chatbotsGrid">
    ' . $cards_html . '
</div>

<!-- MODAL -->
<div class="modal fade" id="chatbotModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-550px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">Adicionar Chatbot</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="chatbotForm">
                    <input type="hidden" id="bot_id" name="bot_id">

                    <div class="mb-4">
                        <label>Nome do Chatbot</label>
                        <input type="text" class="form-control" id="bot_name" name="bot_name"
                               placeholder="Ex: Suporte Principal" required>
                    </div>

                    <div class="mb-4">
                        <label>URL do Chatbot</label>
                        <input type="url" class="form-control" id="bot_url" name="bot_url"
                               placeholder="https://exemplo.com/chatbot" required>
                        <div class="form-text mt-1">Insira a URL completa do chatbot</div>
                    </div>

                    <div class="mb-4">
                        <label>DNS Associado</label>
                        <select class="form-select" id="bot_dns" name="bot_dns" required>
                            <option value="">Selecione um DNS...</option>
                            ' . $dns_options_html . '
                        </select>
                    </div>

                    <div class="mb-2">
                        <label>Status</label>
                        <div class="status-radio-group">
                            <label class="status-radio-item selected-active" id="label_active">
                                <input type="radio" name="status" value="Ativo" id="statusActive" checked>
                                <i class="fa-solid fa-circle-check" style="color:#34d399;font-size:15px;"></i>
                                <span>Ativo</span>
                            </label>
                            <label class="status-radio-item" id="label_inactive">
                                <input type="radio" name="status" value="Inativo" id="statusInactive">
                                <i class="fa-solid fa-circle-xmark" style="color:#f87171;font-size:15px;"></i>
                                <span>Inativo</span>
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-light btn" data-bs-dismiss="modal">
                    <i class="fa-solid fa-xmark me-1"></i>Cancelar
                </button>
                <button type="button" class="btn-primary btn" id="saveBotBtn">
                    <i class="fa-solid fa-floppy-disk"></i>Guardar
                </button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        Swal.fire({
            icon: "success",
            title: "Copiado!",
            text: "URL copiada para a área de transferência",
            timer: 1500,
            showConfirmButton: false
        });
    });
}

// ── Pesquisa nos cards ─────────────────────────────────────────────────────
document.getElementById("search_bots").addEventListener("input", function () {
    const q = this.value.toLowerCase();
    document.querySelectorAll("#chatbotsGrid .col-xl-4, #chatbotsGrid .col-12").forEach(col => {
        const text = col.textContent.toLowerCase();
        col.style.display = text.includes(q) ? "" : "none";
    });
});

// ── Status radio styling ───────────────────────────────────────────────────
document.querySelectorAll("input[name='status']").forEach(radio => {
    radio.addEventListener("change", function () {
        document.getElementById("label_active").classList.remove("selected-active");
        document.getElementById("label_inactive").classList.remove("selected-inactive");
        if (this.value === "Ativo") {
            document.getElementById("label_active").classList.add("selected-active");
        } else {
            document.getElementById("label_inactive").classList.add("selected-inactive");
        }
    });
});

// ── Modal helpers ──────────────────────────────────────────────────────────
let currentAction = "add";
const chatbotModal = new bootstrap.Modal(document.getElementById("chatbotModal"));

function resetModal() {
    document.getElementById("chatbotForm").reset();
    document.getElementById("bot_id").value = "";
    document.getElementById("label_active").classList.add("selected-active");
    document.getElementById("label_inactive").classList.remove("selected-inactive");
}

// Abrir modal de adição
document.getElementById("addChatbotBtn").addEventListener("click", function () {
    currentAction = "add";
    document.getElementById("modalTitle").textContent = "Adicionar Chatbot";
    resetModal();
    chatbotModal.show();
});

// Editar
document.addEventListener("click", function (e) {
    const btn = e.target.closest(".editBtn");
    if (!btn) return;
    currentAction = "edit";
    document.getElementById("modalTitle").textContent = "Editar Chatbot";
    document.getElementById("bot_id").value   = btn.dataset.id;
    document.getElementById("bot_name").value = btn.dataset.name;
    document.getElementById("bot_url").value  = btn.dataset.url;
    document.getElementById("bot_dns").value  = btn.dataset.dns;

    const isAtivo = btn.dataset.status === "Ativo";
    document.getElementById("statusActive").checked   = isAtivo;
    document.getElementById("statusInactive").checked = !isAtivo;
    document.getElementById("label_active").classList.toggle("selected-active", isAtivo);
    document.getElementById("label_inactive").classList.toggle("selected-inactive", !isAtivo);

    chatbotModal.show();
});

// Toggle status
document.addEventListener("click", function (e) {
    const btn = e.target.closest(".toggleBtn");
    if (!btn) return;
    const id            = btn.dataset.id;
    const currentStatus = btn.dataset.currentStatus;
    const newStatus     = currentStatus == 1 ? 0 : 1;

    Swal.fire({
        title: "Alterar Status",
        text: "Deseja " + (newStatus == 1 ? "ativar" : "desativar") + " este chatbot?",
        icon: "question",
        showCancelButton: true,
        confirmButtonText: "Sim, alterar",
        cancelButtonText: "Cancelar"
    }).then(result => {
        if (!result.isConfirmed) return;
        fetch(window.location.href, {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: "action=toggle_status&id=" + encodeURIComponent(id)
        })
        .then(r => r.json())
        .then(data => {
            if (data.status === "success") {
                Swal.fire({ icon: "success", title: "Alterado!", text: data.message, timer: 1500, showConfirmButton: false })
                    .then(() => location.reload());
            } else {
                Swal.fire("Erro", data.message, "error");
            }
        });
    });
});

// Guardar (add / edit)
document.getElementById("saveBotBtn").addEventListener("click", function () {
    const bot_name = document.getElementById("bot_name").value.trim();
    const bot_url  = document.getElementById("bot_url").value.trim();
    const bot_dns  = document.getElementById("bot_dns").value;
    const status   = document.querySelector("input[name='status']:checked").value;
    const id       = document.getElementById("bot_id").value;

    if (!bot_name || !bot_url || !bot_dns) {
        Swal.fire("Erro", "Preencha todos os campos!", "error");
        return;
    }

    let body = "action=" + encodeURIComponent(currentAction)
        + "&bot_name=" + encodeURIComponent(bot_name)
        + "&bot_url="  + encodeURIComponent(bot_url)
        + "&bot_dns="  + encodeURIComponent(bot_dns)
        + "&status="   + encodeURIComponent(status);

    if (currentAction === "edit") body += "&id=" + encodeURIComponent(id);

    fetch(window.location.href, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === "success") {
            Swal.fire({ icon: "success", title: "Sucesso!", text: data.message, timer: 1500, showConfirmButton: false })
                .then(() => { chatbotModal.hide(); location.reload(); });
        } else {
            Swal.fire("Erro", data.message, "error");
        }
    });
});
</script>