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

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

$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.");
    }
}

if ($user_role === 'superadmin') {
    $sql = "SELECT s.ID, s.Sub_kategori, s.Keterangan, s.CrtDate, 
                   u1.NomborStaff AS CrtBy, 
                   s.MdfDate, 
                   u2.NomborStaff AS MdfBy,
                   j.KodJbtn, 
                   b.KodBhgn, 
                   k.Kategori
            FROM subkategori s
            JOIN kategori k ON s.IDKategori = k.ID
            JOIN bahagian b ON k.IDBhgn = b.ID
            JOIN jabatan j ON b.IDJbtn = j.ID
            LEFT JOIN users u1 ON s.CrtBy = u1.ID
            LEFT JOIN users u2 ON s.MdfBy = u2.ID
            ORDER BY s.IDKategori ASC";
    $stmt = $conn->prepare($sql);
} else {
    $sql = "SELECT s.ID, s.Sub_kategori, s.Keterangan, s.CrtDate, 
                   u1.NomborStaff AS CrtBy, 
                   s.MdfDate, 
                   u2.NomborStaff AS MdfBy,
                   j.KodJbtn, 
                   b.KodBhgn, 
                   k.Kategori
            FROM subkategori s
            JOIN kategori k ON s.IDKategori = k.ID
            JOIN bahagian b ON k.IDBhgn = b.ID
            JOIN jabatan j ON b.IDJbtn = j.ID
            LEFT JOIN users u1 ON s.CrtBy = u1.ID
            LEFT JOIN users u2 ON s.MdfBy = u2.ID
            WHERE j.ID = ?
            ORDER BY s.IDKategori ASC";
    $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 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">Senarai Sub-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 Sub-Kategori</h4>
                                <h6 class="card-subtitle">Export data to Copy, CSV, Excel, PDF & Print</h6>
                                <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>Sub-Kategori</th>
                                                <th>Kod Sub-Kategori</th>
                                                <th>Tarikh Daftar</th>
                                                <th>Daftar Oleh</th>
                                                <th>Tarikh Kemaskini</th>
                                                <th>Kemaskini Oleh</th>
                                                <th>Tindakan</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            if ($result->num_rows > 0):
                                                $row_number = 1;
                                                while ($row = $result->fetch_assoc()):
                                            ?>
                                            <tr>
                                                <td><?= $row_number++; ?></td>
                                                <td><?= htmlspecialchars($row['Keterangan']); ?></td>
                                                <td><?= htmlspecialchars($row['KodJbtn'] . '-' . $row['KodBhgn'] . '/' . $row['Kategori'] . '/' . $row['Sub_kategori']); ?></td>
                                                <td><?= htmlspecialchars($row['CrtDate']); ?></td>
                                                <td class="wrap-cell"><?php echo htmlspecialchars($row['CrtBy'] ?? 'Tidak diketahui'); ?></td>

                                                <td><?= !empty($row['MdfDate']) ? htmlspecialchars($row['MdfDate']) : ''; ?></td>
                                                <td><?= !empty($row['MdfBy']) ? htmlspecialchars($row['MdfBy']) : ''; ?></td>
                                                <td>
                                                    <a href="edit_sub.php?id=<?= $row['ID']; ?>" class="btn btn-warning btn-sm">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;
                                            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>