<?php
/**
 * modules/users/list_users.php
 * PSO ERMDS Corporate Theme Adapted for WIMAS
 */

// 1. FETCH GLOBAL PERMISSIONS (Calculated by index.php Gatekeeper)
$p = $GLOBALS['my_privs'] ?? ['can_view' => 0, 'can_add' => 0, 'can_edit' => 0, 'can_del' => 0];

// SUPER ADMIN BYPASS
if (in_array(1, $_SESSION['all_role_ids'] ?? [])) {
    $p = ['can_view' => 1, 'can_add' => 1, 'can_edit' => 1, 'can_del' => 1];
}

// 2. FETCH DATA (Shows both Active and Suspended records)
$sql = "SELECT u.USER_ID, u.USERNAME, u.FULL_NAME, u.STATUS, u.LAST_LOGIN, 
               GROUP_CONCAT(r.ROLE_NAME SEPARATOR ', ') as ASSIGNED_ROLES
        FROM TBL_USERS u
        LEFT JOIN TBL_USER_ROLES ur ON u.USER_ID = ur.USER_ID
        LEFT JOIN TBL_ROLES r ON ur.ROLE_ID = r.ROLE_ID
        GROUP BY u.USER_ID
        ORDER BY u.FULL_NAME ASC";
$result = $db->query($sql);
?>

