<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = "Mensagem Servidor";

$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(251,191,36,0.08) 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(251,191,36,0.10);
    border: 1px solid rgba(251,191,36,0.22);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    color: #fbbf24;
    flex-shrink: 0;
}
.mac-page-header p {
    color: rgba(148,163,184,0.7);
    font-size: 13px;
    margin: 0;
}

/* ═══════════════════════════
   CARD
═══════════════════════════ */
.mac-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);
}
.mac-card-header {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06);
    padding: 18px 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    flex-wrap: wrap;
}
.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(251,191,36,0.4) !important;
    background: rgba(251,191,36,0.03) !important;
    box-shadow: 0 0 0 3px rgba(251,191,36,0.08) !important;
    outline: none !important;
}

/* ═══════════════════════════
   TABLE
═══════════════════════════ */
.mac-card .card-body { padding: 0 !important; }
#settings_table { width: 100% !important; border-collapse: collapse !important; }
#settings_table thead tr {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06);
}
#settings_table thead th {
    color: rgba(148,163,184,0.6) !important;
    font-size: 11px !important;
    font-weight: 700 !important;
    text-transform: uppercase !important;
    letter-spacing: 0.08em !important;
    padding: 14px 20px !important;
    white-space: nowrap;
}
#settings_table tbody tr {
    border-bottom: 1px solid rgba(255,255,255,0.04) !important;
    transition: background 0.15s ease;
}
#settings_table tbody tr:last-child { border-bottom: none !important; }
#settings_table tbody tr:hover { background: rgba(251,191,36,0.03) !important; }
#settings_table tbody td {
    color: rgba(203,213,225,0.85) !important;
    font-size: 13px !important;
    padding: 12px 20px !important;
    vertical-align: middle !important;
}
.td-id {
    background: rgba(99,179,237,0.08);
    border: 1px solid rgba(99,179,237,0.12);
    border-radius: 6px;
    padding: 3px 10px;
    font-size: 12px;
    font-weight: 700;
    color: #63b3ed !important;
    display: inline-block;
}
.td-title {
    color: #e2e8f0 !important;
    font-weight: 600;
}
.td-content {
    color: rgba(148,163,184,0.7) !important;
    font-size: 12px !important;
    max-width: 340px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.btn-edit-mac {
    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: 14px !important;
    width: 34px; height: 34px;
    padding: 0 !important;
    display: inline-flex; align-items: center; justify-content: center;
    transition: all 0.2s ease !important;
    cursor: pointer;
}
.btn-edit-mac: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;
}

/* DataTables dark */
.dataTables_wrapper .dataTables_length label,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_filter label {
    color: rgba(148,163,184,0.6) !important;
    font-size: 12px !important;
}
.dataTables_wrapper .dataTables_length select,
.dataTables_wrapper .dataTables_filter input {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.08) !important;
    color: #e2e8f0 !important;
    border-radius: 8px !important;
    padding: 4px 10px !important;
    font-size: 12px !important;
}
.dataTables_wrapper .dataTables_paginate .paginate_button {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.08) !important;
    border-radius: 8px !important;
    color: rgba(148,163,184,0.7) !important;
    margin: 0 2px !important;
    font-size: 12px !important;
    transition: all 0.2s ease !important;
}
.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
    background: rgba(251,191,36,0.1) !important;
    border-color: rgba(251,191,36,0.3) !important;
    color: #fbbf24 !important;
}
.dataTables_wrapper .dataTables_paginate .paginate_button.current {
    background: linear-gradient(135deg, rgba(251,191,36,0.2), rgba(99,179,237,0.15)) !important;
    border-color: rgba(251,191,36,0.3) !important;
    color: #e2e8f0 !important;
    font-weight: 700 !important;
}
.dataTables_wrapper { padding: 16px 24px !important; }
.dataTables_wrapper .row:first-child { margin-bottom: 12px; }
.dataTables_wrapper .row:last-child  { margin-top: 12px; }

/* ═══════════════════════════
   MODAL
═══════════════════════════ */
#settings_modal .modal-content {
    background: #161b22 !important;
    border: 1px solid rgba(251,191,36,0.12) !important;
    border-radius: 16px !important;
    box-shadow: 0 24px 64px rgba(0,0,0,0.6) !important;
}
#settings_modal .modal-header {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06) !important;
    padding: 20px 24px !important;
}
#settings_modal .modal-header h2 {
    color: #e2e8f0 !important;
    font-size: 16px !important;
    font-weight: 700;
    display: flex; align-items: center; gap: 10px;
    margin: 0;
}
#settings_modal .modal-header h2::before {
    content: "";
    display: inline-block;
    width: 4px; height: 20px;
    background: linear-gradient(180deg, #fbbf24, #63b3ed);
    border-radius: 4px;
}
#settings_modal .btn-close {
    filter: invert(1) opacity(0.4) !important;
    transition: opacity 0.2s ease !important;
}
#settings_modal .btn-close:hover { filter: invert(1) opacity(0.8) !important; }
#settings_modal .modal-body {
    padding: 24px !important;
    background: #161b22;
}
#settings_modal .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;
}
#settings_modal .modal-body .form-control {
    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;
}
#settings_modal .modal-body textarea.form-control {
    min-height: 120px;
    resize: vertical;
}
#settings_modal .modal-body .form-control::placeholder { color: rgba(148,163,184,0.3) !important; }
#settings_modal .modal-body .form-control:focus {
    border-color: rgba(251,191,36,0.4) !important;
    box-shadow: 0 0 0 3px rgba(251,191,36,0.08) !important;
    background: rgba(251,191,36,0.03) !important;
    outline: none !important;
}
#settings_modal .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;
}
#settings_modal .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;
}
#settings_modal .btn-light:hover {
    background: rgba(255,255,255,0.1) !important;
    color: #e2e8f0 !important;
}
#settings_modal .btn-primary {
    background: linear-gradient(135deg, #b45309, #fbbf24) !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(251,191,36,0.25) !important;
    transition: all 0.2s ease !important;
    display: flex; align-items: center; gap: 8px;
}
#settings_modal .btn-primary:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(251,191,36,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-bullhorn"></i></span>
            Mensagem Servidor
        </h1>
        <p>Edite as mensagens e notificações exibidas no servidor.</p>
    </div>
