<?php
/**
 * Get Users API (Superuser Only)
 */
require_once '../guard.php';
require_once __DIR__ . '/../../includes/database.php';

header('Content-Type: application/json');

// Only superusers can access user management
if ($_SESSION['user_role'] !== 'superuser') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Superuser access required']);
    exit();
}

try {
    $db = Database::getInstance();
    $conn = $db->getConnection();
    
    $stmt = $conn->prepare("
        SELECT u.*, un.name as unit_name 
        FROM users u 
        LEFT JOIN units un ON u.unit_id = un.id 
        ORDER BY u.full_name ASC
    ");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode(['success' => true, 'users' => $users]);
    
} catch (Exception $e) {
    error_log("Users fetch error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>