<style>
    /* WIMAS Theme adaptations based on PSO styling */
    .thead-wimas { background-color: #F4F7FA; color: #343a40; border-bottom: 2px solid #007bff; }
    .btn-white { background-color: #ffffff; }
    .dataTables_filter input { border-radius: 20px; border: 1px solid #ced4da; padding: 5px 12px; width: 250px !important; }
</style>

<div class="p-3">
    <section class="content-header px-0">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="font-weight-bold text-primary"><i class="fas fa-users mr-2"></i>System Users</h1>
                </div>
                <div class="col-sm-6 text-right">
                    <?php if($p['can_add'] == 1): ?>
                    <a href="index.php?s=<?php echo encrypt_url('mod=users&page=add_users'); ?>" class="btn btn-primary shadow-sm">
                        <i class="fas fa-user-plus mr-1"></i> Register New User
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </section>

    <section class="content px-0">
        <div class="container-fluid">
            <div class="card card-outline card-primary shadow-sm" style="border-top: 4px solid #007bff;">
                <div class="card-body p-0">
                    <div class="table-responsive p-3">
                        <table id="usersTable" class="table table-hover table-striped mb-0" style="font-size: 0.9rem;">
                            <thead class="thead-wimas">
                                <tr>
                                    <th width="5%" class="pl-3">#</th>
                                    <th>Full Name</th>
                                    <th>Username</th>
                                    <th>Assigned Roles</th>
                                    <th>Last Login</th>
                                    <th class="text-center">Status</th>
                                    
                                    <!-- Only show Management column if user has View, Edit, or Delete rights -->
                                    <?php if($p['can_view'] == 1 || $p['can_edit'] == 1 || $p['can_del'] == 1): ?>
                                        <th width="12%" class="text-center no-export">Management</th>
                                    <?php endif; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $i=1; while($row = mysqli_fetch_assoc($result)): ?>
                                <tr>
                                    <td class="pl-3 align-middle text-muted"><?php echo $i++; ?></td>
                                    <td class="align-middle font-weight-bold text-dark"><?php echo htmlspecialchars($row['FULL_NAME']); ?></td>
                                    <td class="align-middle text-primary">@<?php echo htmlspecialchars($row['USERNAME']); ?></td>
                                    <td class="align-middle">
                                        <?php 
                                            if ($row['ASSIGNED_ROLES']) {
                                                $roles = explode(', ', $row['ASSIGNED_ROLES']);
                                                foreach($roles as $role) {
                                                    echo '<span class="badge badge-info shadow-sm mr-1">'.htmlspecialchars($role).'</span>';
                                                }
                                            } else {
                                                echo '<span class="text-muted"><i>No Roles Assigned</i></span>';
                                            }
                                        ?>
                                    </td>
                                    <td class="align-middle text-muted">
                                        <?php echo $row['LAST_LOGIN'] ? date('d-M-Y h:i A', strtotime($row['LAST_LOGIN'])) : 'Never Logged In'; ?>
                                    </td>
                                    <td class="text-center align-middle">
                                        <span class="badge <?php echo ($row['STATUS'] == 'ACTIVE') ? 'badge-success' : 'badge-secondary'; ?> px-3 py-1 shadow-sm">
                                            <?php echo htmlspecialchars($row['STATUS']); ?>
                                        </span>
                                    </td>
                                    
                                    <?php if($p['can_view'] == 1 || $p['can_edit'] == 1 || $p['can_del'] == 1): ?>
                                    <td class="text-center align-middle no-export">
                                        <div class="btn-group shadow-sm">
                                            
                                            <!-- VIEW BUTTON -->
                                            <?php if($p['can_view'] == 1): ?>
                                            <a href="index.php?s=<?php echo encrypt_url('mod=users&page=view_users&id='.$row['USER_ID']); ?>" 
                                               class="btn btn-sm btn-white border text-info" title="View Profile" data-toggle="tooltip">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <?php endif; ?>

                                            <!-- EDIT BUTTON -->
                                            <?php if($p['can_edit'] == 1): ?>
                                            <a href="index.php?s=<?php echo encrypt_url('mod=users&page=edit_users&id='.$row['USER_ID']); ?>" 
                                               class="btn btn-sm btn-white border text-primary" title="Edit User" data-toggle="tooltip">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <?php endif; ?>

                                            <!-- TOGGLE STATUS (DELETE/RESTORE) BUTTON -->
                                            <?php if($p['can_del'] == 1 && $row['USER_ID'] != $_SESSION['user_id']): ?>
                                                <?php
                                                    $is_active = ($row['STATUS'] == 'ACTIVE');
                                                    $btn_class = $is_active ? 'text-danger' : 'text-success';
                                                    $icon      = $is_active ? 'fa-user-slash' : 'fa-user-check';
                                                    $tooltip   = $is_active ? 'Suspend User' : 'Activate User';
                                                    $confirm   = $is_active ? 'Are you sure you want to suspend this user account?' : 'Restore this user account to active status?';
                                                ?>
                                                <a href="index.php?s=<?php echo encrypt_url('mod=users&page=delete_users&id='.$row['USER_ID'].'&action='.($is_active ? 'suspend' : 'activate')); ?>"
                                                   class="btn btn-sm btn-white border <?php echo $btn_class; ?>"
                                                   onclick="return confirm('<?php echo $confirm; ?>');"
                                                   title="<?php echo $tooltip; ?>" data-toggle="tooltip">
                                                    <i class="fas <?php echo $icon; ?>"></i>
                                                </a>
                                            <?php endif; ?>

                                        </div>
                                    </td>
                                    <?php endif; ?>
                                    
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Scripts placed at the bottom for Datatables and Tooltips -->
<script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="assets/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="assets/plugins/datatables-bs4/css/dataTables.bootstrap4.min.js">

<script>
window.addEventListener('load', function() {
    if (window.jQuery && $.fn.DataTable) {
        // Initialize AdminLTE Tooltips
        $('[data-toggle="tooltip"]').tooltip(); 
        
        // Initialize DataTable
        $('#usersTable').DataTable({
            "responsive": true,
            "autoWidth": false,
            "order": [[1, "asc"]], // Sort by Full Name by default
            "columnDefs": [
                { "orderable": false, "targets": "no-export" } // Disable sorting on Management column
            ],
            "language": {
                "search": "<strong>Quick Filter:</strong>",
                "lengthMenu": "Show _MENU_ entries"
            }
        });
    }
});
</script>