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

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

// Dapatkan jabatan & bahagian user dari table users
$user_query = "SELECT jabatan, bahagian FROM users WHERE id = ?";
$stmt_user = $conn->prepare($user_query);
$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;
}

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil data dari POST dengan validation basic
    $Kategori = trim($_POST['Kategori'] ?? '');
    $Keterangan = trim($_POST['Keterangan'] ?? '');

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

    if ($Kategori === '' || $Keterangan === '' || $NamaJbtn <= 0 || $IDBhgn <= 0) {
        $error = "Sila isi semua maklumat yang diperlukan dengan betul.";
    } else {
        // Check if Kategori sudah wujud
        $stmt_check = $conn->prepare("SELECT * FROM kategori WHERE (Kategori = ? OR Keterangan = ?) AND IDBhgn = ?");
        $stmt_check->bind_param("ssi", $Kategori, $Keterangan, $IDBhgn);
        $stmt_check->execute();
        $result_check = $stmt_check->get_result();

            if ($result_check->num_rows > 0) {
            $error = "Kod Kategori atau Keterangan ini telah digunakan dalam bahagian ini.";
            } else {
            $stmt_check->close();
            // Insert kategori
            $stmt = $conn->prepare("INSERT INTO kategori (IDBhgn, Kategori, Keterangan, CrtBy) VALUES (?, ?, ?, ?)");
            if ($stmt === false) {
                die("MySQL Prepare Error: " . $conn->error);
            }
            $stmt->bind_param("isss", $IDBhgn, $Kategori, $Keterangan, $user_id);
            if ($stmt->execute()) {
                $success = "Kategori berjaya ditambah!";
            } else {
                $error = "Ralat: " . $stmt->error;
            }
            $stmt->close();
        }
    }
}

// Untuk dropdown Jabatan (superadmin saja)
$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;
    }
}

// Jika admin, dapatkan nama jabatan user
$user_jabatan_name = '';
if ($user_role === 'admin') {
    $user_jabatan_name = getJabatanName($conn, $user_jabatan_id);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Tambah 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 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 Kategori</li>
                            </ol>
                        </div>
                    </div>
                </div>

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

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

                                    <?php if ($user_role === 'superadmin'): ?>
                                        <div class="form-group">
                                            <label for="NamaJbtn">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 for="IDBhgn">Bahagian:</label>
                                            <select name="IDBhgn" id="IDBhgn" class="form-control" required>
                                                <option value="" disabled selected>Pilih Bahagian</option>
                                            </select>
                                        </div>

                                    <?php elseif ($user_role === 'admin'): ?>
                                        <div class="form-group">
                                            <label for="NamaJbtn">Jabatan:</label>
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($user_jabatan_name); ?>" readonly>
                                            <input type="hidden" name="NamaJbtn" value="<?php echo htmlspecialchars($user_jabatan_id); ?>">
                                        </div>

                                        <div class="form-group">
                                            <label for="IDBhgn">Bahagian:</label>
                                            <select name="IDBhgn" id="IDBhgn" class="form-control" required>
                                                <option value="" disabled selected>Pilih Bahagian</option>
                                                <?php
                                                // Dapatkan bahagian ikut jabatan user
                                                $stmt_bhgn = $conn->prepare("SELECT ID, Keterangan, KodBhgn FROM bahagian WHERE IDJbtn = ?");
                                                $stmt_bhgn->bind_param("i", $user_jabatan_id);
                                                $stmt_bhgn->execute();
                                                $res_bhgn = $stmt_bhgn->get_result();
                                                while ($row_bhgn = $res_bhgn->fetch_assoc()):
                                                ?>
                                                <option value="<?= $row_bhgn['ID'] ?>">
                                                <?= htmlspecialchars($row_bhgn['Keterangan']) ?>
                                                </option>
                                                <?php endwhile;
                                                $stmt_bhgn->close();
                                                ?>
                                            </select>
                                        </div>
                                    <?php endif; ?>

                                    <div class="form-group">
                                        <label for="Kategori">Kod Kategori:</label>
                                        <input type="number" class="form-control" name="Kategori" id="Kategori" required>
                                    </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 Kategori</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

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

    <?php include('jquery.php'); ?>

    <?php if ($user_role === 'superadmin'): ?>
    <script>
    $(document).ready(function() {
        $('#NamaJbtn').change(function() {
            var jabatan_id = $(this).val();

            if (jabatan_id) {
                $.ajax({
                    url: '<?= $_SERVER['PHP_SELF'] ?>',
                    type: 'GET',
                    data: { jabatan_id: jabatan_id },
                    dataType: 'json',
                    success: function(data) {
                        $('#IDBhgn').empty().append('<option value="" disabled selected>Pilih Bahagian</option>');
                        $.each(data, function(key, value) {
                            var formattedText = value.Keterangan;
                            $('#IDBhgn').append('<option value="' + value.ID + '">' + formattedText + '</option>');
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error("AJAX Error: " + status + " - " + error + "\nResponse: " + xhr.responseText);
                        alert("Terdapat ralat semasa memuatkan bahagian.");
                    }
                });
            } else {
                $('#IDBhgn').empty().append('<option value="" disabled selected>Pilih Bahagian</option>');
            }
        });
    });
    </script>

    <?php endif; ?>

</body>
</html>