<?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 = "Usuários Ativos";

$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(52,211,153,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(52,211,153,0.12);
    border: 1px solid rgba(52,211,153,0.22);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    color: #34d399;
    flex-shrink: 0;
}
.mac-page-header p {
    color: rgba(148,163,184,0.7);
    font-size: 13px;
    margin: 0;
}
.mac-stat-pill {
    background: rgba(52,211,153,0.08);
    border: 1px solid rgba(52,211,153,0.15);
    border-radius: 50px;
    padding: 6px 14px;
    color: #34d399;
    font-size: 12px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 6px;
    flex-shrink: 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(52,211,153,0.4) !important;
    background: rgba(52,211,153,0.04) !important;
    box-shadow: 0 0 0 3px rgba(52,211,153,0.08) !important;
    outline: none !important;
}
.btn-add-mac {
    background: linear-gradient(135deg, #059669, #34d399) !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(52,211,153,0.25) !important;
    cursor: pointer;
}
.btn-add-mac:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(52,211,153,0.35) !important;
}

/* ═══════════════════════════
   TABLE
═══════════════════════════ */
.mac-card .card-body { padding: 0 !important; }
#playlist_table { width: 100% !important; border-collapse: collapse !important; }
#playlist_table thead tr {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06);
}
#playlist_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;
}
#playlist_table tbody tr {
    border-bottom: 1px solid rgba(255,255,255,0.04) !important;
    transition: background 0.15s ease;
}
#playlist_table tbody tr:last-child { border-bottom: none !important; }
#playlist_table tbody tr:hover { background: rgba(52,211,153,0.03) !important; }
#playlist_table tbody td {
    color: rgba(203,213,225,0.85) !important;
    font-size: 13px !important;
    padding: 12px 20px !important;
    vertical-align: middle !important;
}

/* Badges / cells */
.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-dns {
    background: rgba(139,92,246,0.08);
    border: 1px solid rgba(139,92,246,0.15);
    border-radius: 6px;
    padding: 3px 10px;
    font-size: 11px;
    font-weight: 700;
    color: #a78bfa !important;
    display: inline-block;
}
.td-mac {
    font-family: monospace;
    font-size: 12px !important;
    color: #34d399 !important;
    letter-spacing: 0.04em;
}
.td-pin {
    background: rgba(251,191,36,0.08);
    border: 1px solid rgba(251,191,36,0.15);
    border-radius: 6px;
    padding: 3px 10px;
    font-size: 12px;
    font-weight: 700;
    color: #fbbf24 !important;
    display: inline-block;
    font-family: monospace;
}
.td-pass {
    color: rgba(148,163,184,0.4) !important;
    font-family: monospace;
    font-size: 12px !important;
    letter-spacing: 0.1em;
}

/* Action buttons — icon only */
.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;
}
.btn-delete-mac {
    background: rgba(248,113,113,0.1) !important;
    border: 1px solid rgba(248,113,113,0.2) !important;
    color: #f87171 !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-delete-mac: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;
}

