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

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

// Dapatkan maklumat jabatan & bahagian user
$stmt_user = $conn->prepare("SELECT jabatan, bahagian FROM users WHERE id = ?");
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_result = $stmt_user->get_result();
$user_data = $user_result->fetch_assoc();
$stmt_user->close();

if (!$user_data) {
    die("Data pengguna tidak dijumpai.");
}

$user_jabatan_id = $user_data['jabatan'];
$user_bahagian_id = $user_data['bahagian'];

// Fungsi untuk dapatkan nama jabatan
function getJabatanName($conn, $id) {
    $stmt = $conn->prepare("SELECT NamaJbtn FROM jabatan WHERE ID = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $name = ($res->num_rows > 0) ? $res->fetch_assoc()['NamaJbtn'] : '';
    $stmt->close();
    return $name;
}

// AJAX - Dapatkan senarai bahagian
if (isset($_GET['jabatan_id']) && is_numeric($_GET['jabatan_id'])) {
    $stmt = $conn->prepare("SELECT ID, Keterangan FROM bahagian WHERE IDJbtn = ?");
    $stmt->bind_param("i", $_GET['jabatan_id']);
    $stmt->execute();
    $res = $stmt->get_result();
    $data = [];
    while ($row = $res->fetch_assoc()) {
        $data[] = $row;
    }
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

// AJAX - Dapatkan senarai kategori
if (isset($_GET['bahagian_id']) && is_numeric($_GET['bahagian_id'])) {
    $stmt = $conn->prepare("SELECT ID, Keterangan FROM kategori WHERE IDBhgn = ?");
    $stmt->bind_param("i", $_GET['bahagian_id']);
    $stmt->execute();
    $res = $stmt->get_result();
    $data = [];
    while ($row = $res->fetch_assoc()) {
        $data[] = $row;
    }
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

// Proses borang
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $IDKategori = intval($_POST['IDKategori'] ?? 0);
    $Sub_kategori = trim($_POST['Sub_kategori'] ?? '');
    $Keterangan = trim($_POST['Keterangan'] ?? '');

    if ($user_role === 'superadmin') {
        $NamaJbtn = intval($_POST['NamaJbtn'] ?? 0);
        $IDBhgn = intval($_POST['IDBhgn'] ?? 0);
    } else {
        $NamaJbtn = $user_jabatan_id;
        $IDBhgn = intval($_POST['IDBhgn'] ?? 0);
    }

    if ($IDKategori <= 0 || $NamaJbtn <= 0 || $IDBhgn <= 0 || $Sub_kategori === '' || $Keterangan === '') {
        $error = "Sila isi semua maklumat dengan lengkap.";
    } else {
        $stmt_check = $conn->prepare("SELECT 1 FROM subkategori WHERE (Sub_kategori = ? OR Keterangan = ?) AND IDKategori = ?");
        $stmt_check->bind_param("ssi", $Sub_kategori, $Keterangan, $IDKategori);
        $stmt_check->execute();
        $result_check = $stmt_check->get_result();

        if ($result_check->num_rows > 0) {
            $error = "Sub-kategori atau keterangan ini telah wujud dalam kategori ini.";
        } else {
            $stmt_check->close();
            $stmt = $conn->prepare("INSERT INTO subkategori (IDKategori, Sub_kategori, Keterangan, CrtBy) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("isss", $IDKategori, $Sub_kategori, $Keterangan, $user_id);
            if ($stmt->execute()) {
                $success = "Sub-kategori berjaya ditambah.";
            } else {
                $error = "Ralat: " . $stmt->error;
            }
            $stmt->close();
        }
    }
}

// Data dropdown
$jabatan_options = [];
if ($user_role === 'superadmin') {
    $res_jbtn = $conn->query("SELECT ID, NamaJbtn FROM jabatan ORDER BY NamaJbtn");
    while ($row = $res_jbtn->fetch_assoc()) {
        $jabatan_options[] = $row;
    }
}

$user_jabatan_name = '';
if ($user_role === 'admin') {
    $user_jabatan_name = getJabatanName($conn, $user_jabatan_id);
}
?>

<!DOCTYPE html>
<html lang="ms">
<head>
    <title>Tambah Sub-Kategori</title>
    <?php include('header.php'); ?>
</head>
<body class="skin-blue fixed-layout">
<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 Sub-Kategori</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 Sub-Kategori</li>
                            </ol>
                        </div>
                    </div>
                </div>

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

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Tambah SubKategori Baru</h4>
                            <form method="post" id="kategoriForm">

                                <?php if ($user_role === 'superadmin'): ?>
                                    <div class="form-group">
                                        <label>Jabatan</label>
                                        <select name="NamaJbtn" id="NamaJbtn" class="form-control" required>
                                            <option value="" disabled selected>Pilih Jabatan</option>
                                            <?php foreach ($jabatan_options as $jbtn): ?>
                                                <option value="<?= $jbtn['ID'] ?>"><?= htmlspecialchars($jbtn['NamaJbtn']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Bahagian</label>
                                        <select name="IDBhgn" id="IDBhgn" class="form-control" required>
                                            <option value="" disabled selected>Pilih Bahagian</option>
                                        </select>
                                    </div>
                                <?php else: ?>
                                    <div class="form-group">
                                        <label>Jabatan</label>
                                        <input type="text" class="form-control" value="<?= htmlspecialchars($user_jabatan_name) ?>" readonly>
                                        <input type="hidden" name="NamaJbtn" value="<?= htmlspecialchars($user_jabatan_id) ?>">
                                    </div>
                                    <div class="form-group">
                                        <label>Bahagian</label>
                                        <select name="IDBhgn" id="IDBhgn" class="form-control" required>
                                            <option value="" disabled selected>Pilih Bahagian</option>
                                            <?php
                                            $stmt = $conn->prepare("SELECT ID, Keterangan FROM bahagian WHERE IDJbtn = ?");
                                            $stmt->bind_param("i", $user_jabatan_id);
                                            $stmt->execute();
                                            $res = $stmt->get_result();
                                            while ($row = $res->fetch_assoc()):
                                            ?>
                                                <option value="<?= $row['ID'] ?>"><?= htmlspecialchars($row['Keterangan']) ?></option>
                                            <?php endwhile; ?>
                                            <?php $stmt->close(); ?>
                                        </select>
                                    </div>
                                <?php endif; ?>

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

                                <div class="form-group">
                                    <label>Kod Sub-Kategori</label>
                                    <input type="number" class="form-control" name="Sub_kategori" required>
                                </div>

                                <div class="form-group">
                                    <label>Keterangan</label>
                                    <input type="text" class="form-control" name="Keterangan" required>
                                </div>

                                <button type="submit" class="btn btn-primary btn-block">Tambah SubKategori</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

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

    <?php include('jquery.php'); ?>
<script>
$(document).ready(function () {
    // Superadmin: apabila jabatan berubah, load bahagian
    $('#NamaJbtn').on('change', function () {
        const jabatan_id = $(this).val();
        $('#IDBhgn').html('<option value="" disabled selected>Pilih Kategori</option>');
        $('#IDKategori').html('<option value="" disabled selected>Pilih Kategori</option>');
        if (jabatan_id) {
            $.get('', { jabatan_id }, function (data) {
                $('#IDBhgn').html('<option value="" disabled selected>Pilih Bahagian</option>');
                $.each(data, function (i, item) {
                    $('#IDBhgn').append(`<option value="${item.ID}">${item.Keterangan}</option>`);
                });
            }, 'json');
        }
    });

    // Semua role: apabila bahagian berubah, load kategori
    $('#IDBhgn').on('change', function () {
        const bahagian_id = $(this).val();
        $('#IDKategori').html('<option value="" disabled selected>Pilih Kategori</option>');
        if (bahagian_id) {
            $.get('', { bahagian_id }, function (data) {
                $('#IDKategori').html('<option value="" disabled selected>Pilih Kategori</option>');
                $.each(data, function (i, item) {
                    $('#IDKategori').append(`<option value="${item.ID}">${item.Keterangan}</option>`);
                });
            }, 'json');
        }
    });

    // Admin: trigger auto-load kategori awal
    <?php if ($user_role === 'admin'): ?>
    $('#IDBhgn').trigger('change');
    <?php endif; ?>
});
</script>
</body>
</html>