<?php
// -------------------------------------------------------------------
// DETACHED MODULE: EMPLOYEES POPULATION FILTERING
// Handles multi-department lookups and filters out cross-listed managers.
// -------------------------------------------------------------------

if (!isset($conn) || !isset($departments) || !isset($userRole) || !isset($userDeptId) || !isset($loggedInEmployeeId)) {
    die("Core dependency structural configurations missing.");
}

$employees = [];
// Use a dedicated variable name for this file's own prepared statement --
// $stmt is a very generic name, and since this file is require()'d (sharing
// its parent script's variable scope, not an isolated one), reusing $stmt
// here collided with an already-closed $stmt left over from earlier in
// department_schedule.php whenever this file's own query didn't happen to
// use a prepared statement (the "else" branch below uses $conn->query()
// directly). That stale, already-closed object is what caused
// "mysqli_stmt object is already closed" when the closing code ran.
$filterStmt = null;

if ($userRole === 'staff') {
    // Plain staff only ever see their own row, never a coworker's.
    $filterStmt = $conn->prepare("SELECT id, name, department_id FROM employees WHERE id = ?");
    $filterStmt->bind_param("i", $loggedInEmployeeId);
    $filterStmt->execute();
    $res = $filterStmt->get_result();
} elseif ($userRole === 'manager' || $userRole === 'supervisor') {
    $filterStmt = $conn->prepare("SELECT id, name, department_id FROM employees WHERE FIND_IN_SET(?, department_id) > 0 ORDER BY name");
    $filterStmt->bind_param("i", $userDeptId);
    $filterStmt->execute();
    $res = $filterStmt->get_result();
} else {
    $res = $conn->query("SELECT id, name, department_id FROM employees ORDER BY name");
}

while ($row = $res->fetch_assoc()) {
    $assignedDepts = !empty($row['department_id']) ? explode(',', $row['department_id']) : [];
    
    // Step 1: Pre-scan to check if employee is explicitly assigned to a Managers department
    $belongsToManagerDept = false;
    $managerDeptIdKey = null;
    
    foreach ($assignedDepts as $rawDeptId) {
        $checkId = intval(trim($rawDeptId));
        if (isset($departments[$checkId])) {
            $deptNameClean = strtolower(trim($departments[$checkId]['name']));
            if ($deptNameClean === 'managers' || $deptNameClean === 'manager') {
                $belongsToManagerDept = true;
                $managerDeptIdKey = $checkId;
                break; 
            }
        }
    }
    
    // Step 2: Distribute to layout buckets safely
    foreach ($assignedDepts as $rawDeptId) {
        $deptId = intval(trim($rawDeptId));
        
        if ($deptId <= 0 || !isset($departments[$deptId])) {
            continue;
        }
        
        // If they belong to the Manager group, hide them from any loop that isn't the manager bucket
        if ($belongsToManagerDept && $deptId !== $managerDeptIdKey) {
            continue;
        }
        
        if (!isset($employees[$deptId])) {
            $employees[$deptId] = [];
        }
        
        $employees[$deptId][] = $row;
    }
}

if ($filterStmt !== null) {
    $filterStmt->close();
}

// Post-sort hierarchy layers if looking through a specific manager/supervisor branch viewport
if (($userRole === 'manager' || $userRole === 'supervisor') && isset($employees[$userDeptId])) {
    usort($employees[$userDeptId], function ($a, $b) use ($loggedInEmployeeId) {
        if ($a['id'] == $loggedInEmployeeId) return -1;
        if ($b['id'] == $loggedInEmployeeId) return 1;
        return strcmp($a['name'], $b['name']);
    });
}