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

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

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

$error = ''; // Inisialisasi pembolehubah
$success = '';

// Dapatkan data jabatan untuk dropdown
$jabatan_query = "SELECT ID, NamaJbtn, KodJbtn FROM jabatan";
$jabatan_result = $conn->query($jabatan_query);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!empty($_POST['IDJbtn']) && !empty($_POST['NamaBhgn']) && !empty($_POST['KodBhgn']) && !empty($_POST['Keterangan'])) {
        $IDJbtn = $_POST['IDJbtn'];
        $NamaBhgn = $_POST['NamaBhgn'];
        $KodBhgn = $_POST['KodBhgn'];
        $Keterangan = $_POST['Keterangan'];

        // Semak jika NamaBhgn atau Keterangan sudah wujud
        $stmt_check = $conn->prepare("SELECT * FROM bahagian WHERE NamaBhgn = ? OR Keterangan = ?");
        $stmt_check->bind_param("ss", $NamaBhgn, $Keterangan);
        $stmt_check->execute();
        $result = $stmt_check->get_result();

        if ($result->num_rows > 0) {
            $error = "Bahagian dengan Nama atau Keterangan ini sudah wujud!";
        } else {
            // Jika tiada pendua, masukkan data baru
            $stmt = $conn->prepare("INSERT INTO bahagian (IDJbtn, NamaBhgn, KodBhgn, Keterangan, CrtBy, MdfBy) VALUES (?, ?, ?, ?, ?, ?)");
            if ($stmt === false) {
                $error = "Ralat MySQL: " . $conn->error;
            } else {
                $stmt->bind_param("isssss", $IDJbtn, $NamaBhgn, $KodBhgn, $Keterangan, $user_id, $user_id);
                if ($stmt->execute()) {
                    $success = "Bahagian berjaya ditambah!";
                } else {
                    $error = "Ralat: " . $stmt->error;
                }
            }
            $stmt->close();
        }
        $stmt_check->close();
    } else {
        $error = "Sila lengkapkan semua medan.";
    }
}
?>

<!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 Bahagian</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 Bahagian </li>
                            </ol>
                            <?php if (!empty($error)) : ?>
                                <div class="alert alert-danger text-center"><?php echo $error; ?></div>
                            <?php elseif (!empty($success)) : ?>
                                <div class="alert alert-success text-center"><?php echo $success; ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                     <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                <h4 class="card-title">Tambah Bahagian Baru</h4>
                                <form method="post">
            <div class="form-group">
                <label for="IDJbtn">Jabatan:</label>
                <select class="form-control" name="IDJbtn" id="IDJbtn" 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']; ?> (<?php echo $row['KodJbtn']; ?>)</option><?php } ?>
                </select>
            </div>
            <div class="form-group">
                <label for="KodBhgn">Kod Bahagian:</label>
                <input type="number" class="form-control" name="KodBhgn" id="KodBhgn" required oninput="this.value = this.value.toUpperCase();">
            </div>

            <div class="form-group">
                <label for="NamaBhgn">Nama Bahagian:</label>
                <input type="text" class="form-control" name="NamaBhgn" id="NamaBhgn" required oninput="this.value = this.value.toUpperCase();">
            </div>
            
            <div class="form-group">
                <label for="Keterangan">Keterangan:</label>
                <input type="text" class="form-control" name="Keterangan" id="Keterangan" required>
            </div>
            <button type="submit" class="btn btn-primary btn-block">Tambah Bahagian</button>
        </form>
                                </div>
                            </div>
                        </div>
                 </div>

                </div>
        </div>
       
        <!-- footer -->
        <!-- ============================================================== -->
        <?php
include('footer.php');
?>
        <!-- ============================================================== -->
        <!-- End footer -->
        <!-- ============================================================== -->
    </div>
    
    <!-- All Jquery -->
    <!-- ============================================================== -->
     <?php
include('jquery.php');
?>
</body>
</html>