<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

$role = $_SESSION['role'] ?? 'user';
$user_department = currentUserDepartment($conn);
$current_user_id = (int) ($_SESSION['user_id'] ?? 0);

// Fetch staff data based on filter
$filter_type = isset($_GET['filter']) ? $_GET['filter'] : 'MAINPP';
$valid_filters = ['MAINPP', 'AGENSI LUAR'];
if (!in_array($filter_type, $valid_filters, true)) {
    $filter_type = 'MAINPP';
}

// Sync MAINPP users from users table to staff_distribution_list
syncMainPPUsersToStaffDistributionList($conn);

$staff_list = [];

if ($filter_type === 'MAINPP') {
    // Query from staff_distribution_list table
    $sql = "SELECT id, agency_type, name, position, department, source, user_id 
            FROM staff_distribution_list 
            WHERE deleted_at IS NULL AND agency_type = 'MAINPP'
            ORDER BY created_at DESC";
    $result = mysqli_query($conn, $sql);
    if ($result) {
        $staff_list = mysqli_fetch_all($result, MYSQLI_ASSOC);
    }
} else if ($filter_type === 'AGENSI LUAR') {
    // Query from staff_distribution_list table
    $sql = "SELECT id, agency_type, name, position, department, agency, address, created_at, updated_at 
            FROM staff_distribution_list 
            WHERE deleted_at IS NULL AND agency_type = 'AGENSI LUAR'
            ORDER BY created_at DESC";
    $result = mysqli_query($conn, $sql);
    if ($result) {
        $staff_list = mysqli_fetch_all($result, MYSQLI_ASSOC);
    }
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Senarai Kakitangan | MAINPP WORKSPACE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <?php renderAppShellAssets(); ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --bg-light: rgba(245, 250, 253, 0.72); --bg-card: rgba(255, 255, 255, 0.68); --text-main: #163447;
            --text-muted: #2d5367; --border: rgba(255, 255, 255, 0.48); --sidebar-width: 280px;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
            --glass: rgba(255, 255, 255, 0.58);
            --glass-strong: rgba(255, 255, 255, 0.76);
            --shadow-soft: 0 24px 70px rgba(2, 62, 95, 0.16);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif; }
        body {
            min-height: 100vh;
            display: flex;
            color: var(--text-main);
            background:
                linear-gradient(135deg, rgba(245, 250, 253, 0.90), rgba(222, 246, 252, 0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            overflow-x: hidden;
        }

        .sidebar {
            width: var(--sidebar-width);
            background: linear-gradient(180deg, rgba(2,62,95,0.94), rgba(0,119,182,0.84));
            border-right: 1px solid rgba(255,255,255,0.22);
            box-shadow: 18px 0 44px rgba(2,38,60,0.20);
            backdrop-filter: blur(18px) saturate(1.25);
            -webkit-backdrop-filter: blur(18px) saturate(1.25);
            overflow: hidden;
            position: fixed;
            height: 100vh;
            padding: 20px 0;
            z-index: 1000;
            transition: width 0.3s ease;
            display: flex;
            flex-direction: column;
        }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header {
            flex: 0 0 auto;
            text-align: center;
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255,255,255,0.16);
            margin-bottom: 20px;
            white-space: nowrap;
            overflow: hidden;
            background: transparent !important;
        }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 58px; margin-bottom: 10px; transition: margin 0.3s ease; filter: drop-shadow(0 8px 14px rgba(0,0,0,0.22)); }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 800; color: #fff; margin-bottom: 4px; letter-spacing: 0.01em; }
        .sidebar-header p { font-size: 0.75rem; color: rgba(255,255,255,0.72); }
        .sidebar-menu {
            list-style: none;
            padding: 0 10px;
            display: flex;
            flex-direction: column;
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 0;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #8f8f8f transparent;
        }
        .sidebar-menu::-webkit-scrollbar {
            width: 10px;
        }
        .sidebar-menu::-webkit-scrollbar-track {
            background: transparent;
        }
        .sidebar-menu::-webkit-scrollbar-thumb {
            background: #8f8f8f;
            border-radius: 999px;
            border: 2px solid transparent;
            background-clip: content-box;
        }
        .sidebar-menu::-webkit-scrollbar-button {
            display: none;
            width: 0;
            height: 0;
        }
        .sidebar-section { padding: 10px 18px 6px; color: rgba(255,255,255,0.58); font-size: 0.72rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-spacer { margin-top: auto; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: rgba(255,255,255,0.88); text-decoration: none; border-radius: 10px; margin-bottom: 5px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-menu .dropdown { position: relative; }
        .sidebar-menu .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; color: rgba(255,255,255,0.88); background: none; border: none; border-radius: 10px; cursor: pointer; font-size: 0.9rem; text-align: left; transition: all 0.2s ease; }
        .sidebar-menu .dropdown-toggle:hover, .sidebar-menu .dropdown-toggle.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu .dropdown-toggle i.chevron { transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.8rem; }
        .sidebar-menu .dropdown.active .dropdown-toggle i.chevron { transform: rotate(180deg); }
        .sidebar-menu .dropdown-menu { display: flex; flex-direction: column; padding-left: 42px; margin-top: 4px; max-height: 0; opacity: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu { max-height: 260px; opacity: 1; }
        .sidebar-menu .dropdown-menu a { padding: 8px 18px; color: rgba(255,255,255,0.78); text-decoration: none; border-radius: 8px; font-size: 0.85rem; display: flex; align-items: center; gap: 8px; opacity: 0; transform: translateY(-5px); transition: opacity 0.2s ease, transform 0.2s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu a { opacity: 1; transform: translateY(0); }
        .sidebar-menu .dropdown-menu a:hover, .sidebar-menu .dropdown-menu a.active { background: rgba(255,255,255,0.16); color: #fff; }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar-toggle { position: absolute; right: 10px; top: 20px; width: 28px; height: 28px; background: rgba(255,255,255,0.20); color: #fff; border: 1px solid rgba(255,255,255,0.28); border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 10px 22px rgba(0,0,0,0.14); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .main { position: relative; z-index: 1; margin-left: var(--sidebar-width); flex: 1; padding: 28px 32px; transition: margin-left 0.3s ease; }
        .top-bar {
            background: var(--glass);
            padding: 18px 24px;
            border-radius: 18px;
            box-shadow: var(--shadow-soft);
            margin-bottom: 18px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border: 1px solid var(--border);
            backdrop-filter: blur(22px) saturate(1.25);
            -webkit-backdrop-filter: blur(22px) saturate(1.25);
        }
        .top-bar h2 { color: var(--primary-dark); font-size: 1.35rem; font-weight: 850; display: flex; align-items: center; gap: 10px; }
        .top-bar h2 i { color: var(--secondary); }

        /* Filter Buttons */
        .filter-buttons {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .filter-btn {
            padding: 12px 24px;
            background: rgba(255, 255, 255, 0.70);
            border: 1px solid rgba(0, 119, 182, 0.20);
            border-radius: 12px;
            cursor: pointer;
            font-weight: 750;
            color: var(--primary-dark);
            transition: all 0.25s ease;
            box-shadow: 0 8px 20px rgba(2, 62, 95, 0.06);
            white-space: nowrap;
        }
        .filter-btn:hover {
            transform: translateY(-1px);
            background: rgba(0, 119, 182, 0.12);
            color: var(--primary-dark);
        }
        .filter-btn.active {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: #fff;
            box-shadow: 0 14px 28px rgba(0, 119, 182, 0.24);
        }
        .filter-btn.add-staff {
            background: linear-gradient(90deg, var(--success), #2ecc71);
            color: #fff;
            border: none;
        }
        .filter-btn.add-staff:hover {
            background: linear-gradient(90deg, #1a9955, #27ae60);
            box-shadow: 0 14px 28px rgba(26, 153, 85, 0.24);
        }

        /* Form Container */
        .form-container {
            background: var(--glass);
            border-radius: 18px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: var(--shadow-soft);
            border: 1px solid var(--border);
            backdrop-filter: blur(24px) saturate(1.25);
            -webkit-backdrop-filter: blur(24px) saturate(1.25);
            display: none;
        }
        .form-container.show { display: block; animation: slideDown 0.3s ease; }
        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .form-title {
            color: var(--primary-dark);
            font-size: 1.15rem;
            font-weight: 850;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .form-title i { color: var(--secondary); }
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 16px;
            margin-bottom: 16px;
        }
        .form-group { margin-bottom: 16px; }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 650;
            color: var(--text-main);
            font-size: 0.9rem;
        }
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid rgba(0, 119, 182, 0.20);
            border-radius: 10px;
            font-size: 0.95rem;
            background: rgba(255, 255, 255, 0.85);
            transition: all 0.2s ease;
        }
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(0, 119, 182, 0.15);
        }
        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }
        .form-actions {
            display: flex;
            gap: 12px;
            margin-top: 20px;
        }
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-weight: 700;
            font-size: 0.95rem;
            transition: all 0.25s ease;
        }
        .btn-primary {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: #fff;
            box-shadow: 0 10px 20px rgba(0, 119, 182, 0.20);
        }
        .btn-primary:hover {
            transform: translateY(-1px);
            filter: brightness(1.04);
            box-shadow: 0 14px 28px rgba(0, 119, 182, 0.24);
        }
        .btn-secondary {
            background: rgba(255, 255, 255, 0.85);
            color: var(--text-muted);
            border: 1px solid rgba(0, 119, 182, 0.20);
        }
        .btn-secondary:hover {
            background: rgba(0, 119, 182, 0.08);
            color: var(--primary-dark);
        }

        /* Staff Cards */
        .table-container {
            background: var(--glass);
            border-radius: 18px;
            padding: 24px;
            box-shadow: var(--shadow-soft);
            border: 1px solid var(--border);
            backdrop-filter: blur(24px) saturate(1.25);
            -webkit-backdrop-filter: blur(24px) saturate(1.25);
            overflow: visible;
        }
        .table-title {
            color: var(--primary-dark);
            font-size: 1.15rem;
            font-weight: 850;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .table-title i { color: var(--secondary); }
        .staff-card-grid {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 16px;
        }
        .staff-card {
            display: flex;
            flex-direction: column;
            min-height: 100%;
            padding: 16px;
            border-radius: 16px;
            border: 1px solid rgba(255, 255, 255, 0.58);
            background: rgba(255, 255, 255, 0.72);
            box-shadow: 0 14px 34px rgba(2, 62, 95, 0.10);
            transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
        }
        .staff-card:hover {
            transform: translateY(-2px);
            background: rgba(255, 255, 255, 0.86);
            box-shadow: 0 18px 40px rgba(2, 62, 95, 0.14);
        }
        .staff-card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            margin-bottom: 12px;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(0, 119, 182, 0.12);
        }
        .staff-card-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 34px;
            height: 34px;
            padding: 0 10px;
            border-radius: 999px;
            background: rgba(0, 119, 182, 0.12);
            color: var(--primary-dark);
            font-weight: 850;
            font-size: 0.9rem;
        }
        .staff-card-type {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 10px;
            border-radius: 999px;
            background: rgba(230, 246, 252, 0.84);
            color: var(--primary-dark);
            font-size: 0.74rem;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.02em;
        }
        .staff-info {
            display: flex;
            flex-direction: column;
            gap: 8px;
            flex: 1;
        }
        .staff-info-item {
            font-size: 0.9rem;
            color: var(--text-main);
            line-height: 1.45;
            overflow-wrap: anywhere;
        }
        .staff-info-item strong {
            display: block;
            color: var(--primary-dark);
            font-weight: 700;
            font-size: 0.76rem;
            margin-bottom: 2px;
        }
        .staff-info-item small {
            color: var(--text-muted);
            font-size: 0.85rem;
        }
        .action-buttons {
            display: flex;
            gap: 8px;
            justify-content: flex-end;
            margin-top: 14px;
            padding-top: 12px;
            border-top: 1px solid rgba(0, 119, 182, 0.10);
        }
        .btn-edit {
            background: linear-gradient(90deg, #f39c12, #e67e22);
            color: #fff;
            padding: 8px;
            width: 36px;
            height: 36px;
            border-radius: 8px;
            font-size: 0.9rem;
            font-weight: 700;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .btn-edit:hover {
            transform: translateY(-1px);
            filter: brightness(1.04);
        }
        .btn-delete {
            background: linear-gradient(90deg, var(--danger), #c0392b);
            color: #fff;
            padding: 8px;
            width: 36px;
            height: 36px;
            border-radius: 8px;
            font-size: 0.9rem;
            font-weight: 700;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .btn-delete:hover {
            transform: translateY(-1px);
            filter: brightness(1.04);
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: var(--text-muted);
        }
        .empty-state i { font-size: 3rem; margin-bottom: 15px; opacity: 0.5; }

        .hidden-field { display: none; }
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }
        @media (max-width: 1280px) {
            .staff-card-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
        }
        @media (max-width: 900px) {
            .staff-card-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
        }
        @media (max-width: 560px) {
            .staff-card-grid { grid-template-columns: 1fr; }
            .table-container { padding: 18px; }
        }
    </style>
</head>
<body class="role-<?= htmlspecialchars($role) ?>">

    <aside class="sidebar" id="sidebar">
        <button class="sidebar-toggle" id="sidebarToggle" title="Tutup/Buka Menu">
            <i class="fas fa-chevron-left"></i>
        </button>
        <div class="sidebar-header">
            <img src="mainpp.png" alt="Logo MAINPP">
            <h3>MAINPP WORKSPACE</h3>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'Senarai_Kakitangan.php'); ?>
        </ul>
    </aside>

    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-users"></i> SENARAI KAKITANGAN</h2>
            <?php renderTopBarUserMenu($conn, $role, 'Senarai_Kakitangan.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Senarai Kakitangan', 'url' => 'Senarai_Kakitangan.php', 'current' => true]
        ]);
        ?>

        <!-- Filter Buttons -->
        <div class="filter-buttons">
            <button class="filter-btn <?= $filter_type === 'MAINPP' ? 'active' : '' ?>" onclick="setFilter('MAINPP')">
                <i class="fas fa-building"></i> MAINPP
            </button>
            <button class="filter-btn <?= $filter_type === 'AGENSI LUAR' ? 'active' : '' ?>" onclick="setFilter('AGENSI LUAR')">
                <i class="fas fa-external-link-alt"></i> AGENSI LUAR
            </button>
            <button class="filter-btn add-staff" onclick="toggleForm()">
                <i class="fas fa-plus"></i> TAMBAH KAKITANGAN
            </button>
        </div>

        <!-- Welcome Message (shown when no filter is selected) -->
        <?php if (!isset($_GET['filter'])): ?>
        <div class="empty-state" style="margin-top: 40px;">
            <i class="fas fa-hand-pointer"></i>
            <p>Sila pilih jenis kakitangan untuk melihat senarai.</p>
        </div>
        <?php endif; ?>

        <!-- Add/Edit Form -->
        <div class="form-container" id="staffForm" style="display: none;">
            <h3 class="form-title">
                <i class="fas fa-user-plus"></i> 
                <span id="formTitle">Tambah Kakitangan Baru</span>
            </h3>
            <form id="staffFormElement" method="POST" action="staff_save.php">
                <input type="hidden" name="staff_id" id="staff_id" value="">
                <input type="hidden" name="form_mode" id="form_mode" value="create">
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="agency_type">Agensi *</label>
                        <select id="agency_type" name="agency_type" required onchange="toggleAgencyFields()">
                            <option value="">-- Pilih Agensi --</option>
                            <option value="MAINPP">MAINPP</option>
                            <option value="AGENSI LUAR">AGENSI LUAR</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="name">Nama</label>
                        <input type="text" id="name" name="name" placeholder="Masukkan nama kakitangan">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="position">Jawatan *</label>
                        <input type="text" id="position" name="position" required placeholder="Masukkan jawatan">
                    </div>
                    <div class="form-group" id="department_group">
                        <label for="department" id="department_label">Bahagian</label>
                        <input type="text" id="department" name="department" placeholder="Masukkan bahagian">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group hidden-field" id="agency_group">
                        <label for="agency">Nama Agensi *</label>
                        <input type="text" id="agency" name="agency" required placeholder="Masukkan nama agensi">
                    </div>
                    <div class="form-group hidden-field" id="address_group">
                        <label for="address">Alamat *</label>
                        <textarea id="address" name="address" required placeholder="Masukkan alamat"></textarea>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Simpan
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="toggleForm()">
                        <i class="fas fa-times"></i> Batal
                    </button>
                </div>
            </form>
        </div>

        <!-- Staff Table -->
        <div class="table-container" id="staffTable" style="display: <?= isset($_GET['filter']) ? 'block' : 'none' ?>;">
            <h3 class="table-title">
                <i class="fas fa-list"></i> Senarai Kakitangan 
                <span style="font-size: 0.9rem; font-weight: 600; color: var(--text-muted); margin-left: auto;">
                    <?= count($staff_list) ?> rekod
                </span>
            </h3>
            <?php if (empty($staff_list)): ?>
                <div class="empty-state">
                    <i class="fas fa-users"></i>
                    <p>Tiada data kakitangan untuk dipaparkan.</p>
                </div>
            <?php else: ?>
                <div class="staff-card-grid">
                    <?php foreach ($staff_list as $index => $staff): ?>
                    <article class="staff-card">
                        <div class="staff-card-header">
                            <span class="staff-card-number"><?= $index + 1 ?></span>
                            <span class="staff-card-type">
                                <i class="fas <?= ($staff['agency_type'] ?? '') === 'MAINPP' ? 'fa-building' : 'fa-external-link-alt' ?>"></i>
                                <?= htmlspecialchars($staff['agency_type'] ?? '-') ?>
                            </span>
                        </div>
                        <div class="staff-info">
                            <?php if ($staff['agency_type'] === 'MAINPP'): ?>
                                <div class="staff-info-item">
                                    <strong>Nama</strong>
                                    <?= htmlspecialchars($staff['name'] ?? '-') ?>
                                </div>
                                <div class="staff-info-item">
                                    <strong>Jawatan</strong>
                                    <?= htmlspecialchars($staff['position'] ?? '-') ?>
                                </div>
                                <div class="staff-info-item">
                                    <strong>Bahagian</strong>
                                    <?= htmlspecialchars($staff['department'] ?? '-') ?>
                                </div>
                            <?php else: ?>
                                <div class="staff-info-item">
                                    <strong>Nama</strong>
                                    <?= htmlspecialchars($staff['name'] ?? '-') ?>
                                </div>
                                <div class="staff-info-item">
                                    <strong>Jawatan</strong>
                                    <?= htmlspecialchars($staff['position'] ?? '-') ?>
                                </div>
                                <div class="staff-info-item">
                                    <strong>Bahagian</strong>
                                    <?= htmlspecialchars($staff['department'] ?? '-') ?>
                                </div>
                                <div class="staff-info-item">
                                    <strong>Agensi</strong>
                                    <?= htmlspecialchars($staff['agency'] ?? '-') ?>
                                </div>
                                <div class="staff-info-item">
                                    <strong>Alamat</strong>
                                    <?= !empty($staff['address']) ? nl2br(htmlspecialchars($staff['address'])) : '-' ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="action-buttons">
                            <button class="btn-edit" onclick="editStaff(<?= $staff['id'] ?>)" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn-delete" onclick="deleteStaff(<?= $staff['id'] ?>)" title="Delete">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <div class="page-footer">
            Hakcipta Terpelihara &copy; <?= date('Y') ?> Majlis Agama Islam Negeri Pulau Pinang.
        </div>
    </main>

    <script>
        function toggleForm() {
            const form = document.getElementById('staffForm');
            const table = document.getElementById('staffTable');
            
            if (form.style.display === 'none' || form.style.display === '') {
                form.style.display = 'block';
                table.style.display = 'none';
            } else {
                form.style.display = 'none';
                table.style.display = 'block';
                resetForm();
            }
        }

        function resetForm() {
            document.getElementById('staffFormElement').reset();
            document.getElementById('staff_id').value = '';
            document.getElementById('form_mode').value = 'create';
            document.getElementById('formTitle').textContent = 'Tambah Kakitangan Baru';
            document.getElementById('staffFormElement').setAttribute('action', 'staff_save.php');
            toggleAgencyFields();
        }

        function toggleAgencyFields() {
            const agencyType = document.getElementById('agency_type').value;
            const departmentGroup = document.getElementById('department_group');
            const agencyGroup = document.getElementById('agency_group');
            const addressGroup = document.getElementById('address_group');
            const departmentLabel = document.getElementById('department_label');
            const departmentInput = document.getElementById('department');
            const agencyInput = document.getElementById('agency');
            const addressInput = document.getElementById('address');

            if (agencyType === 'MAINPP') {
                departmentGroup.classList.remove('hidden-field');
                agencyGroup.classList.add('hidden-field');
                addressGroup.classList.add('hidden-field');
                departmentLabel.textContent = 'Bahagian *';
                departmentInput.required = true;
                agencyInput.required = false;
                addressInput.required = false;
            } else if (agencyType === 'AGENSI LUAR') {
                departmentGroup.classList.remove('hidden-field');
                agencyGroup.classList.remove('hidden-field');
                addressGroup.classList.remove('hidden-field');
                departmentLabel.textContent = 'Bahagian';
                departmentInput.required = false;
                agencyInput.required = true;
                addressInput.required = true;
            } else {
                departmentGroup.classList.remove('hidden-field');
                agencyGroup.classList.add('hidden-field');
                addressGroup.classList.add('hidden-field');
                departmentLabel.textContent = 'Bahagian';
                departmentInput.required = false;
                agencyInput.required = false;
                addressInput.required = false;
            }
        }

        function setFilter(filterType) {
            const form = document.getElementById('staffForm');
            const table = document.getElementById('staffTable');
            
            form.style.display = 'none';
            table.style.display = 'block';
            
            const url = new URL(window.location.href);
            url.searchParams.set('filter', filterType);
            window.location.href = url.toString();
        }

        function editStaff(staffId) {
            fetch('staff_fetch.php?id=' + staffId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const staff = data.staff;
                        document.getElementById('staff_id').value = staff.id;
                        document.getElementById('form_mode').value = 'edit';
                        document.getElementById('agency_type').value = staff.agency_type;
                        document.getElementById('name').value = staff.name;
                        document.getElementById('position').value = staff.position;
                        document.getElementById('department').value = staff.department || '';
                        document.getElementById('agency').value = staff.agency || '';
                        document.getElementById('address').value = staff.address || '';
                        
                        document.getElementById('formTitle').textContent = 'Kemaskini Maklumat Kakitangan';
                        document.getElementById('staffFormElement').setAttribute('action', 'staff_update.php');
                        
                        toggleAgencyFields();
                        
                        const form = document.getElementById('staffForm');
                        const table = document.getElementById('staffTable');
                        form.style.display = 'block';
                        table.style.display = 'none';
                    } else {
                        alert('Gagal memuatkan data kakitangan.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Ralat berlaku semasa memuatkan data.');
                });
        }

        function deleteStaff(staffId) {
            if (confirm('Adakah you pasti ingin memadamkan rekod ini?')) {
                const formData = new FormData();
                formData.append('staff_id', staffId);
                
                fetch('staff_delete.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.href = 'Senarai_Kakitangan.php?filter=<?= $filter_type ?>&success=deleted';
                    } else {
                        alert('Gagal memadamkan rekod: ' + (data.message || 'Ralat tidak diketahui'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Ralat berlaku semasa memadamkan rekod.');
                });
            }
        }

        document.getElementById('staffFormElement').addEventListener('submit', function(e) {
            const agencyType = document.getElementById('agency_type').value;
            const position = document.getElementById('position').value.trim();
            const staffId = document.getElementById('staff_id').value.trim();

            if (staffId !== '') {
                document.getElementById('form_mode').value = 'edit';
                this.setAttribute('action', 'staff_update.php');
            } else {
                document.getElementById('form_mode').value = 'create';
                this.setAttribute('action', 'staff_save.php');
            }

            if (!agencyType) {
                e.preventDefault();
                alert('Sila pilih agensi.');
                return;
            }

            if (!position) {
                e.preventDefault();
                alert('Sila masukkan jawatan.');
                return;
            }

            if (agencyType === 'MAINPP') {
                const department = document.getElementById('department').value.trim();
                
                if (!department) {
                    e.preventDefault();
                    alert('Sila masukkan bahagian.');
                    return;
                }
            }

            if (agencyType === 'AGENSI LUAR') {
                const agency = document.getElementById('agency').value.trim();
                const address = document.getElementById('address').value.trim();
                
                if (!agency) {
                    e.preventDefault();
                    alert('Sila masukkan nama agensi.');
                    return;
                }
                
                if (!address) {
                    e.preventDefault();
                    alert('Sila masukkan alamat.');
                    return;
                }
            }
        });

        const sidebar = document.getElementById('sidebar');
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => sidebar.classList.toggle('collapsed'));
        }
        if (window.innerWidth < 992) sidebar.classList.add('collapsed');

        document.querySelectorAll('.sidebar-menu .dropdown-toggle, .dropdown-toggle').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const dropdown = this.parentElement;
                const isActive = dropdown.classList.contains('active');
                document.querySelectorAll('.sidebar-menu .dropdown, .dropdown').forEach(item => {
                    if (item !== dropdown) item.classList.remove('active');
                });
                dropdown.classList.toggle('active', !isActive);
            });
        });
    </script>
</body>
</html>
