<?php
/**
 * API endpoint to unassign a member
 * 
 * POST Parameters:
 * - assignment_id: ID of the assignment to remove
 * - reason: Optional reason for unassignment
 */

// 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 member unassignments
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'message' => 'Error unassigning member'
];

// Handle request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Get POST data
        $postData = json_decode(file_get_contents('php://input'), true);
        
        // If POST data is empty, try regular POST
        if (empty($postData)) {
            $postData = $_POST;
        }
        
        // Validate required fields
        if (!isset($postData['assignment_id']) || empty($postData['assignment_id'])) {
            throw new Exception("Field 'assignment_id' is required");
        }
        
        // Get unassignment details
        $assignmentId = (int)$postData['assignment_id'];
        $reason = isset($postData['reason']) ? $postData['reason'] : '';
        $status = isset($postData['status']) ? $postData['status'] : 'cancelled';
        
        // Validate status
        if (!in_array($status, ['cancelled', 'completed'])) {
            $status = 'cancelled';
        }
        
        // Get current admin ID
        $adminId = $_SESSION['admin_id'];
        
        // Create assignment service
        $assignmentService = new AssignmentService();
        
        // Unassign member
        $result = $assignmentService->unassignMember($assignmentId, $adminId, $reason, $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 POST.';
}

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