<?php
require_once __DIR__ . '/../auth/protect_admin.php';
require_once __DIR__ . '/../includes/header_admin.php';
require_once __DIR__ . '/../config/db.php';
?>

<div class="container mt-4">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3>Manajemen Users</h3>

        <!-- Tombol membuka modal tambah user -->
        <button class="btn btn-primary" id="btnAddUser">
            <i class="bi bi-plus-lg"></i> Tambah User
        </button>
    </div>

    <!-- NOTIFIKASI -->
    <?php if (isset($_GET['success'])): ?>
        <script>
        Swal.fire("Berhasil!", "User berhasil ditambahkan!", "success");
        </script>
    <?php endif; ?>

    <?php if (isset($_GET['edit'])): ?>
        <script>
        Swal.fire("Update Berhasil!", "User telah diperbarui!", "success");
        </script>
    <?php endif; ?>

    <?php if (isset($_GET['delete'])): ?>
        <script>
        Swal.fire("Deleted!", "User berhasil dihapus!", "success");
        </script>
    <?php endif; ?>

    <div class="card shadow-sm">
        <div class="card-body">

            <table class="table table-bordered table-striped">
                <thead class="table-dark">
                    <tr>
                        <th width="50">#</th>
                        <th>Username</th>
                        <th>Nama</th>
                        <th>Role</th>
                        <th>Dibuat</th>
                        <th width="120">Aksi</th>
                    </tr>
                </thead>

                <tbody>
                <?php
                $stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC");
                $no = 1;

                while ($row = $stmt->fetch()):
                ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= htmlspecialchars($row['username']) ?></td>
                        <td><?= htmlspecialchars($row['nama']) ?></td>
                        <?php
                        $role = $row['role'];

                        $badgeClass = match($role) {
                            'superadmin' => 'bg-primary',            // biru
                            'operator'   => 'bg-warning text-dark',  // kuning
                            'guru'       => 'bg-success',            // hijau
                            default      => 'bg-secondary'
                        };
                        ?>
                        <td>
                            <span class="badge <?= $badgeClass ?>">
                                <?= ucfirst($role) ?>
                            </span>
                        </td>

                        <td><?= $row['created_at'] ?></td>

                        <td class="text-center">

                            <!-- EDIT BUTTON -->
                            <button class="btn btn-warning btn-sm"
                                onclick="openEditModal(
                                    '<?= $row['id'] ?>',
                                    '<?= htmlspecialchars($row['nama'], ENT_QUOTES) ?>',
                                    '<?= htmlspecialchars($row['username'], ENT_QUOTES) ?>',
                                    '<?= $row['role'] ?>'
                                )">
                                <i class="bi bi-pencil"></i>
                            </button>

                            <!-- DELETE BUTTON -->
                            <button class="btn btn-danger btn-sm"
                                onclick="deleteUser(<?= $row['id'] ?>)">
                                <i class="bi bi-trash"></i>
                            </button>

                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>

            </table>

        </div>
    </div>
</div>


<!-- =====================================================
   MODAL ADD USER
===================================================== -->
<div class="modal fade" id="modalAddUser" tabindex="-1">
  <div class="modal-dialog">
    <form method="POST" action="/presensi_v1/process/add_user.php" class="modal-content">

        <div class="modal-header">
            <h5 class="modal-title">Tambah User Baru</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <div class="modal-body">

            <div class="mb-3">
                <label class="form-label">Nama Lengkap</label>
                <input type="text" name="nama" class="form-control" required>
            </div>

            <div class="mb-3">
                <label class="form-label">Username</label>
                <input type="text" name="username" class="form-control" required>
            </div>

            <div class="mb-3">
                <label class="form-label">Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>

            <div class="mb-3">
                <label class="form-label">Role</label>
                <select name="role" class="form-select" required>
                    <option value="superadmin">Superadmin</option>
                    <option value="operator">Operator</option>
                    <option value="guru">Guru</option>
                </select>
            </div>

        </div>

        <div class="modal-footer">
            <button type="submit" class="btn btn-success">Simpan User</button>
        </div>

    </form>
  </div>
</div>


<!-- =====================================================
   MODAL EDIT USER
===================================================== -->
<div class="modal fade" id="modalEditUser" tabindex="-1">
  <div class="modal-dialog">
    <form method="POST" action="/presensi_v1/process/edit_user.php" class="modal-content">

        <input type="hidden" name="id" id="edit_id">

        <div class="modal-header">
            <h5 class="modal-title">Edit User</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <div class="modal-body">

            <div class="mb-3">
                <label class="form-label">Nama</label>
                <input type="text" id="edit_nama" name="nama" class="form-control" required>
            </div>

            <div class="mb-3">
                <label class="form-label">Username</label>
                <input type="text" id="edit_username" name="username" class="form-control" required>
            </div>

            <div class="mb-3">
                <label class="form-label">Role</label>
                <select id="edit_role" name="role" class="form-select" required>
                    <option value="superadmin">Superadmin</option>
                    <option value="operator">Operator</option>
                    <option value="guru">Guru</option>
                </select>
            </div>

            <div class="mb-3">
                <label class="form-label">Password Baru (opsional)</label>
                <input type="password" name="password" class="form-control">
                <small class="text-muted">Kosongkan jika tidak ingin mengubah password.</small>
            </div>

        </div>

        <div class="modal-footer">
            <button type="submit" class="btn btn-success">Update User</button>
        </div>

    </form>
  </div>
</div>


<!-- =====================================================
   JAVASCRIPT HANDLER
===================================================== -->
<script>
// OPEN ADD MODAL
document.getElementById("btnAddUser").addEventListener("click", function () {
    let modal = new bootstrap.Modal(document.getElementById('modalAddUser'));
    modal.show();
});

// OPEN EDIT MODAL
function openEditModal(id, nama, username, role) {
    document.getElementById("edit_id").value = id;
    document.getElementById("edit_nama").value = nama;
    document.getElementById("edit_username").value = username;
    document.getElementById("edit_role").value = role;

    let modal = new bootstrap.Modal(document.getElementById('modalEditUser'));
    modal.show();
}

// DELETE USER
function deleteUser(id) {
    Swal.fire({
        title: "Hapus User?",
        text: "Data user akan dihapus permanen!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Ya, Hapus",
        cancelButtonText: "Batal"
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "/presensi_v1/process/delete_user.php?id=" + id;
        }
    });
}
</script>

</div> <!-- END matrix-content -->
</body>
</html>
<?php require_once "../includes/footer.php"; ?>