</div>

<!-- CARD -->
<div class="mac-card">
    <div class="mac-card-header">
        <div class="mac-search-wrap">
            <i class="fa-solid fa-magnifying-glass"></i>
            <input type="text" id="search_settings" placeholder="Pesquisar mensagem..." />
        </div>
    </div>
    <div class="card-body">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="settings_table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Título</th>
                    <th>Conteúdo</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody id="settings_table_body"></tbody>
        </table>
    </div>
</div>

<!-- MODAL -->
<div class="modal fade" id="settings_modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-600px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal_title">Editar Mensagem</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="settings_id">
                <div class="mb-5">
                    <label>Título</label>
                    <input type="text" class="form-control" id="note_title" placeholder="Digite o título" required>
                </div>
                <div class="mb-2">
                    <label>Conteúdo</label>
                    <textarea class="form-control" id="note_content" placeholder="Digite o conteúdo da mensagem" required></textarea>
                </div>
            </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" onclick="updateNote()">
                    <i class="fa-solid fa-floppy-disk"></i>Guardar
                </button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
let settingsTable;

function loadSettings() {
    fetch("actions/note_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "view" }),
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            const tableBody = document.getElementById("settings_table_body");
            tableBody.innerHTML = "";

            data.data.forEach(setting => {
                const preview = setting.note_content.length > 60
                    ? setting.note_content.substring(0, 60) + "…"
                    : setting.note_content;

                tableBody.innerHTML += `
                    <tr id="row_${setting.id}">
                        <td><span class="td-id">#${setting.id}</span></td>
                        <td><span class="td-title">${setting.note_title}</span></td>
                        <td><span class="td-content" title="${setting.note_content}">${preview}</span></td>
                        <td>
                            <button class="btn-edit-mac" title="Editar"
                                onclick="openEditModal(${setting.id}, '${setting.note_title.replace(/'/g,"\\'")}', '${setting.note_content.replace(/'/g,"\\'")}')">
                                <i class="fa-solid fa-pen-to-square"></i>
                            </button>
                        </td>
                    </tr>`;
            });

            if (settingsTable) { settingsTable.destroy(); }

            settingsTable = $('#settings_table').DataTable({
                searching: true,
                paging: true,
                info: true,
                language: {
                    search: "",
                    searchPlaceholder: "Filtrar...",
                    lengthMenu: "Mostrar _MENU_",
                    info: "_START_–_END_ de _TOTAL_",
                    paginate: { previous: "‹", next: "›" },
                    zeroRecords: "Nenhum resultado encontrado",
                    emptyTable: "Nenhuma mensagem cadastrada"
                }
            });

            document.getElementById("search_settings").addEventListener("input", function () {
                if (settingsTable) settingsTable.search(this.value).draw();
            });
        }
    })
    .catch(err => console.error("Erro ao carregar mensagens:", err));
}

function openEditModal(id, title, content) {
    document.getElementById("modal_title").textContent = "Editar Mensagem";
    document.getElementById("settings_id").value   = id;
    document.getElementById("note_title").value    = title;
    document.getElementById("note_content").value  = content;
    new bootstrap.Modal(document.getElementById("settings_modal")).show();
}

function updateNote() {
    const id           = document.getElementById("settings_id").value;
    const note_title   = document.getElementById("note_title").value.trim();
    const note_content = document.getElementById("note_content").value.trim();

    if (!note_title || !note_content) {
        Swal.fire("Erro", "Título e Conteúdo são obrigatórios!", "error");
        return;
    }

    fetch("actions/note_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "edit", id, note_title, note_content }),
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            Swal.fire("Sucesso", data.message, "success");
            bootstrap.Modal.getInstance(document.getElementById("settings_modal")).hide();

            // Atualizar linha sem recarregar
            const preview = note_content.length > 60 ? note_content.substring(0, 60) + "…" : note_content;
            const row = document.querySelector(`#row_${id}`);
            if (row) {
                row.innerHTML = `
                    <td><span class="td-id">#${id}</span></td>
                    <td><span class="td-title">${note_title}</span></td>
                    <td><span class="td-content" title="${note_content}">${preview}</span></td>
                    <td>
                        <button class="btn-edit-mac" title="Editar"
                            onclick="openEditModal(${id}, '${note_title.replace(/'/g,"\\'")}', '${note_content.replace(/'/g,"\\'")}')">
                            <i class="fa-solid fa-pen-to-square"></i>
                        </button>
                    </td>`;
            }
        } else {
            Swal.fire("Erro", data.message, "error");
        }
    })
    .catch(err => {
        console.error("Erro ao atualizar:", err);
        Swal.fire("Erro", "Ocorreu um erro inesperado.", "error");
    });
}

document.addEventListener("DOMContentLoaded", loadSettings);
</script>