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

if (!checkRoles(['superadmin', 'staf', 'admin'])) {
    header('Location: unauthorized.php');
    exit;
}

// Fetch user's Jabatan & Bahagian
$userQuery = mysqli_query($conn, "SELECT u.jabatan, u.bahagian, j.NamaJbtn, b.Keterangan, j.KodJbtn, b.KodBhgn, u.role
                              FROM users u
                              JOIN jabatan j ON u.jabatan = j.ID
                              JOIN bahagian b ON u.bahagian = b.ID
                              WHERE u.ID = '$user_id'");
$userData = mysqli_fetch_assoc($userQuery);

if (!$userData) {
    die("Ralat: Gagal mendapatkan data pengguna.");
}

$jabatan_id   = $userData['jabatan'];
$bahagian_id  = $userData['bahagian'];
$jabatan_nama = $userData['NamaJbtn'];
$bahagian_nama= $userData['Keterangan'];
$kod_jabatan  = $userData['KodJbtn'];
$kod_bahagian = $userData['KodBhgn'];
$user_role    = $userData['role'];

// Untuk superadmin: senarai semua jabatan
$jabatanList = mysqli_query($conn, "SELECT * FROM jabatan ORDER BY NamaJbtn ASC");

// Untuk admin/staf: senarai kategori ikut bahagian
if ($user_role != 'superadmin') {
    $kategoriQuery = mysqli_query($conn, "SELECT ID, IDBhgn, Kategori, Keterangan 
                                          FROM kategori 
                                          WHERE IDBhgn = '$bahagian_id'");
}

// ================= Form submit =================
if (isset($_POST['submit'])) {
    $tarikh        = $_POST['tarikh'] ?? '';
    $tajuk         = $_POST['tajuk'] ?? '';
    $lokasi        = $_POST['lokasi'] ?? '';
    $no_rujukan    = $_POST['no_rujukan'] ?? '';
    $kategori_id   = $_POST['kategori'] ?? null;
    $subkategori_id= ($_POST['subkategori'] ?? 0);

    if ($subkategori_id == 0) {
        $subkategori_id = "NULL"; // simpan NULL kalau tiada
        $bilQuery = mysqli_query($conn, "SELECT MAX(bil_latest) AS latest_bil 
                                         FROM surat 
                                         WHERE IDKategori = '$kategori_id' AND IDSubkategori IS NULL");
    } else {
        $bilQuery = mysqli_query($conn, "SELECT MAX(bil_latest) AS latest_bil 
                                         FROM surat 
                                         WHERE IDSubkategori = '$subkategori_id'");
    }

    $bilRow = mysqli_fetch_assoc($bilQuery);
    $bil_latest = ($bilRow['latest_bil'] ?? 0) + 1;

    // build query
    $jabatan_id = $_POST['jabatan'] ?? $jabatan_id;
$bahagian_id = $_POST['bahagian'] ?? $bahagian_id;

$query = "INSERT INTO surat (IDKategori, IDSubkategori, Tarikh, Tajuk, Lokasi, no_rujukan, bil_latest, jabatan, bahagian, CrtDate, CrtBy)
VALUES ('$kategori_id', " . ($subkategori_id === "NULL" ? "NULL" : "'$subkategori_id'") . ", '$tarikh', '$tajuk', '$lokasi', '$no_rujukan', '$bil_latest', '$jabatan_id', '$bahagian_id', NOW(), '$user_id')";


    if (mysqli_query($conn, $query)) {
        $success = "Data berjaya disimpan!";
    } else {
        $error = "Ralat: " . mysqli_error($conn);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include('header.php'); ?>
<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">Tambah Nombor Rujukan </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 No.Rujukan</li>
            </ol>
        </div>
    </div>
</div>

<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h2 class="text-title mb-4">Tambah Nombor Rujukan Surat/Memo</h2>

<?php if (isset($error)) : ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
<?php elseif (isset($success)) : ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<form method="post" id="formSurat">

    <?php if ($user_role == 'superadmin'): ?>
        <div class="form-group">
            <label for="jabatan">Jabatan:</label>
            <select id="jabatan" name="jabatan" class="form-control" required>
                <option value="" disabled selected>Pilih Jabatan</option>
                <?php while ($j = mysqli_fetch_assoc($jabatanList)) : ?>
                    <option value="<?= $j['ID'] ?>" data-kodjbtn="<?= $j['KodJbtn'] ?>">
                        <?= htmlspecialchars($j['NamaJbtn']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="form-group">
            <label for="bahagian">Bahagian:</label>
            <select id="bahagian" name="bahagian" class="form-control" required>
                <option value="" disabled selected>Pilih Bahagian</option>
            </select>
        </div>
    <?php else: ?>
    <div class="form-group">
        <label for="jabatan">Jabatan:</label>
        <input type="text" class="form-control" value="<?= $jabatan_nama ?>" readonly>
        <input type="hidden" id="jabatan" name="jabatan" value="<?= $jabatan_id ?>">
    </div>

    <div class="form-group">
        <label for="bahagian">Bahagian:</label>
        <select id="bahagian" name="bahagian" class="form-control" required>
            <option value="" disabled selected>Pilih Bahagian</option>
            <?php
            $bahagianList = mysqli_query($conn, "SELECT * FROM bahagian WHERE IDJbtn = '$jabatan_id' ORDER BY ID ASC");
            while ($b = mysqli_fetch_assoc($bahagianList)) :
            ?>
                <option value="<?= $b['ID'] ?>" data-kodbhgn="<?= $b['KodBhgn'] ?>">
                    <?= htmlspecialchars($b['Keterangan']) ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>
<?php endif; ?>

    <div class="form-group">
        <label for="kategori">Kategori:</label>
        <select id="kategori" name="kategori" class="form-control" required>
            <option value="" disabled selected>Pilih Kategori</option>
            <?php if ($user_role != 'superadmin') : ?>
                <?php while ($row = mysqli_fetch_assoc($kategoriQuery)) : ?>
                    <option value="<?= $row['ID'] ?>" data-kategori="<?= htmlspecialchars($row['Kategori']) ?>" data-keterangan="<?= htmlspecialchars($row['Keterangan']) ?>">
                        <?= htmlspecialchars($row['Keterangan']) ?>
                    </option>
                <?php endwhile; ?>
            <?php endif; ?>
        </select>
    </div>

    <div class="form-group">
        <label for="subkategori">Sub-Kategori:</label>
        <select id="subkategori" name="subkategori" class="form-control" required>
            <option value="" disabled selected>Pilih Sub-Kategori</option>
        </select>
    </div>

    <div class="form-group">
        <label for="no_rujukan">Nombor Rujukan:</label>
        <input type="text" id="no_rujukan" name="no_rujukan" class="form-control" readonly>
    </div>

    <div class="form-group">
        <label for="bil_latest">Bilangan Surat/Memo Terkini:</label>
        <input type="number" id="bil_latest" name="bil_latest" value="<?= isset($bil_latest) ? $bil_latest : 1; ?>" class="form-control" readonly>
    </div>

    <div class="form-group">
        <label for="tarikh">Tarikh:</label>
        <input type="text" class="form-control" id="tarikh" name="tarikh" value="<?= date('Y-m-d') ?>" readonly>
    </div>

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

    <div class="form-group">
        <label for="lokasi">Lokasi Surat/Memo:</label>
        <input type="text" id="lokasi" name="lokasi" class="form-control">
    </div>

    <button type="submit" name="submit" class="btn btn-primary btn-block">Simpan</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php include('footer.php'); ?>
<?php include('jquery.php'); ?>
<script>
function loadBahagian(jabatan_id) {
    $.post("ajax_handler.php", { jabatan_id: jabatan_id }, function(data) {
        $('#bahagian').html(data);

        // Reset semua dropdown & field bawahnya
        $('#kategori').html('<option value="" disabled selected>Pilih Kategori</option>');
        $('#subkategori').html('<option value="" disabled selected>Pilih Sub-Kategori</option>');
        $('#no_rujukan').val('');
        $('#bil_latest').val(1);
    });
}

function loadKategori(bahagian_id) {
    $.post("ajax_handler.php", { bahagian_id: bahagian_id }, function(data) {
        $('#kategori').html(data);

        // Reset subkategori & nombor rujukan setiap kali bahagian berubah
        $('#subkategori').html('<option value="" disabled selected>Pilih Sub-Kategori</option>');
        $('#no_rujukan').val('');
        $('#bil_latest').val(1);
    });
}

function filterSubKategori() {
    var kategori_id = $('#kategori').val();
    $.post("ajax_handler.php", { kategori_id: kategori_id }, function(response) {
        $('#subkategori').html(response);
        updateNoRujukan();
    });
}

function updateNoRujukan() {
    var jabatan = ($('#jabatan option:selected').data('kodjbtn')) || "<?= $kod_jabatan ?>";
    var bahagian = ($('#bahagian option:selected').data('kodbhgn')) || "<?= $kod_bahagian ?>";
    var kategori = $('#kategori option:selected').data('kategori') || '';
    var subkategori = $('#subkategori option:selected').data('subkategori') || '';
    var kategoriId = $('#kategori').val();
    var subkategoriId = $('#subkategori').val();

    if (jabatan && bahagian && kategori && subkategoriId !== null) {
        $.ajax({
            url: 'ajax_handler.php',
            method: 'POST',
            data: { kategori: kategoriId, subkategori: subkategoriId },
            success: function(response) {
                var bil_latest = parseInt(response) || 1;
                var noRujukan = jabatan + '-' + bahagian + '/' + kategori;
                if (subkategoriId != 0 && subkategori) {
                    noRujukan += '/' + subkategori;
                }
                noRujukan += '(' + bil_latest + ')';
                $('#no_rujukan').val(noRujukan);
                $('#bil_latest').val(bil_latest);
            }
        });
    }
}
// ===================== EVENTS =====================
// Bila tukar jabatan → reset semua bawah dia
$('#jabatan').change(function() {
    loadBahagian($(this).val());
});

// Bila tukar bahagian → reset kategori & subkategori
$('#bahagian').change(function() {
    $('#kategori').html('<option value="" disabled selected>Pilih Kategori</option>');
    $('#subkategori').html('<option value="" disabled selected>Pilih Sub-Kategori</option>');
    $('#no_rujukan').val('');
    $('#bil_latest').val(1);

    loadKategori($(this).val());
});

// Bila tukar kategori → load subkategori
$('#kategori').change(function() {
    filterSubKategori();
});

// Bila tukar subkategori → update no rujukan
$('#subkategori').change(function() {
    updateNoRujukan();
});
</script>
</body>
</html>