<?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 = "Meu Perfil";

$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(167,139,250,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(167,139,250,0.12);
    border: 1px solid rgba(167,139,250,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;
}

/* ═══════════════════════════
   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(167,139,250,0.4) !important;
    background: rgba(167,139,250,0.04) !important;
    box-shadow: 0 0 0 3px rgba(167,139,250,0.08) !important;
    outline: none !important;
}

/* ═══════════════════════════
   TABLE
═══════════════════════════ */
.mac-card .card-body { padding: 0 !important; }
#users_table { width: 100% !important; border-collapse: collapse !important; }
#users_table thead tr {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06);
}
#users_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;
}
#users_table tbody tr {
    border-bottom: 1px solid rgba(255,255,255,0.04) !important;
    transition: background 0.15s ease;
}
#users_table tbody tr:last-child { border-bottom: none !important; }
#users_table tbody tr:hover { background: rgba(167,139,250,0.03) !important; }
#users_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-user {
    display: flex;
    align-items: center;
    gap: 10px;
}
.td-user-avatar {
    width: 30px; height: 30px;
    background: rgba(167,139,250,0.12);
    border: 1px solid rgba(167,139,250,0.2);
    border-radius: 8px;
    display: flex; align-items: center; justify-content: center;
    font-size: 13px;
    color: #a78bfa;
    flex-shrink: 0;
    font-weight: 700;
}
.td-user-name {
    color: #e2e8f0 !important;
    font-weight: 600;
    font-size: 13px;
}
.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(167,139,250,0.1) !important;
    border-color: rgba(167,139,250,0.3) !important;
    color: #a78bfa !important;
}
.dataTables_wrapper .dataTables_paginate .paginate_button.current {
    background: linear-gradient(135deg, rgba(167,139,250,0.2), rgba(99,179,237,0.15)) !important;
    border-color: rgba(167,139,250,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
═══════════════════════════ */
#users_modal .modal-content {
    background: #161b22 !important;
    border: 1px solid rgba(167,139,250,0.12) !important;
    border-radius: 16px !important;
    box-shadow: 0 24px 64px rgba(0,0,0,0.6) !important;
}
#users_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;
}
#users_modal .modal-header h2 {
    color: #e2e8f0 !important;
    font-size: 16px !important;
    font-weight: 700;
    display: flex; align-items: center; gap: 10px;
    margin: 0;
}
#users_modal .modal-header h2::before {
    content: "";
    display: inline-block;
    width: 4px; height: 20px;
    background: linear-gradient(180deg, #a78bfa, #63b3ed);
    border-radius: 4px;
}
#users_modal .btn-close {
    filter: invert(1) opacity(0.4) !important;
}
#users_modal .btn-close:hover { filter: invert(1) opacity(0.8) !important; }
#users_modal .modal-body {
    padding: 24px !important;
    background: #161b22;
}
#users_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;
}
#users_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;
}
#users_modal .modal-body .form-control::placeholder { color: rgba(148,163,184,0.3) !important; }
#users_modal .modal-body .form-control:focus {
    border-color: rgba(167,139,250,0.4) !important;
    box-shadow: 0 0 0 3px rgba(167,139,250,0.08) !important;
    background: rgba(167,139,250,0.03) !important;
    outline: none !important;
}
#users_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;
}
#users_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;
}
#users_modal .btn-light:hover {
    background: rgba(255,255,255,0.1) !important;
    color: #e2e8f0 !important;
}
#users_modal .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(167,139,250,0.25) !important;
    transition: all 0.2s ease !important;
    display: flex; align-items: center; gap: 8px;
}
#users_modal .btn-primary:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(167,139,250,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-circle-user"></i></span>
            Meu Perfil
        </h1>
        <p>Gerencie as credenciais de acesso ao painel.</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_users" placeholder="Pesquisar utilizador..." />
        </div>
    </div>
    <div class="card-body">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="users_table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Utilizador</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody id="users_table_body"></tbody>
        </table>
    </div>
</div>

<!-- MODAL -->
<div class="modal fade" id="users_modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-500px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal_title">Editar Utilizador</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="users_id">
                <div class="mb-5">
                    <label>Utilizador</label>
                    <input type="text" class="form-control" id="username" placeholder="Nome de utilizador" required>
                </div>
                <div class="mb-2">
                    <label>Palavra-passe</label>
                    <input type="password" class="form-control" id="password" placeholder="Nova palavra-passe" 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="updateUser()">
                    <i class="fa-solid fa-floppy-disk"></i>Guardar
                </button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
let usersTable;

function loadUsers() {
    fetch("actions/user_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("users_table_body");
            tableBody.innerHTML = "";

            data.data.forEach(user => {
                const initial = user.username.charAt(0).toUpperCase();
                tableBody.innerHTML += `
                    <tr id="row_${user.id}">
                        <td><span class="td-id">#${user.id}</span></td>
                        <td>
                            <div class="td-user">
                                <div class="td-user-avatar">${initial}</div>
                                <span class="td-user-name">${user.username}</span>
                            </div>
                        </td>
                        <td>
                            <button class="btn-edit-mac" title="Editar"
                                onclick="openEditModal(${user.id}, '${user.username.replace(/'/g, "\\'")}')">
                                <i class="fa-solid fa-pen-to-square"></i>
                            </button>
                        </td>
                    </tr>`;
            });

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

            usersTable = $('#users_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 utilizador cadastrado"
                }
            });

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

function openEditModal(id, username) {
    document.getElementById("modal_title").textContent = "Editar Utilizador";
    document.getElementById("users_id").value  = id;
    document.getElementById("username").value  = username;
    document.getElementById("password").value  = "";
    new bootstrap.Modal(document.getElementById("users_modal")).show();
}

function updateUser() {
    const id       = document.getElementById("users_id").value;
    const username = document.getElementById("username").value.trim();
    const password = document.getElementById("password").value.trim();

    if (!username || !password) {
        Swal.fire("Erro", "Utilizador e palavra-passe são obrigatórios!", "error");
        return;
    }

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

            const initial = username.charAt(0).toUpperCase();
            const row = document.querySelector(`#row_${id}`);
            if (row) {
                row.innerHTML = `
                    <td><span class="td-id">#${id}</span></td>
                    <td>
                        <div class="td-user">
                            <div class="td-user-avatar">${initial}</div>
                            <span class="td-user-name">${username}</span>
                        </div>
                    </td>
                    <td>
                        <button class="btn-edit-mac" title="Editar"
                            onclick="openEditModal(${id}, '${username.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", loadUsers);
</script>