<?php
/**
 * API endpoint to assign a member
 * 
 * POST Parameters:
 * - member_id: ID of the member to assign
 * - assigned_to_id: ID of the admin or group to assign to
 * - assigned_to_type: Type of assignment ('admin' or 'group')
 * - notes: Optional notes about the assignment
 */

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

// Default response structure
$response = [
    'success' => false,
    'message' => 'Error assigning 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
        $requiredFields = ['member_id', 'assigned_to'];
        foreach ($requiredFields as $field) {
            if (!isset($postData[$field]) || empty($postData[$field])) {
                throw new Exception("Field '$field' is required");
            }
        }
        
        // Get assignment details
        $memberId = (int)$postData['member_id'];
        $assignedTo = (int)$postData['assigned_to'];
        $assignmentType = isset($postData['assignment_type']) ? $postData['assignment_type'] : 'review';
        $priority = isset($postData['priority']) ? $postData['priority'] : 'normal';
        $notes = isset($postData['notes']) ? $postData['notes'] : '';
        $dueDate = isset($postData['due_date']) ? $postData['due_date'] : null;
        
        // Validate assignment_type
        if (!in_array($assignmentType, ['review', 'approval', 'verification', 'follow_up'])) {
            throw new Exception("Invalid assignment_type. Must be one of: review, approval, verification, follow_up");
        }
        
        // Validate priority
        if (!in_array($priority, ['low', 'normal', 'high', 'urgent'])) {
            throw new Exception("Invalid priority. Must be one of: low, normal, high, urgent");
        }
        
        // Get current admin ID
        $adminId = $_SESSION['admin_id'];
        
        // Create assignment service
        $assignmentService = new AssignmentService();
        
        // Assign member
        $result = $assignmentService->assignMember(
            $memberId, 
            $assignedTo, 
            $adminId,      // admin who is making the assignment
            $assignmentType, 
            $priority, 
            $notes, 
            $dueDate
        );
        
        // 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;
