<?php
/**
 * API endpoint to list assigned members
 * 
 * GET Parameters:
 * - assigned_to_id: ID of the admin or group
 * - assigned_to_type: Type ('admin' or 'group')
 * - active_only: Get only active assignments (default: true)
 */

// Include dependencies
require_once '../../config/database.php';
require_once '../../config/auth_enhanced.php';
require_once '../../services/assignment/AssignmentService.php';

use Services\Assignment\AssignmentService;

// Require admin access for viewing assigned members
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'data' => [],
    'message' => 'Error retrieving assigned members'
];

// Handle request
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        // Validate required parameters
        $requiredParams = ['assigned_to'];
        foreach ($requiredParams as $param) {
            if (!isset($_GET[$param]) || empty($_GET[$param])) {
                throw new Exception("Parameter '$param' is required");
            }
        }
        
        // Get parameters
        $assignedTo = (int)$_GET['assigned_to'];
        $status = isset($_GET['status']) ? $_GET['status'] : 'active';
        
        // Validate status
        if (!in_array($status, ['active', 'completed', 'cancelled', 'overdue', 'all'])) {
            throw new Exception("Invalid status. Must be one of: active, completed, cancelled, overdue, all");
        }
        
        // Create assignment service
        $assignmentService = new AssignmentService();
        
        // Get assigned members
        $result = $assignmentService->getAssignedMembers($assignedTo, $status);
        
        // Return response
        $response = $result;
        
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
    }
} else {
    // Method not allowed
    http_response_code(405);
    $response['message'] = 'Method not allowed. Use GET.';
}

// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);
exit;
