<?php
require_once __DIR__ . '/includes/layout.php';
require_login();
require_roles(['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']);
require_department_access($conn, 'senarai_pengguna', 'read');

$search = trim($_GET['search'] ?? '');
$users = [];
$canUpdateUsers = has_department_access($conn, 'senarai_pengguna', 'update');

if ($search !== '') {
    $normalizedIcSearch = preg_replace('/\D+/', '', $search);
    if ($normalizedIcSearch !== '' && strlen($normalizedIcSearch) >= 6) {
        $searchLogKey = 'last_ic_search_log';
        $currentLogSignature = $normalizedIcSearch . '|' . current_user_id();
        if (($_SESSION[$searchLogKey] ?? '') !== $currentLogSignature) {
            add_current_user_log($conn, 'Carian IC dalam Senarai Pengguna: ' . $search);
            $_SESSION[$searchLogKey] = $currentLogSignature;
        }
    }
    $searchLike = '%' . $search . '%';
    $stmt = $conn->prepare("
        SELECT id, nama, ic, emel, role, jabatan, approval_status, account_status, deactivated_at, created_at
        FROM users
        WHERE ic LIKE ?
           OR nama LIKE ?
           OR role LIKE ?
           OR jabatan LIKE ?
           OR approval_status LIKE ?
           OR account_status LIKE ?
        ORDER BY created_at DESC, id DESC
    ");
    $stmt->bind_param('ssssss', $searchLike, $searchLike, $searchLike, $searchLike, $searchLike, $searchLike);
    $stmt->execute();
    $users = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
} else {
    unset($_SESSION['last_ic_search_log']);
    $result = $conn->query("
        SELECT id, nama, ic, emel, role, jabatan, approval_status, account_status, deactivated_at, created_at
        FROM users
        ORDER BY created_at DESC, id DESC
    ");
    $users = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}

$extraJs = <<<HTML
<script>
function openDropdownMenu(event, button) {
    event.preventDefault();
    event.stopPropagation();
    document.querySelectorAll('.dropdown-menu.show').forEach((menu) => {
        if (!button.closest('.dropdown-form').contains(menu)) {
            menu.classList.remove('show');
        }
    });
    const form = button.closest('.dropdown-form');
    const menu = form ? form.querySelector('.dropdown-menu') : null;
    if (menu) {
        menu.classList.toggle('show');
    }
}

function submitStatusOption(button, targetStatus) {
    const form = button.closest('.dropdown-form');
    const input = form ? form.querySelector('.target-status-input') : null;
    const label = targetStatus === 'active' ? 'Aktif' : 'Tidak Aktif';
    if (!form || !input) {
        return;
    }
    if (!confirm('Adakah anda pasti mahu menukar status pengguna ini kepada ' + label + '?')) {
        return;
    }
    input.value = targetStatus;
    form.submit();
}

function submitRoleOption(button, targetRole) {
    const form = button.closest('.dropdown-form');
    const input = form ? form.querySelector('.target-role-input') : null;
    if (!form || !input) {
        return;
    }
    if (!confirm('Adakah anda pasti mahu menukar role pengguna ini kepada ' + targetRole + '?')) {
        return;
    }
    input.value = targetRole;
    form.submit();
}

document.addEventListener('click', function (event) {
    document.querySelectorAll('.dropdown-menu.show').forEach((menu) => {
        if (!menu.closest('.dropdown-form').contains(event.target)) {
            menu.classList.remove('show');
        }
    });
});
</script>
HTML;

render_layout_start('Senarai Pengguna - Dashboard Audit MAINPP');
?>
<style>
.status-cell { min-width: 150px; }
.role-cell { min-width: 165px; }
.status-stack { display: flex; flex-direction: column; gap: 6px; }
.dropdown-form { margin: 0; position: relative; }
.dropdown-pill {
    position: relative; display: inline-flex; align-items: center; min-width: 118px; border-radius: 999px;
    padding: 7px 28px 7px 10px; border: 1px solid transparent; overflow: hidden;
}
.dropdown-pill.static { padding-right: 10px; }
.dropdown-pill.active { background: #dcfce7; color: #166534; }
.dropdown-pill.inactive { background: #fee2e2; color: #991b1b; }
.dropdown-pill.role-user { background: #eef5ff; color: #0d6efd; }
.dropdown-pill.role-admin { background: #ede9fe; color: #6d28d9; }
.dropdown-pill.role-system { background: #fff7ed; color: #c2410c; }
.dropdown-dot, .dropdown-option-dot {
    width: 10px; height: 10px; border-radius: 50%; margin-right: 8px; flex-shrink: 0;
}
.dropdown-pill.active .dropdown-dot, .dropdown-option-dot.active { background: #166534; }
.dropdown-pill.inactive .dropdown-dot, .dropdown-option-dot.inactive { background: #991b1b; }
.dropdown-pill.role-user .dropdown-dot, .dropdown-option-dot.role-user { background: #0d6efd; }
.dropdown-pill.role-admin .dropdown-dot, .dropdown-option-dot.role-admin { background: #6d28d9; }
.dropdown-pill.role-system .dropdown-dot, .dropdown-option-dot.role-system { background: #c2410c; }
.dropdown-label { font-size: 12px; font-weight: 700; line-height: 1.1; }
.dropdown-arrow-btn {
    position: absolute; right: 0; top: 0; bottom: 0; width: 26px; border: none; background: transparent; color: inherit; cursor: pointer;
}
.dropdown-menu {
    display: none; position: absolute; top: calc(100% + 8px); left: 0; min-width: 118px; background: #fff;
    border: 1px solid #d9e2ec; border-radius: 12px; box-shadow: 0 12px 30px rgba(18,52,88,0.12); padding: 6px; z-index: 20;
}
.dropdown-menu.show { display: block; }
.dropdown-option-btn {
    width: 100%; border: none; background: transparent; border-radius: 10px; padding: 8px 10px; display: flex;
    align-items: center; gap: 8px; font-size: 12px; font-weight: 700; text-align: left; cursor: pointer;
}
.dropdown-option-btn:hover { background: #f8fbff; }
.status-note { font-size: 10px; color: #92400e; font-weight: 600; }
.action-stack {
    display: inline-flex;
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 14px;
    border-radius: 999px;
    font-size: 14px;
    font-weight: 700;
    text-decoration: none;
    white-space: nowrap;
}
.action-btn.view-btn {
    background: #eef5ff;
    color: #0d6efd;
}
.action-btn.edit-btn {
    background: #fff7ed;
    color: #c2410c;
}
</style>

<?php if (isset($_GET['success']) && $_GET['success'] === 'status_updated'): ?>
    <div class="status-message status-success">Status pengguna berjaya dikemaskini.</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'role_updated'): ?>
    <div class="status-message status-success">Role pengguna berjaya dikemaskini.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'self_status'): ?>
    <div class="status-message status-danger">Anda tidak boleh menukar status akaun sendiri.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'self_role'): ?>
    <div class="status-message status-danger">Anda tidak boleh menukar role akaun sendiri.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'invalid_role'): ?>
    <div class="status-message status-danger">Role yang dipilih tidak dibenarkan.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'protected_system_admin'): ?>
    <div class="status-message status-danger">Admin Audit tidak dibenarkan mengubah role Pentadbir Sistem.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'approval_required'): ?>
    <div class="status-message status-danger">Pengguna hanya boleh diaktifkan selepas diluluskan.</div>
<?php elseif (isset($_GET['error'])): ?>
    <div class="status-message status-danger">Tindakan tidak berjaya diproses.</div>
<?php endif; ?>

<div class="page-card">
    <h3><i class="fa-solid fa-users"></i> Senarai Pengguna Sistem</h3>
    <form method="GET" class="search-form">
        <div class="search-input-wrap">
            <i class="fa-solid fa-magnifying-glass"></i>
            <input type="text" name="search" class="search-input" placeholder="Cari IC, nama, role, bahagian / unit, status atau status kelulusan" value="<?= htmlspecialchars($search) ?>">
        </div>
        <button type="submit" class="search-btn">Cari</button>
        <a href="senarai_pengguna.php" class="reset-btn">Reset</a>
    </form>
</div>

<div class="table-container">
    <table>
        <thead>
            <tr>
                <th>Bil</th>
                <th>Nama</th>
                <th>Emel</th>
                <th>Role</th>
                <th>Bahagian / Unit</th>
                <th>Status</th>
                <th>Status Kelulusan</th>
                <th>Tarikh Daftar</th>
                <th>Tarikh Deactivate</th>
                <th>Tindakan</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($users)): ?>
                <?php $bil = 1; foreach ($users as $row): ?>
                <?php
                [$approvalLabel, $approvalClass] = approval_badge_meta($row['approval_status'] ?? 'pending');
                $accountStatus = $row['account_status'] ?? 'inactive';
                [$accountLabel, $accountClass] = account_badge_meta($accountStatus);
                $canActivate = ($row['approval_status'] ?? '') === 'active';
                $roleClass = 'role-user';
                if (($row['role'] ?? '') === 'Admin Audit') {
                    $roleClass = 'role-admin';
                } elseif (($row['role'] ?? '') === 'Pentadbir Sistem') {
                    $roleClass = 'role-system';
                }
                $currentManagerRole = current_user_role();
                $allowedRoleTargets = $currentManagerRole === 'Pentadbir Sistem'
                    ? ['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']
                    : ['Pengguna Biasa', 'Admin Audit'];
                $roleOptions = array_values(array_filter($allowedRoleTargets, static function ($role) use ($row) {
                    return $role !== ($row['role'] ?? '');
                }));
                $isCurrentUser = (int) $row['id'] === (int) ($_SESSION['user_id'] ?? 0);
                $isSystemAdminTarget = ($row['role'] ?? '') === 'Pentadbir Sistem';
                $isProtectedSystemAdmin = $currentManagerRole === 'Admin Audit' && $isSystemAdminTarget;
                $canChangeRole = $canUpdateUsers && !$isCurrentUser && !$isProtectedSystemAdmin && !empty($roleOptions);
                ?>
                <tr>
                    <td><?= $bil++ ?></td>
                    <td><strong><?= htmlspecialchars($row['nama']) ?></strong></td>
                    <td><?= htmlspecialchars($row['emel']) ?></td>
                    <td class="role-cell">
                        <?php if ($canChangeRole): ?>
                        <form action="proses_role_pengguna.php" method="POST" class="dropdown-form">
                            <input type="hidden" name="user_id" value="<?= (int) $row['id'] ?>">
                            <input type="hidden" name="target_role" value="" class="target-role-input">
                            <div class="dropdown-pill <?= $roleClass ?>">
                                <span class="dropdown-dot"></span>
                                <span class="dropdown-label"><?= htmlspecialchars($row['role']) ?></span>
                                <button type="button" class="dropdown-arrow-btn" onclick="openDropdownMenu(event, this)">
                                    <i class="fa-solid fa-chevron-down"></i>
                                </button>
                            </div>
                            <div class="dropdown-menu">
                                <?php foreach ($roleOptions as $roleOption): ?>
                                <?php
                                $optionClass = 'role-user';
                                if ($roleOption === 'Admin Audit') {
                                    $optionClass = 'role-admin';
                                } elseif ($roleOption === 'Pentadbir Sistem') {
                                    $optionClass = 'role-system';
                                }
                                ?>
                                <button type="button" class="dropdown-option-btn" onclick="submitRoleOption(this, '<?= htmlspecialchars($roleOption) ?>')">
                                    <span class="dropdown-option-dot <?= $optionClass ?>"></span>
                                    <span><?= htmlspecialchars($roleOption) ?></span>
                                </button>
                                <?php endforeach; ?>
                            </div>
                        </form>
                        <?php else: ?>
                        <div class="dropdown-pill static <?= $roleClass ?>">
                            <span class="dropdown-dot"></span>
                            <span class="dropdown-label"><?= htmlspecialchars($row['role']) ?></span>
                        </div>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($row['jabatan']) ?></td>
                    <td class="status-cell">
                        <div class="status-stack">
                            <?php if ((int) $row['id'] !== (int) ($_SESSION['user_id'] ?? 0)): ?>
                                <?php
                                $nextStatus = $accountStatus === 'active' ? 'inactive' : 'active';
                                $canShowToggle = $accountStatus === 'active' || ($accountStatus === 'inactive' && $canActivate);
                                ?>
                                <?php if ($canUpdateUsers && $canShowToggle): ?>
                                <form action="proses_status_pengguna.php" method="POST" class="dropdown-form">
                                    <input type="hidden" name="user_id" value="<?= (int) $row['id'] ?>">
                                    <input type="hidden" name="target_status" value="" class="target-status-input">
                                    <div class="dropdown-pill <?= $accountStatus === 'active' ? 'active' : 'inactive' ?>">
                                        <span class="dropdown-dot"></span>
                                        <span class="dropdown-label"><?= htmlspecialchars($accountLabel) ?></span>
                                        <button type="button" class="dropdown-arrow-btn" onclick="openDropdownMenu(event, this)">
                                            <i class="fa-solid fa-chevron-down"></i>
                                        </button>
                                    </div>
                                    <div class="dropdown-menu">
                                        <button type="button" class="dropdown-option-btn" onclick="submitStatusOption(this, '<?= htmlspecialchars($nextStatus) ?>')">
                                            <span class="dropdown-option-dot <?= $nextStatus === 'active' ? 'active' : 'inactive' ?>"></span>
                                            <span><?= $nextStatus === 'active' ? 'Aktif' : 'Tidak Aktif' ?></span>
                                        </button>
                                    </div>
                                </form>
                                <?php else: ?>
                                <div class="dropdown-pill static inactive">
                                    <span class="dropdown-dot"></span>
                                    <span class="dropdown-label"><?= htmlspecialchars($accountLabel) ?></span>
                                </div>
                                <small class="status-note">Belum boleh diaktifkan</small>
                                <?php endif; ?>
                            <?php else: ?>
                            <div class="dropdown-pill static <?= $accountStatus === 'active' ? 'active' : 'inactive' ?>">
                                <span class="dropdown-dot"></span>
                                <span class="dropdown-label"><?= htmlspecialchars($accountLabel) ?></span>
                            </div>
                            <small class="field-note">Akaun semasa</small>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td><span class="status-badge <?= $approvalClass ?>"><i class="fa-solid fa-circle"></i><?= htmlspecialchars($approvalLabel) ?></span></td>
                    <td><?= date('d/m/Y h:i A', strtotime($row['created_at'])) ?></td>
                    <td><?= !empty($row['deactivated_at']) ? date('d/m/Y h:i A', strtotime($row['deactivated_at'])) : '-' ?></td>
                    <td>
                        <?php if ((int) $row['id'] !== (int) ($_SESSION['user_id'] ?? 0)): ?>
                        <div class="action-stack">
                            <a href="detail_pengguna.php?id=<?= (int) $row['id'] ?>" class="action-btn view-btn"><i class="fa-solid fa-magnifying-glass"></i> View</a>
                            <?php if ($canUpdateUsers): ?>
                            <a href="edit_pengguna.php?id=<?= (int) $row['id'] ?>" class="action-btn edit-btn"><i class="fa-solid fa-pen"></i> Edit</a>
                            <?php endif; ?>
                        </div>
                        <?php else: ?>
                        <span class="field-note">Akaun semasa</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="10" class="empty-state">Tiada pengguna ditemui untuk carian ini.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>
<?php render_layout_end($extraJs); ?>
