<?php
/**
 * API: Update assignment status
 * 
 * This endpoint updates the status of an assignment (complete, cancel, etc.)
 */

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;

// Define email notification settings
define('ENABLE_ASSIGNMENT_NOTIFICATIONS', true);

// Require admin access
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'data' => null,
    'message' => 'Error updating assignment'
];

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Method not allowed';
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

try {
    // Get POST data
    $postData = json_decode(file_get_contents('php://input'), true);
    if (!$postData) {
        $postData = $_POST;
    }
    
    // Validate required fields
    $requiredFields = ['assignment_id', 'status'];
    foreach ($requiredFields as $field) {
        if (!isset($postData[$field]) || empty($postData[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    $db = new Database();
    $conn = $db->getConnection();
    
    // Start transaction
    $conn->beginTransaction();
    
    $assignmentId = $postData['assignment_id'];
    $status = $postData['status'];
    $notes = isset($postData['notes']) ? $postData['notes'] : null;
    
    // Get assignment details first
    $getQuery = "SELECT member_id, assigned_to, assigned_by FROM admin_assignments WHERE id = :assignment_id";
    $getStmt = $conn->prepare($getQuery);
    $getStmt->bindValue(':assignment_id', $assignmentId);
    $getStmt->execute();
    
    if ($getStmt->rowCount() === 0) {
        throw new Exception("Assignment not found");
    }
    
    $assignment = $getStmt->fetch(PDO::FETCH_ASSOC);
    
    // Update assignment
    $query = "UPDATE admin_assignments 
              SET status = :status, 
                  notes = CONCAT(IFNULL(notes, ''), '\n\n', :notes),
                  completed_at = :completed_at,
                  updated_at = NOW()
              WHERE id = :assignment_id";
    
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':status', $status);
    $stmt->bindValue(':notes', $notes);
    $stmt->bindValue(':completed_at', ($status === 'completed') ? date('Y-m-d H:i:s') : null);
    $stmt->bindValue(':assignment_id', $assignmentId);
    $stmt->execute();
    
    // If assignment is completed, clear the assigned_to field in members table
    if ($status === 'completed') {
        $updateMemberQuery = "UPDATE members 
                             SET assigned_to = NULL,
                                 assignment_notes = CONCAT(IFNULL(assignment_notes, ''), '\n\n', :notes, '\n(Completed on ', NOW(), ')')
                             WHERE id = :member_id";
        $updateMemberStmt = $conn->prepare($updateMemberQuery);
        $updateMemberStmt->bindValue(':notes', $notes);
        $updateMemberStmt->bindValue(':member_id', $assignment['member_id']);
        $updateMemberStmt->execute();
    }
    
    // Create notification for the admin who assigned this task
    if ($status === 'completed' && $assignment['assigned_by'] != $_SESSION['admin_id']) {
        // Get member name
        $memberQuery = "SELECT CONCAT(first_name, ' ', last_name) as member_name FROM members WHERE id = :member_id";
        $memberStmt = $conn->prepare($memberQuery);
        $memberStmt->bindValue(':member_id', $assignment['member_id']);
        $memberStmt->execute();
        $memberName = $memberStmt->fetch(PDO::FETCH_ASSOC)['member_name'];
        
        // Get admin name
        $adminQuery = "SELECT CONCAT(first_name, ' ', last_name) as admin_name FROM admins WHERE id = :admin_id";
        $adminStmt = $conn->prepare($adminQuery);
        $adminStmt->bindValue(':admin_id', $_SESSION['admin_id']);
        $adminStmt->execute();
        $adminName = $adminStmt->fetch(PDO::FETCH_ASSOC)['admin_name'];
        
        // Create notification
        $notificationQuery = "INSERT INTO notifications 
                             (type, title, message, target_audience, target_user_id, created_by, priority, related_entity_type, related_entity_id) 
                             VALUES 
                             ('success', :title, :message, 'specific', :target_user_id, :created_by, 'normal', 'member', :member_id)";
        $notificationStmt = $conn->prepare($notificationQuery);
        $notificationStmt->bindValue(':title', 'Assignment Completed');
        $notificationStmt->bindValue(':message', "$adminName has completed the review assignment for member: $memberName.");
        $notificationStmt->bindValue(':target_user_id', $assignment['assigned_by']);
        $notificationStmt->bindValue(':created_by', $_SESSION['admin_id']);
        $notificationStmt->bindValue(':member_id', $assignment['member_id']);
        $notificationStmt->execute();
        
        $notificationId = $conn->lastInsertId();
        
        // Add notification recipient
        $recipientQuery = "INSERT INTO notification_recipients 
                          (notification_id, user_id, user_type) 
                          VALUES 
                          (:notification_id, :user_id, 'admin')";
        $recipientStmt = $conn->prepare($recipientQuery);
        $recipientStmt->bindValue(':notification_id', $notificationId);
        $recipientStmt->bindValue(':user_id', $assignment['assigned_by']);
        $recipientStmt->execute();
    }
    
    // Commit transaction
    $conn->commit();
    
    // Send email notification if enabled
    if (defined('ENABLE_ASSIGNMENT_NOTIFICATIONS') && ENABLE_ASSIGNMENT_NOTIFICATIONS) {
        try {
            // Get additional information for email
            $emailInfoQuery = "SELECT 
                              m.first_name as member_first_name, m.last_name as member_last_name,
                              a.username as assigned_to_name, a.email as assigned_to_email,
                              assigner.username as assigned_by_name, assigner.email as assigned_by_email
                          FROM 
                              admin_assignments aa
                          JOIN 
                              members m ON aa.member_id = m.id
                          JOIN 
                              admin_users a ON aa.assigned_to = a.id
                          LEFT JOIN 
                              admin_users assigner ON aa.assigned_by = assigner.id
                          WHERE 
                              aa.id = :assignment_id";
              
            $emailInfoStmt = $conn->prepare($emailInfoQuery);
            $emailInfoStmt->bindValue(':assignment_id', $assignmentId);
            $emailInfoStmt->execute();
            $emailInfo = $emailInfoStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($emailInfo) {
                $memberName = $emailInfo['member_first_name'] . ' ' . $emailInfo['member_last_name'];
                
                // Initialize email service
                $emailService = new EmailService();
                
                // Send status update notification to assigned admin
                $emailService->sendStatusUpdateNotification(
                    $emailInfo['assigned_to_email'],
                    $emailInfo['assigned_to_name'],
                    $memberName,
                    $assignmentId,
                    $status
                );
                
                // If completed or cancelled, also notify the admin who created the assignment
                if (($status === 'completed' || $status === 'cancelled') && 
                    isset($emailInfo['assigned_by_email']) && 
                    $emailInfo['assigned_by_email'] !== $emailInfo['assigned_to_email']) {
                    
                    $emailService->sendStatusUpdateNotification(
                        $emailInfo['assigned_by_email'],
                        $emailInfo['assigned_by_name'],
                        $memberName,
                        $assignmentId,
                        $status
                    );
                }
            }
        } catch (Exception $e) {
            // Log email error but don't fail the transaction
            error_log("Error sending assignment notification email: " . $e->getMessage());
        }
    }
    
    // Format the response
    $response = [
        'success' => true,
        'data' => [
            'assignment_id' => $assignmentId,
            'status' => $status,
            'updated_at' => date('Y-m-d H:i:s')
        ],
        'message' => "Assignment marked as $status successfully"
    ];
    
} catch (PDOException $e) {
    // Rollback transaction on error
    if (isset($conn)) {
        $conn->rollBack();
    }
    $response['message'] = 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
    if (isset($conn)) {
        $conn->rollBack();
    }
    $response['message'] = 'Error: ' . $e->getMessage();
}

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