<?php
require_once '../../config/config.php';
header('Content-Type: application/json');
try { 
    if(!isset($_GET['id'])){ echo json_encode(null); exit; } 
    $id=(int)$_GET['id']; 
    
    // Get staff with roles
    $stmt=$pdo->prepare('
        SELECT s.*, GROUP_CONCAT(srt.role_name) as role_names 
        FROM staff s 
        LEFT JOIN staff_roles sr ON s.staff_id = sr.staff_id 
        LEFT JOIN staff_role_types srt ON sr.role_id = srt.role_id
        WHERE s.staff_id=? 
        GROUP BY s.staff_id
    '); 
    $stmt->execute([$id]); 
    $staff = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if($staff) {
        // Convert role_names string to array
        $staff['roles'] = $staff['role_names'] ? explode(',', $staff['role_names']) : [];
        unset($staff['role_names']); // Remove the temporary field
        
        // For backward compatibility, set single role field
        $staff['role'] = $staff['roles'][0] ?? 'Internal';
        // external_college_name may not exist; keep if present
    }
    
    echo json_encode($staff ?: null); 
} catch(Throwable $e){ 
    http_response_code(500); 
    echo json_encode(['error'=>$e->getMessage()]); 
}
?>


