<?php
/**
 * API endpoint to transfer assignments
 * 
 * POST Parameters:
 * - from_id: Source admin/group ID
 * - from_type: Source type ('admin' or 'group')
 * - to_id: Target admin/group ID
 * - to_type: Target type ('admin' or 'group')
 * - notes: Optional notes about the transfer
 */

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

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

// 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 = ['from_id', 'from_type', 'to_id', 'to_type'];
        foreach ($requiredFields as $field) {
            if (!isset($postData[$field]) || empty($postData[$field])) {
                throw new Exception("Field '$field' is required");
            }
        }
        
        // Validate types
        if (!in_array($postData['from_type'], ['admin', 'group'])) {
            throw new Exception("Invalid from_type. Must be 'admin' or 'group'");
        }
        
        if (!in_array($postData['to_type'], ['admin', 'group'])) {
            throw new Exception("Invalid to_type. Must be 'admin' or 'group'");
        }
        
        // Get transfer details
        $fromId = (int)$postData['from_id'];
        $fromType = $postData['from_type'];
        $toId = (int)$postData['to_id'];
        $toType = $postData['to_type'];
        $notes = isset($postData['notes']) ? $postData['notes'] : '';
        
        // Get current admin ID
        $adminId = $_SESSION['admin_id'];
        
        // Create assignment service
        $assignmentService = new AssignmentService();
        
        // Transfer assignments
        $result = $assignmentService->transferAssignments($fromId, $fromType, $toId, $toType, $adminId, $notes);
        
        // 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;