/* 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(52,211,153,0.1) !important;
    border-color: rgba(52,211,153,0.3) !important;
    color: #34d399 !important;
}
.dataTables_wrapper .dataTables_paginate .paginate_button.current {
    background: linear-gradient(135deg, rgba(52,211,153,0.2), rgba(99,179,237,0.15)) !important;
    border-color: rgba(52,211,153,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
═══════════════════════════ */
#playlist_modal .modal-content {
    background: #161b22 !important;
    border: 1px solid rgba(52,211,153,0.12) !important;
    border-radius: 16px !important;
    box-shadow: 0 24px 64px rgba(0,0,0,0.6) !important;
}
#playlist_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;
}
#playlist_modal .modal-header h2 {
    color: #e2e8f0 !important;
    font-size: 16px !important;
    font-weight: 700;
    display: flex; align-items: center; gap: 10px;
}
#playlist_modal .modal-header h2::before {
    content: "";
    display: inline-block;
    width: 4px; height: 20px;
    background: linear-gradient(180deg, #34d399, #63b3ed);
    border-radius: 4px;
}
#playlist_modal .btn-close {
    filter: invert(1) opacity(0.4) !important;
    transition: opacity 0.2s ease !important;
}
#playlist_modal .btn-close:hover { opacity: 0.8 !important; }
#playlist_modal .modal-body {
    padding: 24px !important;
    background: #161b22;
}
#playlist_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;
}
#playlist_modal .modal-body .form-control,
#playlist_modal .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;
}
#playlist_modal .modal-body .form-control::placeholder { color: rgba(148,163,184,0.3) !important; }
#playlist_modal .modal-body .form-control:focus,
#playlist_modal .modal-body .form-select:focus {
    border-color: rgba(52,211,153,0.4) !important;
    box-shadow: 0 0 0 3px rgba(52,211,153,0.08) !important;
    background: rgba(52,211,153,0.03) !important;
    outline: none !important;
}
#playlist_modal .modal-body .form-select option { background: #1e293b; color: #e2e8f0; }
#playlist_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;
}
#playlist_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;
}
#playlist_modal .btn-light:hover {
    background: rgba(255,255,255,0.1) !important;
    color: #e2e8f0 !important;
}
#playlist_modal .btn-primary {
    background: linear-gradient(135deg, #059669, #34d399) !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(52,211,153,0.25) !important;
    transition: all 0.2s ease !important;
    display: flex; align-items: center; gap: 8px;
}
#playlist_modal .btn-primary:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(52,211,153,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-users"></i></span>
            Usuários Ativos
        </h1>
        <p>Gerencie as playlists e endereços MAC dos usuários conectados.</p>
    </div>
    <div class="mac-stat-pill" id="mac-count-pill">
        <i class="fa-solid fa-circle-dot"></i>
        <span id="mac-total">—</span> usuários
    </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_playlist" placeholder="Pesquisar usuário..." />
        </div>
        <button class="btn-add-mac" onclick="openAddModal()">
            <i class="fa-solid fa-plus"></i> Adicionar
        </button>
    </div>
    <div class="card-body">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="playlist_table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>DNS</th>
                    <th>MAC Address</th>
                    <th>Usuário</th>
                    <th>Senha</th>
                    <th>PIN</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody id="playlist_table_body"></tbody>
        </table>
    </div>
</div>

<!-- MODAL -->
<div class="modal fade" id="playlist_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">Adicionar Usuário</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="playlist_id">
                <div class="mb-5">
                    <label>DNS</label>
                    <select class="form-select" id="dns_id" required>
                        <option value="">Selecione um DNS...</option>
                    </select>
                </div>
                <div class="mb-5">
                    <label>Endereço MAC</label>
                    <input type="text" class="form-control" id="mac_address" placeholder="Ex: AA:BB:CC:DD:EE:FF" required>
                </div>
                <div class="mb-5">
                    <label>Usuário</label>
                    <input type="text" class="form-control" id="username" placeholder="Nome de usuário" required>
                </div>
                <div class="mb-5">
                    <label>Senha</label>
                    <input type="password" class="form-control" id="password" placeholder="Senha" required>
                </div>
                <div class="mb-2">
                    <label>PIN</label>
                    <input type="text" class="form-control" id="pin" placeholder="PIN numérico" required>
                </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="savePlaylist()">
                    <i class="fa-solid fa-floppy-disk"></i>Guardar
                </button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php'; ?>

<script>
let playlistTable;

function loadPlaylistTable() {
    fetch("actions/mac_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("playlist_table_body");
            tableBody.innerHTML = "";

            const total = data.data.length;
            const el = document.getElementById("mac-total");
            if (el) el.textContent = total;

            data.data.forEach((record) => {
                const maskedPass = "•".repeat(Math.min(record.password.length, 8));
                tableBody.innerHTML += `
                    <tr id="row_${record.id}">
                        <td><span class="td-id">#${record.id}</span></td>
                        <td><span class="td-dns">DNS ${record.dns_id}</span></td>
                        <td><span class="td-mac">${record.mac_address}</span></td>
                        <td style="color:#e2e8f0;font-weight:600;">${record.username}</td>
                        <td><span class="td-pass">${maskedPass}</span></td>
                        <td><span class="td-pin">${record.pin}</span></td>
                        <td style="display:flex;gap:8px;align-items:center;">
                            <button class="btn-edit-mac" title="Editar"
                                onclick="editPlaylist(${record.id}, ${record.dns_id}, '${record.mac_address}', '${record.username}', '${record.password}', '${record.pin}')">
                                <i class="fa-solid fa-pen-to-square"></i>
                            </button>
                            <button class="btn-delete-mac" title="Apagar" onclick="deletePlaylist(${record.id})">
                                <i class="fa-solid fa-trash"></i>
                            </button>
                        </td>
                    </tr>`;
            });

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

            playlistTable = $('#playlist_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: "Nenhum usuário cadastrado"
                }
            });

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

