<?php 
include "auth.php";
checkPermission(['admin']); // only admin allowed

include "db.php";

// Handle Add User
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_user'])) {
    $username = $conn->real_escape_string($_POST['username']);
    $password = md5($_POST['password']); 
    $role = $conn->real_escape_string($_POST['role']);
    $conn->query("INSERT INTO users (username,password,role) VALUES ('$username','$password','$role')");
}

// Handle Edit User
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_user'])) {
    $id = intval($_POST['id']);
    $username = $conn->real_escape_string($_POST['username']);
    $role = $conn->real_escape_string($_POST['role']);
    $password = $_POST['password'];

    if (!empty($password)) {
        $password_hashed = md5($password);
        $conn->query("UPDATE users SET username='$username', password='$password_hashed', role='$role' WHERE id=$id");
    } else {
        $conn->query("UPDATE users SET username='$username', role='$role' WHERE id=$id");
    }
}

// Handle Delete User
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $conn->query("DELETE FROM users WHERE id=$id");
    header("Location: users.php?msg=deleted");
    exit;
}

$users = $conn->query("SELECT * FROM users");
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>User Management</title>
  <link rel="stylesheet" href="css/style.css">
  <style>
    .modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; 
             background:rgba(0,0,0,0.6); justify-content:center; align-items:center; }
    .modal-content { background:#fff; padding:20px; border-radius:8px; width:400px; }
    .modal-header { font-size:25px; font-weight: 500; margin-bottom:20px; }
    .close { float:right; cursor:pointer; font-size:30px; }
    button{
        background: r
    }
  </style>
</head>
<body>

<?php include("global/header.php"); ?>

<main class="main">
    <header class="topbar">
            <button class="hamburger" id="hamburger" aria-label="Toggle menu">☰</button>
            <div style="margin-left: 8px; font-weight: 600;">Dashboard <span class="topbar-menu-space"> > </span> Users</div>

            <div class="profile">
                <button class="profile-btn" id="profileBtn" aria-expanded="false">
                    <span>Welcome <?php echo htmlspecialchars($_SESSION['username']); ?></span>
                    <img class="avatar" src="https://i.pravatar.cc/80" alt="Profile" />
                </button>
                <nav class="dropdown" id="profileDropdown">
                    <a href="profile.php">Profile Settings</a>
                    <a href="users.php">Users Settings</a>
                    <a href="logout.php">Logout</a>
                </nav>
            </div>
        </header>
<section class="content">
    <div class="container">
        <h2>👥 User Management</h2>

        <!-- Add User Form -->
        <form method="post" class="filter-box">
            <input type="hidden" name="add_user" value="1">
            <div class="form-group">
                <input type="text" name="username" placeholder="Username" required>
            </div>
            <div class="form-group">
                <input type="password" name="password" placeholder="Password" required>
            </div>
            <div class="form-group">
                <select name="role">
        <option value="admin">Admin</option>
        <option value="manager">Manager</option>
        <option value="staff">Staff</option>
      </select>
            </div>
            <div class="form-group">
                <button type="submit">✚ Add User</button>
            </div>
        </form>

        <!-- Users Table -->
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Username</th>
                    <th>Role</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while($u=$users->fetch_assoc()){ ?>
                <tr>
                    <td>
                        <?= $u['id'] ?>
                    </td>
                    <td>
                        <?= $u['username'] ?>
                    </td>
                    <td>
                        <?= $u['role'] ?>
                    </td>
                    <td>
                        <?= $u['created_at'] ?>
                    </td>
                    <td class="action-btns">
                        <button class="btn" onclick='openEditModal(<?= json_encode($u) ?>)'>Edit</button>
                        <?php if($u['role']!="admin"){ ?>
                        <a class="btn btn-danger" href="users.php?delete=<?= $u['id'] ?>" onclick="return confirm('Delete this user?')">
                  Delete
                </a>
                        <?php } ?>
                    </td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
</section>
</main>

<!-- Edit User Modal -->
<div id="editModal" class="modal">
  <div class="modal-content">
    <span class="close" onclick="closeModal('editModal')">&times;</span>
    <div class="modal-header">Edit User</div>
    <form method="post">
      <input type="hidden" name="edit_user" value="1">
      <input type="hidden" name="id" id="editId">
      
      <label>Username:</label>
      <input type="text" name="username" id="editUsername" required><br><br>

      <label>New Password:</label>
      <input type="password" name="password" id="editPassword" placeholder="New Password"><br><br>

      <label>Role:</label>
      <select name="role" id="editRole">
        <option value="admin">Admin</option>
        <option value="manager">Manager</option>
        <option value="staff">Staff</option>
      </select><br><br>

      <button class="btn submit-btn" type="submit">Update</button>
    </form>
  </div>
</div>

<script>
  function openEditModal(user) {
    document.getElementById('editId').value = user.id;
    document.getElementById('editUsername').value = user.username;
    document.getElementById('editRole').value = user.role;
    document.getElementById('editPassword').value = "";
    document.getElementById('editModal').style.display = 'flex';
  }
  function closeModal(id) {
    document.getElementById(id).style.display = 'none';
  }
  window.onclick = function(e) {
    if (e.target.classList.contains('modal')) {
      e.target.style.display = 'none';
    }
  }
</script>
<script>
            // Sidebar accordion: click ONLY the top-level buttons, not the whole LI.
            const submenuButtons = document.querySelectorAll(".has-submenu > .menu-link");
            submenuButtons.forEach((btn) => {
                btn.addEventListener("click", (e) => {
                    e.preventDefault(); // keep as a toggle, no page jump
                    const currentItem = btn.parentElement; // .has-submenu
                    const isOpen = currentItem.classList.contains("open");

                    // Close other open menus (accordion behavior)
                    document.querySelectorAll(".has-submenu.open").forEach((li) => {
                        if (li !== currentItem) {
                            li.classList.remove("open");
                            const b = li.querySelector(".menu-link");
                            if (b) b.setAttribute("aria-expanded", "false");
                        }
                    });

                    // Toggle current
                    currentItem.classList.toggle("open");
                    btn.setAttribute("aria-expanded", String(!isOpen));
                });
            });

            // Ensure clicks inside submenu DO NOT toggle/close the parent unintentionally
            document.querySelectorAll(".submenu").forEach((ul) => {
                ul.addEventListener("click", (e) => {
                    e.stopPropagation();
                });
            });

            // Mobile: show/hide sidebar
            const sidebar = document.getElementById("sidebar");
            const hamburger = document.getElementById("hamburger");
            hamburger.addEventListener("click", () => {
                sidebar.classList.toggle("active");
            });

            // Close sidebar when clicking outside on small screens
            document.addEventListener("click", (e) => {
                const isClickInside = sidebar.contains(e.target) || hamburger.contains(e.target);
                if (!isClickInside && sidebar.classList.contains("active")) {
                    sidebar.classList.remove("active");
                }
            });

            // Profile dropdown
            const profileBtn = document.getElementById("profileBtn");
            const profileDropdown = document.getElementById("profileDropdown");
            profileBtn.addEventListener("click", (e) => {
                e.stopPropagation();
                const open = profileDropdown.classList.toggle("open");
                profileBtn.setAttribute("aria-expanded", String(open));
            });
            document.addEventListener("click", () => profileDropdown.classList.remove("open"));
        </script>
</body>
</html>
