<?php
/**
 * API endpoint for bulk actions on assignments
 * 
 * POST Parameters:
 * - action: The action to perform ('complete', 'cancel', 'delete')
 * - ids: Array of assignment IDs to perform the action on
 */

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

use Services\Assignment\AssignmentService;
use Services\Email\EmailService;

// Require admin access
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'message' => 'Error processing bulk action'
];

// 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;
        }

        // Extract parameters
        $action = isset($postData['action']) ? $postData['action'] : '';
        $ids = isset($postData['ids']) ? $postData['ids'] : [];
        
        // Validate
        if (empty($action)) {
            throw new Exception('No action specified');
        }
        
        if (empty($ids) || !is_array($ids)) {
            throw new Exception('No assignments selected');
        }
        
        // Initialize services
        $assignmentService = new AssignmentService();
        $emailService = new EmailService();
        
        // Process based on action
        $successCount = 0;
        $failureCount = 0;
        
        switch ($action) {
            case 'complete':
                // Mark assignments as completed
                foreach ($ids as $id) {
                    $result = $assignmentService->updateAssignmentStatus(intval($id), 'completed');
                    
                    if ($result['success']) {
                        $successCount++;
                        
                        // Send notification email
                        if (isset($result['assignment']) && $result['assignment']) {
                            $assignment = $result['assignment'];
                            $emailService->sendStatusUpdateNotification(
                                $assignment['assigned_to_email'],
                                $assignment['assigned_to_name'],
                                $assignment['member_name'],
                                $assignment['id'],
                                'completed'
                            );
                        }
                    } else {
                        $failureCount++;
                    }
                }
                break;
                
            case 'cancel':
                // Cancel assignments
                foreach ($ids as $id) {
                    $result = $assignmentService->updateAssignmentStatus(intval($id), 'cancelled');
                    
                    if ($result['success']) {
                        $successCount++;
                        
                        // Send notification email
                        if (isset($result['assignment']) && $result['assignment']) {
                            $assignment = $result['assignment'];
                            $emailService->sendStatusUpdateNotification(
                                $assignment['assigned_to_email'],
                                $assignment['assigned_to_name'],
                                $assignment['member_name'],
                                $assignment['id'],
                                'cancelled'
                            );
                        }
                    } else {
                        $failureCount++;
                    }
                }
                break;
                
            case 'delete':
                // Delete assignments
                foreach ($ids as $id) {
                    $result = $assignmentService->deleteAssignment(intval($id));
                    
                    if ($result['success']) {
                        $successCount++;
                    } else {
                        $failureCount++;
                    }
                }
                break;
                
            default:
                throw new Exception('Invalid action specified');
        }
        
        // Set response
        if ($successCount > 0) {
            $actionText = '';
            switch ($action) {
                case 'complete':
                    $actionText = 'marked as completed';
                    break;
                case 'cancel':
                    $actionText = 'cancelled';
                    break;
                case 'delete':
                    $actionText = 'deleted';
                    break;
            }
            
            $response = [
                'success' => true,
                'message' => "$successCount assignments $actionText successfully" . ($failureCount > 0 ? ", $failureCount failed" : ""),
                'data' => [
                    'success_count' => $successCount,
                    'failure_count' => $failureCount
                ]
            ];
        } else {
            throw new Exception("Failed to $action any assignments");
        }
        
    } catch (Exception $e) {
        $response = [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }
}

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