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

// Pastikan hanya Sadmin boleh akses
if (!checkRoles(['superadmin'])) {
    header('Location: unauthorized.php'); 
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<!-- header part -->
<?php include('header.php'); ?>
<!-- end header -->
<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">
        <!-- Topbar header -->
        <?php include('topbar.php'); ?>
        <!-- Left Sidebar -->
        <?php include('leftsidebar.php'); ?>
        
        <!-- Page wrapper -->
        <div class="page-wrapper">
            <!-- Container fluid -->
            <div class="container-fluid">
                <div class="row page-titles">
                    <div class="col-md-5 align-self-center">
                        <h4 class="text-themecolor">Senarai Jabatan</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="dashboard.php">Home</a></li>
                                <li class="breadcrumb-item active">Senarai Jabatan</li>
                            </ol>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Senarai Jabatan</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>Bil.</th>
                                                <th>Nama Jabatan</th>
                                                <th>Kod Jabatan</th>
                                                <th>Tarikh Daftar</th>
                                                <th>Daftar Oleh</th>
                                                <th>Tarikh Kemaskini</th>
                                                <th>Kemaskini Oleh</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        <?php 
                                        // shortform table:j-jabatan,u-users
                                        $sql = "SELECT j.ID, j.NamaJbtn, j.KodJbtn, j.CrtDate, 
                                                u1.NomborStaff AS CrtBy, j.MdfDate, u2.NomborStaff AS MdfBy 
                                                FROM jabatan j
                                                LEFT JOIN users u1 ON j.CrtBy = u1.ID
                                                LEFT JOIN users u2 ON j.MdfBy = u2.ID";

                                        $result = $conn->query($sql);

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

                                        if ($result->num_rows > 0):
                                            $row_number = 1;
                                            while ($row = $result->fetch_assoc()): ?>
                                            <tr>
                                                <td><?php echo $row_number++; ?></td>
                                                <td><?php echo htmlspecialchars($row['NamaJbtn']); ?></td>
                                                <td><?php echo htmlspecialchars($row['KodJbtn']); ?></td>
                                                <td><?php echo htmlspecialchars($row['CrtDate']); ?></td>
                                                <td class="wrap-cell"><?php echo htmlspecialchars($row['CrtBy'] ?? 'Tidak diketahui'); ?></td>
                                                <td><?php echo htmlspecialchars($row['MdfDate']); ?></td>
                                                <td><?php echo htmlspecialchars($row['MdfBy']); ?></td>
                                                <td>
                                                    <a href="edit_jabatan.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">Tiada data</td></tr>
                                        <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
        
        <!-- footer -->
        <?php include('footer.php'); ?>
    </div>
    
    <!-- All Jquery -->
    <?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>