<?php
/**
 * KSO Chandigarh Admin Panel
 * Bulk Assignment API Endpoint
 * 
 * This endpoint handles bulk assignment of tasks to multiple members at once
 */

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

// Check authentication
checkAuthentication();

// Initialize response
$response = [
    'success' => false,
    'message' => '',
    'data' => []
];

// Ensure this is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Invalid request method';
    echo json_encode($response);
    exit;
}

// Get database connection
$database = new Database();
$conn = $database->getConnection();

try {
    // Initialize the assignment service
    $assignmentService = new AssignmentService($conn);
    
    // Get POST data
    $member_ids = isset($_POST['member_ids']) ? $_POST['member_ids'] : [];
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $assigned_to = isset($_POST['assigned_to']) ? trim($_POST['assigned_to']) : '';
    $assignment_type = isset($_POST['assignment_type']) ? trim($_POST['assignment_type']) : '';
    $priority = isset($_POST['priority']) ? trim($_POST['priority']) : '';
    $due_date = isset($_POST['due_date']) ? trim($_POST['due_date']) : '';
    $send_email = isset($_POST['send_email']) ? (bool)$_POST['send_email'] : false;
    
    // Validate inputs
    if (empty($member_ids) || !is_array($member_ids)) {
        $response['message'] = 'No members selected for assignment';
        echo json_encode($response);
        exit;
    }
    
    if (empty($title)) {
        $response['message'] = 'Assignment title is required';
        echo json_encode($response);
        exit;
    }
    
    if (empty($assigned_to)) {
        $response['message'] = 'Assigned to is required';
        echo json_encode($response);
        exit;
    }
    
    if (empty($assignment_type)) {
        $response['message'] = 'Assignment type is required';
        echo json_encode($response);
        exit;
    }
    
    if (empty($priority)) {
        $response['message'] = 'Priority is required';
        echo json_encode($response);
        exit;
    }
    
    if (empty($due_date)) {
        $response['message'] = 'Due date is required';
        echo json_encode($response);
        exit;
    }
    
    // Process bulk assignments
    $successful = 0;
    $failed = 0;
    $admin_id = $_SESSION['admin_id'];
    
    // Start transaction
    $conn->beginTransaction();
    
    foreach ($member_ids as $member_id) {
        // Create assignment data array
        $assignmentData = [
            'title' => $title,
            'description' => $description,
            'member_id' => $member_id,
            'assigned_to' => $assigned_to,
            'assignment_type' => $assignment_type,
            'priority' => $priority,
            'status' => 'active',
            'due_date' => $due_date,
            'created_by' => $admin_id
        ];
        
        // Attempt to create assignment
        $result = $assignmentService->createAssignment($assignmentData);
        
        if ($result) {
            $successful++;
            
            // Send email notification if requested
            if ($send_email) {
                // Include email service
                require_once '../../services/EmailService.php';
                $emailService = new EmailService();
                
                // Get member and admin details
                $memberDetails = $assignmentService->getMemberDetails($member_id);
                $adminDetails = $assignmentService->getAdminDetails($assigned_to);
                
                if ($memberDetails && $adminDetails) {
                    // Send email to assigned admin
                    $emailService->sendAssignmentNotification(
                        $adminDetails['email'],
                        $adminDetails['name'],
                        $title,
                        $description,
                        $memberDetails['name'],
                        $priority,
                        $due_date
                    );
                }
            }
        } else {
            $failed++;
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    // Prepare response
    $response['success'] = true;
    $response['message'] = "Bulk assignment process completed";
    $response['data'] = [
        'successful' => $successful,
        'failed' => $failed
    ];
    
} catch (Exception $e) {
    // Rollback transaction on error
    if ($conn->inTransaction()) {
        $conn->rollBack();
    }
    
    $response['message'] = 'Error processing bulk assignments: ' . $e->getMessage();
    
    // Log the error
    error_log('Bulk Assignment Error: ' . $e->getMessage());
} finally {
    // Close the database connection
    $conn = null;
}

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