<?php
// Start output buffering to prevent any unwanted output
ob_start();

// Suppress PHP errors/warnings from being displayed
error_reporting(E_ALL);
ini_set('display_errors', 0);

try {
    require_once 'auth_rbac.php';
    require_once '../db_config.php';
    require_once '../email_service.php';

    // Require admin login with email permission
    $auth = new AdminAuth();
    $auth->requireLogin();
    $auth->requirePermission('dashboard', 'view');

    // Clean any output that might have been generated
    ob_clean();
    header('Content-Type: application/json');

    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['email_id'])) {
        throw new Exception('Email ID is required');
    }
    
    $email_id = intval($input['email_id']);
    $pdo = getDBConnection();
    
    // Get the original email log entry
    $stmt = $pdo->prepare("
        SELECT 
            en.*,
            r.id as registration_id,
            r.registration_number,
            r.contact_full_name,
            r.contact_email,
            r.university_name,
            r.delegate_count,
            r.total_amount,
            r.payment_method,
            r.payment_status,
            r.created_at as registration_date
        FROM email_notifications en
        LEFT JOIN registrations r ON en.registration_id = r.id
        WHERE en.id = ?
    ");
    $stmt->execute([$email_id]);
    $original_email = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$original_email) {
        throw new Exception('Email log entry not found');
    }
    
    if (!$original_email['registration_id']) {
        throw new Exception('Cannot resend email: No associated registration found');
    }
    
    // Initialize email service
    $emailService = new BrevoEmailService();
    
    // Prepare registration data for email templates
    $registration_data = [
        'id' => $original_email['registration_id'],
        'registration_number' => $original_email['registration_number'],
        'contact_full_name' => $original_email['contact_full_name'],
        'contact_email' => $original_email['contact_email'],
        'university_name' => $original_email['university_name'],
        'delegate_count' => $original_email['delegate_count'],
        'total_amount' => $original_email['total_amount'],
        'payment_method' => $original_email['payment_method'],
        'payment_status' => $original_email['payment_status'],
        'created_at' => $original_email['registration_date']
    ];
    
    $success = false;
    $email_type = $original_email['email_type'];
    
    // Resend the appropriate email type using current data
    switch ($email_type) {
        case 'pending_registration':
            $success = $emailService->sendPendingRegistrationEmail($registration_data);
            break;
            
        case 'registration_confirmation':
            $success = $emailService->sendRegistrationConfirmationEmail($registration_data);
            break;
            
        case 'payment_failure':
            $success = $emailService->sendPaymentFailureEmail($registration_data, 'Manual resend from admin panel');
            break;
            
        case 'payment_reminder_24h':
        case 'payment_reminder_48h':
        case 'payment_reminder_7d':
            $success = $emailService->sendPaymentReminderEmail($registration_data, $email_type);
            break;
            
        case 'admin_notification':
            // For admin notifications, we need to determine the notification type
            $notification_type = 'new_registration'; // Default
            if (strpos($original_email['subject'], 'Payment') !== false) {
                $notification_type = 'payment_received';
            }
            $success = $emailService->sendAdminNotification($notification_type, $registration_data, 'Resent from admin panel');
            break;
            
        default:
            throw new Exception('Unsupported email type: ' . $email_type);
    }
    
    if ($success) {
        echo json_encode([
            'success' => true,
            'message' => 'Email resent successfully',
            'email_type' => $email_type,
            'recipient' => $original_email['contact_email']
        ]);
    } else {
        throw new Exception('Failed to send email - check email service configuration');
    }
    
} catch (Exception $e) {
    // Clean any output that might have been generated
    ob_clean();
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
} catch (Error $e) {
    // Handle fatal errors
    ob_clean();
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Server error: ' . $e->getMessage()
    ]);
}

// End output buffering and send the response
ob_end_flush();
?>
