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

$page_content = '
<div class="card">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <h3>Users</h3>
        </div>
        <div class="card-toolbar">
            <button type="button" class="btn btn-primary" onclick="openAddModal()">
                <i class="ki-outline ki-plus fs-2"></i> Add User
            </button>
        </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-125px">ID</th>
                    <th class="min-w-125px">Username</th>
                    <th class="text-end min-w-70px">Actions</th>
                </tr>
            </thead>
            <tbody id="users_table_body"></tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="users_modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-650px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal_title" class="fw-bold">Update User</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-7">
                    <label for="username" class="fs-6 fw-semibold mb-2">Username</label>
                    <input type="text" class="form-control" id="username" placeholder="Enter Username" required>
                </div>
                <div class="mb-7">
                    <label for="password" class="fs-6 fw-semibold mb-2">Password</label>
                    <div class="position-relative">
                        <input type="password" class="form-control" id="password" placeholder="Enter Password" required>
                        <span class="btn btn-sm btn-icon position-absolute translate-middle top-50 end-0 me-n2" onclick="togglePassword()">
                            <i id="pass_icon" class="bi bi-eye-slash fs-2"></i>
                        </span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="btn_save" onclick="saveUser()">Update</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((response) => response.json())
        .then((data) => {
            if (data.success) {
                const tableBody = document.getElementById("users_table_body");
                tableBody.innerHTML = "";

                data.data.forEach((user) => {
                    tableBody.innerHTML += `
                        <tr id="row_${user.id}">
                            <td>${user.id}</td>
                            <td>${user.username}</td>
                            <td class="text-end">
                                <button class="btn btn-icon btn-bg-light btn-active-color-primary btn-sm me-1" onclick="openEditModal(${user.id}, '${user.username}')">
                                    <i class="ki-outline ki-pencil fs-2"></i>
                                </button>
                                <button class="btn btn-icon btn-bg-light btn-active-color-danger btn-sm" onclick="confirmDelete(${user.id})">
                                    <i class="ki-outline ki-trash fs-2"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                });

                if (usersTable) { usersTable.destroy(); }
                usersTable = $("#users_table").DataTable({
                    "info": false,
                    "order": [[0, "desc"]]
                });
            }
        })
        .catch((error) => console.error("Error loading users:", error));
}

// NOVIDADE: Alternar entre modo Adicionar e Editar
function openAddModal() {
    document.getElementById("modal_title").textContent = "Add New User";
    document.getElementById("btn_save").textContent = "Create User";
    document.getElementById("users_id").value = "";
    document.getElementById("username").value = "";
    document.getElementById("password").value = "";
    new bootstrap.Modal(document.getElementById("users_modal")).show();
}

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

// NOVIDADE: Função genérica que decide se vai editar ou adicionar
function saveUser() {
    const id = document.getElementById("users_id").value;
    const action = id ? "edit" : "add"; // Se tem ID edita, se não, adiciona
    const username = document.getElementById("username").value.trim();
    const password = document.getElementById("password").value.trim();

    if (!username || !password) {
        Swal.fire("Error", "Username and Password are required!", "error");
        return;
    }

    fetch("actions/user_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action, id, username, password }),
    })
    .then((response) => response.json())
    .then((data) => {
        if (data.success) {
            Swal.fire("Success", data.message, "success");
            bootstrap.Modal.getInstance(document.getElementById("users_modal")).hide();
            loadUsers(); // Recarrega a tabela para mostrar as mudanças
        } else {
            Swal.fire("Error", data.message, "error");
        }
    });
}

// NOVIDADE: Função de deletar com confirmação
function confirmDelete(id) {
    Swal.fire({
        title: "Are you sure?",
        text: "You won't be able to revert this!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes, delete it!",
        customClass: { confirmButton: "btn btn-danger", cancelButton: "btn btn-light" }
    }).then((result) => {
        if (result.isConfirmed) {
            fetch("actions/user_actions.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ action: "delete", id }),
            })
            .then(res => res.json())
            .then(data => {
                if(data.success) {
                    Swal.fire("Deleted!", data.message, "success");
                    loadUsers();
                } else { Swal.fire("Error", data.message, "error"); }
            });
        }
    });
}

// NOVIDADE: Mostrar/Esconder senha
function togglePassword() {
    const passInput = document.getElementById("password");
    const icon = document.getElementById("pass_icon");
    if (passInput.type === "password") {
        passInput.type = "text";
        icon.classList.replace("bi-eye-slash", "bi-eye");
    } else {
        passInput.type = "password";
        icon.classList.replace("bi-eye", "bi-eye-slash");
    }
}

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