<?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 = '
<div class="card">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <div class="d-flex align-items-center position-relative my-1">
                <i class="ki-outline ki-magnifier fs-3 position-absolute ms-5"></i>
                <input type="text" id="search_users" class="form-control form-control-solid w-250px ps-12" placeholder="Pesquisar Usuário" />
            </div>
        </div>
    </div>
    <div class="card-body pt-0">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="users_table">
            <thead>
                <tr class="text-start text-gray-500 fw-bold fs-7 text-uppercase gs-0">
                    <th class="min-w-50px">ID</th>
                    <th class="min-w-200px">Usuário / Perfil</th>
                    <th class="text-end min-w-70px">Ações</th>
                </tr>
            </thead>
            <tbody id="users_table_body" class="fw-semibold text-gray-600"></tbody>
        </table>
    </div>
</div>

<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" class="fw-bold">Atualizar Dados</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="fv-row mb-7">
                    <label for="username" class="fs-6 fw-semibold mb-2">Nome de Usuário</label>
                    <input type="text" class="form-control form-control-solid" id="username" placeholder="Seu usuário" required>
                </div>
                
                <div class="fv-row mb-7">
                    <label for="password" class="fs-6 fw-semibold mb-2">Nova Senha</label>
                    <div class="position-relative">
                        <input type="password" class="form-control form-control-solid pe-12" id="password" placeholder="Digite a nova senha" required>
                        <i class="ki-outline ki-eye fs-2 position-absolute top-50 end-0 translate-middle-y me-4" id="toggle_password" style="cursor: pointer; color: #5e6278;"></i>
                    </div>
                    <div class="text-muted fs-7 mt-2">Dica: Use uma senha forte com números e letras.</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" id="btn_update_user" onclick="updateUser()">
                    <span class="indicator-label">Salvar Alterações</span>
                    <span class="indicator-progress">Salvando... <span class="spinner-border spinner-border-sm align-middle ms-2"></span></span>
                </button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
let usersTable;

// Inicialização da Tabela
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.map(user => {
                // Pega a primeira letra do usuário para fazer um avatar bonitinho
                const initial = user.username.charAt(0).toUpperCase();
                
                return `
                    <tr id="row_${user.id}">
                        <td><span class="text-gray-800 fw-bold">#${user.id}</span></td>
                        <td>
                            <div class="d-flex align-items-center">
                                <div class="symbol symbol-circle symbol-40px overflow-hidden me-3">
                                    <div class="symbol-label fs-3 bg-light-primary text-primary fw-bolder">${initial}</div>
                                </div>
                                <div class="d-flex flex-column">
                                    <span class="text-gray-800 fw-bold mb-1 fs-6">${user.username}</span>
                                    <span class="text-muted fw-semibold fs-7">Administrador</span>
                                </div>
                            </div>
                        </td>
                        <td class="text-end">
                            <button class="btn btn-icon btn-bg-light btn-active-color-primary btn-sm" onclick="openEditModal(${user.id}, '${user.username}')" title="Editar Perfil">
                                <i class="ki-outline ki-pencil fs-3"></i>
                            </button>
                        </td>
                    </tr>`;
            }).join('');

            // Recria o DataTable corretamente para não quebrar a paginação/pesquisa
            if ($.fn.DataTable.isDataTable('#users_table')) {
                $('#users_table').DataTable().destroy();
            }

            usersTable = $("#users_table").DataTable({
                info: false,
                order: [[0, 'asc']],
                pageLength: 10,
                language: { search: "" },
                columnDefs: [{ orderable: false, targets: 2 }] // Desativa ordenação na coluna de Ações
            });
        }
    })
    .catch((error) => console.error("Erro ao carregar usuários:", error));
}

// Lógica de Pesquisa
document.getElementById("search_users").addEventListener("input", function() {
    if(usersTable) usersTable.search(this.value).draw();
});

// Revelar/Ocultar Senha no Modal
document.getElementById('toggle_password').addEventListener('click', function() {
    const passInput = document.getElementById('password');
    const type = passInput.getAttribute('type') === 'password' ? 'text' : 'password';
    passInput.setAttribute('type', type);
    this.classList.toggle('ki-eye');
    this.classList.toggle('ki-eye-slash');
});

// Abrir Modal de Edição
function openEditModal(id, username) {
    document.getElementById("users_id").value = id;
    document.getElementById("username").value = username;
    
    const passInput = document.getElementById("password");
    passInput.value = "";
    passInput.setAttribute('type', 'password'); // Reseta para oculto sempre que abrir
    document.getElementById('toggle_password').className = 'ki-outline ki-eye fs-2 position-absolute top-50 end-0 translate-middle-y me-4';

    new bootstrap.Modal(document.getElementById("users_modal")).show();
}

// Salvar Usuário
function updateUser() {
    const btn = document.getElementById("btn_update_user");
    const id = document.getElementById("users_id").value;
    const username = document.getElementById("username").value.trim();
    const password = document.getElementById("password").value.trim();

    if (!username || !password) {
        return toastr.warning("Usuário e Senha são obrigatórios!");
    }

    // Ativa animação de carregamento
    btn.setAttribute('data-kt-indicator', 'on');
    btn.disabled = true;

    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 => {
        // Remove animação
        btn.removeAttribute('data-kt-indicator');
        btn.disabled = false;

        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById("users_modal")).hide();
            toastr.success("Perfil atualizado com sucesso!");
            
            // Recarrega a tabela para aplicar as mudanças visuais (novo nome, novo avatar)
            loadUsers();
        } else {
            Swal.fire("Erro", data.message, "error");
        }
    })
    .catch(() => {
        btn.removeAttribute('data-kt-indicator');
        btn.disabled = false;
        Swal.fire("Erro", "Falha na comunicação com o servidor.", "error");
    });
}

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