<?php
include('session_handler.php'); // Sudah uruskan sesi

// Pastikan hanya admin boleh akses halaman ini
if (!checkRole('superadmin')) {
    header('Location: unauthorized.php');
    exit;
}

$user_id = $_SESSION['user_id']; // untuk CrtBy dan MdfBy
$error = "";
$success = "";

// Fetch jabatan for dropdown
$jabatan_query = "SELECT ID, NamaJbtn FROM jabatan";
$jabatan_result = $conn->query($jabatan_query);

// Handle AJAX request for fetching bahagian
if (isset($_GET['jabatan_id'])) {
    $jabatan_id = $_GET['jabatan_id'];
    $query = "SELECT ID, Keterangan, KodBhgn FROM bahagian WHERE IDJbtn = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $jabatan_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $bahagian = array();
    while ($row = $result->fetch_assoc()) {
        $bahagian[] = $row;
    }
    header('Content-Type: application/json');
    echo json_encode($bahagian);
    exit(); // Stop further execution for AJAX response
}

// Proses apabila borang dihantar
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $NamaStaff = strtoupper(trim($_POST['NamaStaff']));
    $NomborStaff = trim($_POST['NomborStaff']);
    $role = trim($_POST['role']);
    $jabatan_id = trim($_POST['jabatan']);
    $bahagian_id = trim($_POST['bahagian']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);

    // Validasi input
if (empty($NamaStaff) || empty($NomborStaff) || empty($role) || empty($jabatan_id) || empty($bahagian_id) || empty($email) || empty($password) || empty($confirm_password)) {
    $error = "Semua medan wajib diisi.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = "Alamat email tidak sah.";
} elseif ($password !== $confirm_password) {
    $error = "Kata laluan dan pengesahan kata laluan tidak sepadan.";
} else {
    // Hash kata laluan
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);

    // Semak jika nombor staf, email, atau nama staf sudah wujud
    $stmt_check = $conn->prepare("SELECT NamaStaff, NomborStaff, email FROM users WHERE LOWER(NamaStaff) = LOWER(?) OR NomborStaff = ? OR email = ?");
    $stmt_check->bind_param("sss", $NamaStaff, $NomborStaff, $email);
    $stmt_check->execute();
    $result = $stmt_check->get_result();

    if ($result->num_rows > 0) {
        $existing = $result->fetch_assoc();

        if (strcasecmp($existing['NamaStaff'], $NamaStaff) == 0) {
            $error = "Nama staf ini sudah digunakan.";
        } elseif ($existing['NomborStaff'] == $NomborStaff) {
            $error = "Nombor staf ini sudah digunakan.";
        } elseif (strcasecmp($existing['email'], $email) == 0) {
            $error = "Alamat email ini sudah digunakan.";
        } else {
            $error = "Maklumat pengguna sudah wujud.";
        }
    } else {
            // Ambil NamaJbtn
            $stmt_jabatan = $conn->prepare("SELECT NamaJbtn FROM jabatan WHERE ID = ?");
            $stmt_jabatan->bind_param("i", $jabatan_id);
            $stmt_jabatan->execute();
            $result_jabatan = $stmt_jabatan->get_result();
            $row_jabatan = $result_jabatan->fetch_assoc();
            $NamaJbtn = $row_jabatan['NamaJbtn'];
            $stmt_jabatan->close();

            // Ambil Keterangan
            $stmt_bahagian = $conn->prepare("SELECT Keterangan FROM bahagian WHERE ID = ?");
            $stmt_bahagian->bind_param("i", $bahagian_id);
            $stmt_bahagian->execute();
            $result_bahagian = $stmt_bahagian->get_result();
            $row_bahagian = $result_bahagian->fetch_assoc();
            $Keterangan = $row_bahagian['Keterangan'];
            $stmt_bahagian->close();

            // Masukkan pengguna baharu
           $stmt = $conn->prepare("INSERT INTO users (NamaStaff, NomborStaff, Jabatan, Bahagian, role, email, password, CrtBy, MdfBy)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssiisssss", $NamaStaff, $NomborStaff, $jabatan_id, $bahagian_id, $role, $email, $hashed_password, $user_id, $user_id);

            if ($stmt->execute()) {
                $success = "Pengguna berjaya ditambah.";
            } else {
                $error = "Ralat: " . $stmt->error;
            }
            $stmt->close();
        }
        $stmt_check->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<!-- header part -->
<?php
include('header.php');
?>
<!-- end header -->
<body class="skin-blue fixed-layout">
    <!-- ============================================================== -->
    <!-- Preloader - style you can find in spinners.css -->
    <!-- ============================================================== -->
    <div class="preloader">
        <div class="loader">
            <div class="loader__figure"></div>
            <p class="loader__label">SPNR Surat/Memo</p>
        </div>
    </div>
    <!-- ============================================================== -->
    <!-- Main wrapper - style you can find in pages.scss -->
    <!-- ============================================================== -->
    <div id="main-wrapper">
        <!-- ============================================================== -->
        <!-- Topbar header - style you can find in pages.scss -->
        <!-- ============================================================== -->
       <?php
