<?php
/**
 * KSO Chandigarh Admin Panel
 * Batch Update Assignments API Endpoint
 * 
 * This endpoint handles batch updates of multiple assignments 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
    $assignment_ids = isset($_POST['assignment_ids']) ? $_POST['assignment_ids'] : [];
    $status = isset($_POST['status']) ? trim($_POST['status']) : null;
    $priority = isset($_POST['priority']) ? trim($_POST['priority']) : null;
    $assigned_to = isset($_POST['assigned_to']) ? trim($_POST['assigned_to']) : null;
    $due_date = isset($_POST['due_date']) ? trim($_POST['due_date']) : null;
    $send_email = isset($_POST['send_email']) ? (bool)$_POST['send_email'] : false;
    
    // Validate inputs
    if (empty($assignment_ids) || !is_array($assignment_ids)) {
        $response['message'] = 'No assignments selected for update';
        echo json_encode($response);
        exit;
    }
    
    // Check if at least one field is being updated
    if ($status === null && $priority === null && $assigned_to === null && $due_date === null) {
        $response['message'] = 'No update values provided';
        echo json_encode($response);
        exit;
    }
    
    // Process batch updates
    $successful = 0;
    $failed = 0;
    $admin_id = $_SESSION['admin_id'];
    
    // Start transaction
    $conn->beginTransaction();
    
    foreach ($assignment_ids as $assignment_id) {
        // Create update data array (only include fields that are being updated)
        $updateData = [
            'updated_by' => $admin_id
        ];
        
        if ($status !== null) {
            $updateData['status'] = $status;
        }
        
        if ($priority !== null) {
            $updateData['priority'] = $priority;
        }
        
        if ($assigned_to !== null) {
            $updateData['assigned_to'] = $assigned_to;
        }
        
        if ($due_date !== null) {
            $updateData['due_date'] = $due_date;
        }
        
        // Attempt to update assignment
        $result = $assignmentService->updateAssignment($assignment_id, $updateData);
        
        if ($result) {
            $successful++;
            
            // Send email notification if requested
            if ($send_email) {
                // Include email service
                require_once '../../services/EmailService.php';
                $emailService = new EmailService();
                
                // Get assignment details
                $assignmentDetails = $assignmentService->getAssignmentDetails($assignment_id);
                
                if ($assignmentDetails) {
                    // If assignment was reassigned, send notification to new admin
                    if ($assigned_to !== null) {
                        $adminDetails = $assignmentService->getAdminDetails($assigned_to);
                        $memberDetails = $assignmentService->getMemberDetails($assignmentDetails['member_id']);
                        
                        if ($adminDetails && $memberDetails) {
                            // Send reassignment email to new admin
                            $emailService->sendAssignmentReassignedNotification(
                                $adminDetails['email'],
                                $adminDetails['name'],
                                $assignmentDetails['title'],
                                $assignmentDetails['description'],
                                $memberDetails['name'],
                                $updateData['priority'] ?? $assignmentDetails['priority'],
                                $updateData['due_date'] ?? $assignmentDetails['due_date'],
                                $updateData['status'] ?? $assignmentDetails['status']
                            );
                        }
                    }
                    
                    // If status changed to completed, send notification to member
                    if ($status === 'completed') {
                        $memberDetails = $assignmentService->getMemberDetails($assignmentDetails['member_id']);
                        
                        if ($memberDetails) {
                            // Send completion email to member
                            $emailService->sendAssignmentCompletedNotification(
                                $memberDetails['email'],
                                $memberDetails['name'],
                                $assignmentDetails['title']
                            );
                        }
                    }
                }
            }
        } else {
            $failed++;
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    // Prepare response
    $response['success'] = true;
    $response['message'] = "Batch update process completed";
    $response['data'] = [
        'successful' => $successful,
        'failed' => $failed
    ];
    
} catch (Exception $e) {
    // Rollback transaction on error
    if ($conn->inTransaction()) {
        $conn->rollBack();
    }
    
    $response['message'] = 'Error processing batch updates: ' . $e->getMessage();
    
    // Log the error
    error_log('Batch Update Error: ' . $e->getMessage());
} finally {
    // Close the database connection
    $conn = null;
}

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