<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors in output
ini_set('log_errors', 1);

// Start output buffering to catch any unexpected output
ob_start();

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

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

    // Clear any output that might have been generated
    ob_clean();
    header('Content-Type: application/json');
} catch (Exception $e) {
    ob_clean();
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Initialization error: ' . $e->getMessage()]);
    exit;
}

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

$input = json_decode(file_get_contents('php://input'), true);
$testType = $input['test_type'] ?? '';
$testEmail = $input['test_email'] ?? '';

try {
    // Validate input
    if (empty($testType)) {
        throw new Exception('Test type is required');
    }
    
    switch ($testType) {
        case 'api_connection':
            $result = testBrevoApiConnection();
            break;
            
        case 'send_test_email':
            if (empty($testEmail)) {
                throw new Exception('Test email address is required');
            }
            if (!filter_var($testEmail, FILTER_VALIDATE_EMAIL)) {
                throw new Exception('Invalid email address format');
            }
            $result = sendTestEmail($testEmail);
            break;
            
        default:
            throw new Exception('Invalid test type: ' . $testType);
    }
    
    // Ensure we have a valid result
    if (!is_array($result)) {
        throw new Exception('Invalid response from test function');
    }
    
    echo json_encode($result);
    
} catch (Exception $e) {
    error_log('Email test error: ' . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false, 
        'error' => $e->getMessage(),
        'debug_info' => [
            'test_type' => $testType,
            'test_email' => $testEmail,
            'timestamp' => date('Y-m-d H:i:s')
        ]
    ]);
} catch (Error $e) {
    error_log('Email test fatal error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'error' => 'Fatal error: ' . $e->getMessage()
    ]);
}

/**
 * Test Brevo API connection
 */
function testBrevoApiConnection() {
    // Get API key from settings
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT setting_value FROM admin_settings WHERE setting_key = 'brevoApiKey'");
    $stmt->execute();
    $apiKey = $stmt->fetchColumn();
    
    if (empty($apiKey)) {
        return ['success' => false, 'error' => 'Brevo API key not configured'];
    }
    
    // Test API connection by getting account info
    $curl = curl_init();
    
    curl_setopt_array($curl, [
        CURLOPT_URL => 'https://api.brevo.com/v3/account',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => [
            'accept: application/json',
            'api-key: ' . $apiKey
        ],
    ]);
    
    $response = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $error = curl_error($curl);
    curl_close($curl);
    
    if ($error) {
        return ['success' => false, 'error' => 'CURL Error: ' . $error];
    }
    
    $data = json_decode($response, true);
    
    if ($httpCode === 200) {
        $accountInfo = [
            'email' => $data['email'] ?? 'N/A',
            'firstName' => $data['firstName'] ?? '',
            'lastName' => $data['lastName'] ?? '',
            'companyName' => $data['companyName'] ?? 'N/A',
            'plan' => $data['plan'][0]['type'] ?? 'N/A'
        ];
        
        return [
            'success' => true,
            'message' => 'API connection successful!',
            'account_info' => $accountInfo
        ];
    } else {
        $errorMessage = 'API Error';
        if (isset($data['message'])) {
            $errorMessage = $data['message'];
        } elseif (isset($data['code'])) {
            $errorMessage = 'Error code: ' . $data['code'];
        }
        
        return ['success' => false, 'error' => $errorMessage];
    }
}

/**
 * Send a test email
 */
function sendTestEmail($testEmail) {
    try {
        // Check if BrevoEmailService class exists
        if (!class_exists('BrevoEmailService')) {
            throw new Exception('BrevoEmailService class not found. Please check email_service.php');
        }
        
        $emailService = new BrevoEmailService();
        
        // Get event name for branding
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT setting_value FROM admin_settings WHERE setting_key = 'eventName'");
        $stmt->execute();
        $eventName = $stmt->fetchColumn() ?: 'XChange 2025';
        
        // Create test email content
        $subject = "✅ Email Test - {$eventName} Registration System";
        
        $htmlContent = "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Email Test</title>
            <link rel=\"icon\" type=\"image/svg+xml\" href=\"../favicon.svg\">
            <link rel=\"icon\" type=\"image/x-icon\" href=\"../favicon.ico\">
            <link rel=\"apple-touch-icon\" href=\"../favicon.svg\">
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #10b981; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { padding: 30px; background: #f9fafb; border-radius: 0 0 8px 8px; }
                .success-badge { background: #d1fae5; border: 2px solid #10b981; padding: 15px; border-radius: 8px; margin: 20px 0; text-align: center; }
                .info-box { background: #e0f2fe; border: 1px solid #0284c7; padding: 15px; border-radius: 5px; margin: 20px 0; }
                .footer { text-align: center; padding: 20px; color: #666; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>🎉 Email Test Successful!</h1>
                    <h2>{$eventName}</h2>
                </div>
                
                <div class='content'>
                    <div class='success-badge'>
                        <h3 style='margin: 0; color: #065f46;'>✅ Your email configuration is working perfectly!</h3>
                    </div>
                    
                    <p>Congratulations! This test email confirms that your Brevo email service is properly configured and working.</p>
                    
                    <div class='info-box'>
                        <h4>📋 Test Details:</h4>
                        <ul>
                            <li><strong>Test Date:</strong> " . date('Y-m-d H:i:s T') . "</li>
                            <li><strong>Recipient:</strong> {$testEmail}</li>
                            <li><strong>Service:</strong> Brevo Email API</li>
                            <li><strong>System:</strong> {$eventName} Registration System</li>
                        </ul>
                    </div>
                    
                    <h4>✅ What this means:</h4>
                    <ul>
                        <li>Your Brevo API key is valid and active</li>
                        <li>Email sending functionality is working</li>
                        <li>Registration emails will be delivered successfully</li>
                        <li>Admin notifications are properly configured</li>
                    </ul>
                    
                    <p><strong>Next Steps:</strong></p>
                    <ul>
                        <li>Test different email templates from the Email Templates page</li>
                        <li>Monitor email logs for delivery tracking</li>
                        <li>Your registration system is ready for production!</li>
                    </ul>
                    
                    <p>If you have any questions or need assistance, please contact your system administrator.</p>
                </div>
                
                <div class='footer'>
                    <p>This is an automated test email from {$eventName} Registration System</p>
                    <p>© 2025 {$eventName}. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>";
        
        // Send the test email
        $recipient = [
            'email' => $testEmail,
            'name' => 'Test Recipient'
        ];
        
        $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 {
            $stmt = $pdo->prepare("
                INSERT INTO email_notifications 
                (registration_id, email_type, recipient_email, recipient_name, subject, status, sent_at, brevo_message_id) 
                VALUES (NULL, 'api_test', ?, 'Test Recipient', ?, 'sent', NOW(), ?)
            ");
            $stmt->execute([
                $testEmail,
                $subject,
                $result['message_id'] ?? null
            ]);
        } catch (Exception $e) {
            error_log('Failed to log test email: ' . $e->getMessage());
            // Don't fail the test if logging fails
        }
        
        return [
            'success' => true,
            'message' => 'Test email sent successfully!',
            'message_id' => $result['message_id'] ?? null,
            'recipient' => $testEmail
        ];
        
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}
?>
