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

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

$user_role = $_SESSION['user_role'];
$jabatan_id = $_SESSION['jabatan'] ?? 0;
$filter_bahagian = $_GET['bahagian'] ?? ''; // ambil dari URL (ajax)

if ($user_role === 'superadmin') {
    if (!empty($filter_bahagian)) {
        $sql = "SELECT s.ID, s.Tarikh, s.Tajuk, s.Lokasi, s.no_rujukan, u.NamaStaff 
                FROM surat s 
                LEFT JOIN users u ON s.CrtBy = u.ID
                WHERE s.bahagian = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $filter_bahagian);
    } else {
        $sql = "SELECT s.ID, s.Tarikh, s.Tajuk, s.Lokasi, s.no_rujukan, u.NamaStaff 
                FROM surat s 
                LEFT JOIN users u ON s.CrtBy = u.ID";
        $stmt = $conn->prepare($sql);
    }
} else {
    if (!empty($filter_bahagian)) {
        $sql = "SELECT s.ID, s.Tarikh, s.Tajuk, s.Lokasi, s.no_rujukan, u.NamaStaff 
                FROM surat s 
                LEFT JOIN users u ON s.CrtBy = u.ID
                WHERE s.jabatan = ? AND s.bahagian = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $jabatan_id, $filter_bahagian);
    } else {
        $sql = "SELECT s.ID, s.Tarikh, s.Tajuk, s.Lokasi, s.no_rujukan, u.NamaStaff 
                FROM surat s 
                LEFT JOIN users u ON s.CrtBy = u.ID
                WHERE s.jabatan = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $jabatan_id);
    }
}

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

<!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 Surat/Memo</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 Surat/Memo</li>
                            </ol>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Senarai Surat/Memo</h4>

<!-- Filter Bahagian -->
<div class="row mb-3">
    <div class="col-md-5">
        <label for="filter_bahagian" class="form-label">Pilih Mengikut Bahagian:</label>
        <select id="filter_bahagian" class="form-select">
            <option value="" disabled selected>Pilih Bahagian</option>
            <option value="all" <?= ($filter_bahagian === 'all') ? 'selected' : '' ?>>-- Semua Bahagian --</option>
            <?php
            if ($user_role === 'superadmin') {
                $queryBahagian = $conn->query("SELECT ID, Keterangan FROM bahagian ORDER BY ID ASC");
            } else {
                $stmtBahagian = $conn->prepare("SELECT ID, Keterangan FROM bahagian WHERE IDJbtn = ?");
                $stmtBahagian->bind_param("i", $jabatan_id);
                $stmtBahagian->execute();
                $queryBahagian = $stmtBahagian->get_result();
            }

            while ($b = $queryBahagian->fetch_assoc()) {
                $selected = ($filter_bahagian == $b['ID']) ? 'selected' : '';
                echo '<option value="' . $b['ID'] . '" ' . $selected . '>' . htmlspecialchars($b['Keterangan']) . '</option>';
            }
            ?>
        </select>
    </div>
</div>
<!-- End Filter Bahagian -->

                                <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>No. Rujukan</th>
                                                <th>Tarikh </th>
                                                <th>Tajuk Surat/Memo</th>
                                                <th>Lokasi Dokumen</th>
                                                <th>Cipta oleh</th>
                                                <th>Tindakan</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        <?php if ($result->num_rows > 0): ?>
                                        <?php $row_number = 1; ?>
                                        <?php while ($row = $result->fetch_assoc()): ?>
                                            <style>
                                            .wrap-cell {
                                                max-width: 10px;
                                                white-space: normal;
                                                word-wrap: break-word;
                                            }
                                            </style>

                                            <tr id="row_<?php echo $row['ID']; ?>">
                                                <td class="wrap-cell"><?php echo $row_number++; ?></td>
                                                <td class="wrap-cell"><?php echo htmlspecialchars($row['no_rujukan']); ?></td>
                                                <td class="wrap-cell"><?php echo htmlspecialchars($row['Tarikh']); ?></td>
                                                <td class="wrap-cell"><?php echo htmlspecialchars($row['Tajuk']); ?></td>
                                                <td class="wrap-cell"><?php echo htmlspecialchars($row['Lokasi']); ?></td>
                                                <td class="wrap-cell"><?php echo htmlspecialchars($row['NamaStaff'] ?? 'Tidak diketahui'); ?></td>
                                                <td>
                                                    <a href="update_norujukan.php?id=<?php echo $row['ID']; ?>" class="btn btn-success 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="norujukan">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>
<script>
$(document).ready(function() {
    $('#filter_bahagian').on('change', function() {
        let selected = $(this).val();

        // Kalau user pilih "Semua Bahagian"
        if (selected === 'all') {
            window.location.href = 'view_norujukan.php';
        } else {
            // Reload page dengan parameter ?bahagian=
            window.location.href = 'view_norujukan.php?bahagian=' + selected;
        }
    });
});
</script>
</body>
</html>