<?php
include('session_handler.php'); // pastikan session_handler.php assign $user_role & $user_id

// Pastikan hanya Sadmin dan admin boleh akses
if (!checkRoles(['superadmin', 'admin'])) {
    header('Location: unauthorized.php'); 
    exit;
}

// Untuk admin, dapatkan jabatan user dulu
$user_jabatan_id = null;
if ($user_role === 'admin') {
    $stmt = $conn->prepare("SELECT jabatan FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $data = $res->fetch_assoc();
    $stmt->close();

    if ($data) {
        $user_jabatan_id = $data['jabatan'];
    } else {
        die("Data pengguna tidak dijumpai.");
    }
}

// Query kategori ikut role
if ($user_role === 'superadmin') {
    $sql = "SELECT k.ID, k.Kategori, k.Keterangan, k.CrtDate, 
                   u1.NomborStaff AS CrtBy, 
                   k.MdfDate, 
                   u2.NomborStaff AS MdfBy,
                   j.KodJbtn, 
                   b.KodBhgn
            FROM kategori k
            JOIN bahagian b ON k.IDBhgn = b.ID
            JOIN jabatan j ON b.IDJbtn = j.ID
            LEFT JOIN users u1 ON k.CrtBy = u1.ID
            LEFT JOIN users u2 ON k.MdfBy = u2.ID
            ORDER BY k.IDBhgn";
    $stmt = $conn->prepare($sql);
} else {
    // admin - filter ikut jabatan user
    $sql = "SELECT k.ID, k.Kategori, k.Keterangan, k.CrtDate, 
                   u1.NomborStaff AS CrtBy, 
                   k.MdfDate, 
                   u2.NomborStaff AS MdfBy,
                   j.KodJbtn, 
                   b.KodBhgn
            FROM kategori k
            JOIN bahagian b ON k.IDBhgn = b.ID
            JOIN jabatan j ON b.IDJbtn = j.ID
            LEFT JOIN users u1 ON k.CrtBy = u1.ID
            LEFT JOIN users u2 ON k.MdfBy = u2.ID
            WHERE j.ID = ?
            ORDER BY k.IDBhgn";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_jabatan_id);
}

$stmt->execute();
$result = $stmt->get_result();

if ($result === false) {
    die("Ralat Query: " . $conn->error);
}
?>

<!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">Senarai 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">Senarai Kategori</li>
                            </ol>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Senarai Kategori</h4>
                                
                                <div class="table-responsive m-t-40">
                                    <table id="example23" class="display nowrap table table-hover table-striped border" cellspacing="0" width="100%">
                                        <thead>
                                            <tr>
                                                <th>Bilangan</th>
                                                <th>Kategori</th>
                                                <th>Kod Kategori</th>
                                                <th>Tarikh Daftar</th>
                                                <th>Daftar Oleh</th>
                                                <th>Tarikh Kemaskini</th>
                                                <th>Kemaskini Oleh</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        <?php if ($result->num_rows > 0): ?>
                                            <?php $row_number = 1; ?>
                                            <?php while ($row = $result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo $row_number++; ?></td>
                                                    <td><?php echo htmlspecialchars($row['Keterangan']); ?></td>
                                                    <td><?php echo htmlspecialchars($row['KodJbtn'] . '-' . $row['KodBhgn'] . '/' . $row['Kategori']); ?></td>
                                                    <td><?php echo htmlspecialchars($row['CrtDate']); ?></td>
                                                    <td class="wrap-cell"><?php echo htmlspecialchars($row['CrtBy'] ?? 'Tidak diketahui'); ?></td>
                                                    <td><?php echo !empty($row['MdfDate']) ? htmlspecialchars($row['MdfDate']) : ''; ?></td>
                                                    <td><?php echo !empty($row['MdfBy']) ? htmlspecialchars($row['MdfBy']) : ''; ?></td>
                                                    <td>
                                                        <a href="edit_kategori.php?id=<?php echo $row['ID']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                                        <?php if ($user_role === 'superadmin'): ?>
                                                        <button class="btn btn-danger btn-sm btn-delete"
                                                                data-id="<?php echo $row['ID']; ?>"
                                                                data-type="subkategori">Padam</button>
                                                    <?php endif; ?>
                                                    </td>
                                                </tr>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <tr><td colspan="8" class="text-center">Tiada data</td></tr>
                                        <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

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

    <?php include('jquery.php'); ?>
     <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).on('click', '.btn-delete', function() {
    let id = $(this).data('id');
    let type = $(this).data('type');

    Swal.fire({
        title: 'Padam rekod ini?',
        text: "Tindakan ini tidak boleh dibatalkan.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Ya, padam!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('delete.php', { id: id, type: type }, function(response) {
                let res = JSON.parse(response);

                if (res.status === 'unauthorized') {
                    Swal.fire('Akses Ditolak', res.message, 'error');
                } else if (res.status === 'fail') {
                    Swal.fire('Tidak Boleh Padam', res.message, 'warning');
                } else if (res.status === 'success') {
                    Swal.fire('Berjaya', res.message, 'success');
                    $('#row_' + id).fadeOut(500, function() { $(this).remove(); });
                } else {
                    Swal.fire('Ralat', 'Sila cuba semula.', 'error');
                }
            });
        }
    });
});
</script>
</body>
</html>