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

// ========== Ambil bahagian ikut jabatan ==========
if (isset($_POST['jabatan_id'])) {
    $jabatan_id = $_POST['jabatan_id'];
    $bahagianQuery = mysqli_query($conn, "SELECT * FROM bahagian WHERE IDJbtn = '$jabatan_id'");
    $output = '<option value="" disabled selected>Pilih Bahagian</option>';
    while ($b = mysqli_fetch_assoc($bahagianQuery)) {
        $output .= '<option value="'.$b['ID'].'" data-kodbhgn="'.$b['KodBhgn'].'">'.htmlspecialchars($b['Keterangan']).'</option>';
    }
    echo $output;
    exit;
}

// ========== Ambil kategori ikut bahagian ==========
if (isset($_POST['bahagian_id'])) {
    $bahagian_id = $_POST['bahagian_id'];
    $kategoriQuery = mysqli_query($conn, "SELECT * FROM kategori WHERE IDBhgn = '$bahagian_id'");
    $output = '<option value="" disabled selected>Pilih Kategori</option>';
    while ($k = mysqli_fetch_assoc($kategoriQuery)) {
        $output .= '<option value="'.$k['ID'].'" data-kategori="'.htmlspecialchars($k['Kategori']).'">'.htmlspecialchars($k['Keterangan']).'</option>';
    }
    echo $output;
    exit;
}

// ========== Ambil subkategori ikut kategori ==========
if (isset($_POST['kategori_id'])) {
    $kategori_id = $_POST['kategori_id'];
    $subkategoriQuery = mysqli_query($conn, "SELECT * FROM subkategori WHERE IDKategori = '$kategori_id'");
    
    if (mysqli_num_rows($subkategoriQuery) > 0) {
        // Kalau ada subkategori → populate option ikut row
        $output = '<option value="" disabled selected>Pilih Sub-Kategori</option>';
        while ($row = mysqli_fetch_assoc($subkategoriQuery)) {
            $output .= '<option value="' . $row['ID'] . '" data-subkategori="' . htmlspecialchars($row['Sub_kategori']) . '">' . htmlspecialchars($row['Keterangan']) . '</option>';
        }
    } else {
        // Kalau tak ada subkategori → letak Tiada
        $output = '<option value="0">Tiada</option>';
    }

    echo $output;
    exit;
}

// ========== Check bil_latest ==========
if (isset($_POST['kategori']) && isset($_POST['subkategori'])) {
    $kategori_id = $_POST['kategori'];
    $subkategori_id = $_POST['subkategori'];

    if ($subkategori_id == 0) {
        $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;
    echo $bil_latest;
    exit;
}
?>