<?php
include('session_handler.php');

if (!checkRole('superadmin')) {
    header('Location: unauthorized.php');
    exit;
}
// CATCH AJAX PERMINTAAN DROPDOWN BAHAGIAN
if (isset($_GET['ajax']) && $_GET['ajax'] == 'get_bahagian') {
    $id_jabatan = $_GET['id_jabatan'];
    $result = $conn->query("SELECT * FROM bahagian WHERE IDJbtn = '$id_jabatan' ORDER BY Keterangan ASC");

    echo '<option value="">-- Pilih Bahagian --</option>';
    while ($row = $result->fetch_assoc()) {
        echo '<option value="' . $row['ID'] . '">' . $row['Keterangan'] . '</option>';
    }
    exit;
}

// AMBIL ID USER
if (!isset($_GET['id'])) {
    echo "Ralat: ID tidak diberikan.";
    exit;
}

$id = $_GET['id'];

$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 0) {
    echo "Pengguna tidak dijumpai.";
    exit;
}
$user = $result->fetch_assoc();

// DAPATKAN senarai jabatan & bahagian
$jabatanList = $conn->query("SELECT * FROM jabatan ORDER BY NamaJbtn ASC");
$bahagianList = $conn->query("SELECT * FROM bahagian WHERE IDJbtn = '" . $user['jabatan'] . "' ORDER BY Keterangan ASC");

// KEMASKINI
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nombor = $_POST['NomborStaff'];
    $email = $_POST['email'];
    $id_jabatan = $_POST['jabatan'];
    $id_bahagian = $_POST['bahagian'];
    $role = $_POST['role'];

    $update = $conn->prepare("UPDATE users SET NomborStaff=?, email=?, role=?, jabatan=?, bahagian=? WHERE id=?");
    $update->bind_param("sssiii", $nombor, $email, $role, $id_jabatan, $id_bahagian, $id);


    if ($update->execute()) {
        echo "<script>alert('Pengguna berjaya dikemaskini'); window.location='view_user.php';</script>";
        exit;
    } else {
        echo "<script>alert('Ralat semasa mengemaskini pengguna');</script>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<!-- header part -->
<?php include('header.php'); ?>
<!-- end header -->
<body class="skin-blue fixed-layout">
    <div class="preloader">
        <div class="loader">
            <div class="loader__figure"></div>
            <p class="loader__label">SPNR Surat/Memo</p>
        </div>
    </div>

    <div id="main-wrapper">
        <?php include('topbar.php'); ?>
        <?php include('leftsidebar.php'); ?>

        <div class="page-wrapper">
            <div class="container-fluid">
                <div class="row page-titles">
                    <div class="col-md-5 align-self-center">
                        <h4 class="text-themecolor">Edit Pengguna</h4>
                    </div>
                    <div class="col-md-7 align-self-center text-end">
                        <div class="d-flex justify-content-end align-items-center">
                            <ol class="breadcrumb justify-content-end">
                                <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                                <li class="breadcrumb-item"><a href="view_user.php">Senarai Pengguna</a></li>
                                <li class="breadcrumb-item active">Edit Pengguna</li>
                            </ol>
                        </div>
                    </div>
                </div>

                <!-- START HERE -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <form method="post">
                                    <div class="mb-3">
                                        <label>Nama Staff</label>
                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['NamaStaff']); ?>" readonly>
                                    </div>

                                    <div class="mb-3">
                                        <label>Nombor Staff</label>
                                        <input type="text" name="NomborStaff" class="form-control" value="<?php echo htmlspecialchars($user['NomborStaff']); ?>" required>
                                    </div>

                                    <div class="mb-3">
                                        <label>Email</label>
                                        <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                    </div>

                                    <div class="mb-3">
                                    <label>Peranan</label>
                                    <select name="role" class="form-control" required>
                                        <option value="" disabled <?php if (empty($user['role'])) echo 'selected'; ?>>-- Pilih Peranan --</option>
                                        <option value="superadmin" <?php if ($user['role'] == 'superadmin') echo 'selected'; ?>>Superadmin</option>
                                        <option value="admin" <?php if ($user['role'] == 'admin') echo 'selected'; ?>>Admin</option>
                                        <option value="staf" <?php if ($user['role'] == 'staf') echo 'selected'; ?>>Staf</option>
                                    </select>
                                </div>
                                
                                    <div class="mb-3">
                                        <label>Jabatan</label>
                                        <select name="jabatan" id="jabatan" class="form-control" required>
                                            <option value="">-- Pilih Jabatan --</option>
                                            <?php while ($j = $jabatanList->fetch_assoc()): ?>
                                                <option value="<?php echo $j['ID']; ?>" <?php if ($j['ID'] == $user['jabatan']) echo 'selected'; ?>>
                                                    <?php echo $j['NamaJbtn']; ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label>Bahagian</label>
                                        <select name="bahagian" id="bahagian" class="form-control" required>
                                            <option value="">-- Pilih Bahagian --</option>
                                            <?php while ($b = $bahagianList->fetch_assoc()): ?>
                                                <option value="<?php echo $b['ID']; ?>" <?php if ($b['ID'] == $user['bahagian']) echo 'selected'; ?>>
                                                    <?php echo $b['Keterangan']; ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <a href="view_user.php" class="btn btn-warning">Batal</a>
                                    <button type="submit" class="btn btn-success">Simpan</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- END START HERE -->

            </div>
        </div>

        <?php include('footer.php'); ?>
    </div>

    <?php include('jquery.php'); ?>
    <script>
    $('#jabatan').on('change', function () {
        var idJabatan = $(this).val();
        $.ajax({
            url: 'edit_user.php',
            type: 'GET',
            data: { ajax: 'get_bahagian', id_jabatan: idJabatan },
            success: function (data) {
                $('#bahagian').html(data);
            }
        });
    });
    </script>
</body>
</html>