include('topbar.php');
?>
        <!-- ============================================================== -->
        <!-- End Topbar header -->
        <!-- ============================================================== -->
        <!-- ============================================================== -->
        <!-- Left Sidebar - style you can find in sidebar.scss  -->
        <!-- ============================================================== -->
         <?php
include('leftsidebar.php');
?>
        <!-- ============================================================== -->
        <!-- End Left Sidebar - style you can find in sidebar.scss  -->
        <!-- ============================================================== -->
        <!-- ============================================================== -->
        <!-- Page wrapper  -->
        <!-- ============================================================== -->
        <div class="page-wrapper">
            <!-- ============================================================== -->
            <!-- Container fluid  -->
            <!-- ============================================================== -->
            <div class="container-fluid">
                <!-- ============================================================== -->
                <!-- Bread crumb and right sidebar toggle -->
                <!-- ============================================================== -->
                <div class="row page-titles">
                    <div class="col-md-5 align-self-center">
                        <h4 class="text-themecolor">Tambah 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="javascript:void(0)">Home</a></li>
                                <li class="breadcrumb-item active">Tambah Pengguna</li>
                            </ol>
                            
                        </div>
                    </div>
                </div>
                <?php if (!empty($error)): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>

    <?php if (!empty($success)): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>


                        <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                <h4 class="card-title">Tambah Pengguna Baru</h4>

         <form method="post">

             <div class="form-group">
               <label for="NomborStaff" class="form-label">Nombor Staf:</label>
            <input type="text" name="NomborStaff" id="NomborStaff" class="form-control" required>
        </div>

            <div class="form-group">
<label for="NamaStaff" class="form-label">Nama Pengguna:</label>
            <input type="text" name="NamaStaff" id="NamaStaff" class="form-control" required oninput="this.value = this.value.toUpperCase();">
        </div>

        <div class="form-group">
    <label for="jabatan">Jabatan:</label>
    <select class="form-control" name="jabatan" id="jabatan" required>
        <option value="" disabled selected>Pilih Jabatan</option>
        <?php while ($row = $jabatan_result->fetch_assoc()) { ?>
            <option value="<?php echo $row['ID']; ?>"><?php echo $row['NamaJbtn']; ?></option>
        <?php } ?>
    </select>
</div>

<div class="form-group">
    <label for="bahagian">Bahagian:</label>
    <select class="form-control" name="bahagian" id="bahagian" required>
        <option value="" disabled selected>Pilih Jabatan Dulu</option>
    </select>
</div>

<div class="form-group">
    <label>Peranan:</label>
    <select name="role" class="form-control" required>
        <option value="" disabled selected>Pilih Peranan</option>
        <option value="superadmin">Super Admin</option>
        <option value="admin">Admin</option>
        <option value="staf">Staf</option>
    </select>
</div>

            <div class="form-group">
                <label for="email" class="form-label">Email:</label>
            <input type="email" name="email" id="email" class="form-control" required>
        </div>

             <div class="form-group">
                <label for="password" class="form-label">Kata Laluan:</label>
            <input type="password" name="password" id="password" class="form-control" required>
        </div>

             <div class="form-group">
                 <label for="confirm_password" class="form-label">Sahkan Kata Laluan:</label>
            <input type="password" name="confirm_password" id="confirm_password" class="form-control" required>
        </div>

            <button type="submit" class="btn btn-primary btn-block">Tambah Pengguna</button>
        </form>
                                </div>
                            </div>
                        </div>
                 </div>
                        
                </div>
        </div>
       
        <!-- footer -->
        <!-- ============================================================== -->
        <?php
include('footer.php');
?>
        <!-- ============================================================== -->
        <!-- End footer -->
        <!-- ============================================================== -->
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function() {
    $('#jabatan').change(function() {
        var jabatan_id = $(this).val();
        if (jabatan_id !== "") {
            $.ajax({
                url: '', // url kosong, menuju ke file yang sama.
                type: 'GET',
                data: { jabatan_id: jabatan_id },
                dataType: 'json',
                success: function(response) {
                    $('#bahagian').empty();
                    $('#bahagian').append('<option value="" disabled selected>Pilih Bahagian</option>');
                    $.each(response, function(index, bahagian) {
                        $('#bahagian').append('<option value="' + bahagian.ID + '">' + bahagian.Keterangan + '</option>');
                    });
                },
                error: function() {
                    alert('Ralat semasa mengambil data bahagian!');
                }
            });
        } else {
            $('#bahagian').empty();
            $('#bahagian').append('<option value="" disabled selected>Pilih Bahagian</option>');
        }
    });
});
</script>
    <!-- All Jquery -->
    <!-- ============================================================== -->
     <?php
include('jquery.php');
?>
</body>
</html>