<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once '../email_service.php';

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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    switch ($action) {
        case 'send_test':
            $templateType = $input['template'] ?? '';
            $testEmail = $input['email'] ?? '';
            $testName = $input['name'] ?? 'Test User';
            
            if (empty($templateType) || empty($testEmail)) {
                throw new Exception('Template type and email are required');
            }
            
            $result = sendTestEmail($templateType, $testEmail, $testName);
            echo json_encode(['success' => true, 'message' => 'Test email sent successfully']);
            break;
            
        default:
            throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}

/**
 * Send a test email using the specified template
 */
function sendTestEmail($templateType, $testEmail, $testName) {
    // Create sample data for test email
    $sampleData = [
        'id' => 999,
        'registration_number' => 'XC25-TEST123',
        'delegate_type' => 'earlyBird',
        'delegate_count' => 2,
        'has_standard_table' => true,
        'has_double_table' => false,
        'contact_salutation' => 'Dr.',
        'contact_full_name' => $testName,
        'contact_badge_name' => $testName,
        'contact_designation' => 'Test Position',
        'contact_department' => 'Test Department',
        'contact_email' => $testEmail,
        'contact_mobile' => '+1-555-TEST',
        'university_name' => 'Test University',
        'country' => 'Test Country',
        'payment_method' => 'tt',
        'payment_status' => 'pending',
        'total_amount' => 1000.00,
        'created_at' => date('Y-m-d H:i:s'),
        'payment_deadline' => date('Y-m-d', strtotime('+7 days'))
    ];
    
    $emailService = new BrevoEmailService();
    
    // Generate subject and content based on template type
    switch ($templateType) {
        case 'pending_registration':
            $subject = "[TEST] Registration Received - Payment Pending | XChange 2025";
            $htmlContent = $emailService->generatePendingRegistrationTemplate($sampleData);
            break;
            
        case 'registration_confirmation':
            $subject = "[TEST] Registration Confirmed - Welcome to XChange 2025!";
            $htmlContent = $emailService->generateRegistrationConfirmationTemplate($sampleData);
            break;
            
        case 'payment_failure':
            $subject = "[TEST] Payment Issue - XChange 2025 Registration";
            $htmlContent = $emailService->generatePaymentFailureTemplate($sampleData, 'This is a test payment failure message.');
            break;
            
        case 'payment_reminder_24h':
            $subject = "[TEST] Payment Reminder (24h) - XChange 2025";
            $htmlContent = $emailService->generatePaymentReminderTemplate($sampleData, '24h');
            break;
            
        case 'payment_reminder_48h':
            $subject = "[TEST] Payment Reminder (48h) - XChange 2025";
            $htmlContent = $emailService->generatePaymentReminderTemplate($sampleData, '48h');
            break;
            
        case 'payment_reminder_7d':
            $subject = "[TEST] Final Payment Reminder - XChange 2025";
            $htmlContent = $emailService->generatePaymentReminderTemplate($sampleData, '7d');
            break;
            
        case 'admin_notification':
            $subject = "[TEST] Admin Notification - XChange 2025";
            $htmlContent = $emailService->generateAdminNotificationTemplate('payment_received', $sampleData, 'This is a test admin notification.');
            break;
            
        default:
            throw new Exception('Unknown template type: ' . $templateType);
    }
    
    // Add test notice to the email
    $testNotice = "
    <div style='background: #fef3c7; border: 2px solid #f59e0b; padding: 15px; margin: 20px; border-radius: 8px; text-align: center;'>
        <h3 style='color: #92400e; margin: 0 0 10px 0;'>🧪 TEST EMAIL</h3>
        <p style='color: #78350f; margin: 0; font-weight: bold;'>This is a test email sent from the XChange 2025 admin panel.</p>
        <p style='color: #78350f; margin: 5px 0 0 0; font-size: 0.875rem;'>Template: " . ucfirst(str_replace('_', ' ', $templateType)) . "</p>
    </div>";
    
    // Insert test notice at the beginning of the email content
    $htmlContent = str_replace('<div class=\'container\'>', '<div class=\'container\'>' . $testNotice, $htmlContent);
    
    // Send the email
    $recipient = [
        'email' => $testEmail,
        'name' => $testName
    ];
    
    $result = $emailService->sendEmail($recipient, $subject, $htmlContent);
    
    if (!$result['success']) {
        throw new Exception('Failed to send test email: ' . ($result['error'] ?? 'Unknown error'));
    }
    
    // Log the test email
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("
            INSERT INTO email_notifications 
            (registration_id, email_type, recipient_email, recipient_name, subject, status, sent_at, brevo_message_id) 
            VALUES (NULL, ?, ?, ?, ?, 'sent', NOW(), ?)
        ");
        $stmt->execute([
            'test_' . $templateType,
            $testEmail,
            $testName,
            $subject,
            $result['message_id'] ?? null
        ]);
    } catch (Exception $e) {
        error_log('Failed to log test email: ' . $e->getMessage());
        // Don't fail the test email if logging fails
    }
    
    return true;
}
?>