function loadDnsOptions(selectedValue = "") {
    fetch("actions/mac_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "get_dns_options" }),
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            const dnsDropdown = document.getElementById("dns_id");
            dnsDropdown.innerHTML = '<option value="">Selecione um DNS...</option>';
            data.data.forEach((dns) => {
                const selected = dns.id == selectedValue ? "selected" : "";
                dnsDropdown.innerHTML += `<option value="${dns.id}" ${selected}>${dns.title}</option>`;
            });
        }
    })
    .catch(err => console.error("Erro ao carregar DNS:", err));
}

function openAddModal() {
    document.getElementById("modal_title").textContent = "Adicionar Usuário";
    document.getElementById("playlist_id").value = "";
    document.getElementById("dns_id").value = "";
    document.getElementById("mac_address").value = "";
    document.getElementById("username").value = "";
    document.getElementById("password").value = "";
    document.getElementById("pin").value = "";
    loadDnsOptions();
    new bootstrap.Modal(document.getElementById("playlist_modal")).show();
}

function editPlaylist(id, dns_id, mac_address, username, password, pin) {
    document.getElementById("modal_title").textContent = "Editar Usuário";
    document.getElementById("playlist_id").value = id;
    document.getElementById("mac_address").value = mac_address;
    document.getElementById("username").value = username;
    document.getElementById("password").value = password;
    document.getElementById("pin").value = pin;
    loadDnsOptions(dns_id);
    new bootstrap.Modal(document.getElementById("playlist_modal")).show();
}

function savePlaylist() {
    const id          = document.getElementById("playlist_id").value;
    const dns_id      = document.getElementById("dns_id").value.trim();
    const mac_address = document.getElementById("mac_address").value.trim();
    const username    = document.getElementById("username").value.trim();
    const password    = document.getElementById("password").value.trim();
    const pin         = document.getElementById("pin").value.trim();
    const action      = id ? "edit" : "add";

    if (!dns_id || !mac_address || !username || !password || !pin) {
        Swal.fire("Erro", "Preencha todos os campos!", "error");
        return;
    }
    if (!validateMACAddress(mac_address)) {
        Swal.fire("Erro", "Endereço MAC inválido!", "error");
        return;
    }

    fetch("actions/mac_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action, id, dns_id, mac_address, username, password, pin }),
    })
    .then(res => res.json())
    .then(data => {
        Swal.fire(data.success ? "Sucesso" : "Erro", data.message, data.success ? "success" : "error");
        bootstrap.Modal.getInstance(document.getElementById("playlist_modal")).hide();
        if (data.success) loadPlaylistTable();
    })
    .catch(err => console.error("Erro ao guardar:", err));
}

function deletePlaylist(id) {
    Swal.fire({
        title: "Tem a certeza?",
        text: "Este utilizador será removido permanentemente.",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, apagar!",
        cancelButtonText: "Cancelar"
    }).then((result) => {
        if (result.isConfirmed) {
            fetch("actions/mac_actions.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ action: "delete", id }),
            })
            .then(res => res.json())
            .then(data => {
                Swal.fire("Apagado!", data.message, "success");
                if (playlistTable) playlistTable.row(`#row_${id}`).remove().draw(false);
                const el = document.getElementById("mac-total");
                if (el) el.textContent = parseInt(el.textContent) - 1;
            })
            .catch(err => console.error("Erro ao apagar:", err));
        }
    });
}

function validateMACAddress(mac) {
    return /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/.test(mac);
}

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