<?php
/**
 * Email API Endpoint Test Script
 * Tests the /api/send-email.php endpoint functionality
 */

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/utils/helpers.php';

echo "========================================\n";
echo "Email API Endpoint Test\n";
echo "========================================\n\n";

// Test email recipient
$testEmail = getenv('TEST_EMAIL') ?: 'test@example.com';
echo "Test Email Recipient: $testEmail\n\n";

// Test 1: Get a valid user and create a session token
echo "Test 1: Creating test session...\n";
try {
    $stmt = $pdo->query("SELECT id, email FROM users LIMIT 1");
    $user = $stmt->fetch();
    
    if (!$user) {
        echo "❌ ERROR: No users found in database!\n";
        echo "   Create a user first before testing email API.\n\n";
        exit(1);
    }
    
    echo "✅ Using user: {$user['email']} (ID: {$user['id']})\n";
    
    // Create a test session token
    $sessionId = generateUUID();
    $token = bin2hex(random_bytes(32));
    $expiresAt = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
    $stmt = $pdo->prepare("
        INSERT INTO sessions (id, user_id, session_token, expires_at, created_at)
        VALUES (?, ?, ?, ?, datetime('now'))
    ");
    $stmt->execute([$sessionId, $user['id'], $token, $expiresAt]);
    
    echo "✅ Test session created\n";
    echo "   Token: $token\n\n";
} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n\n";
    exit(1);
}

// Test 2: Test API endpoint structure
echo "Test 2: Testing API endpoint structure...\n";
$apiFile = __DIR__ . '/api/send-email.php';
if (!file_exists($apiFile)) {
    echo "❌ ERROR: API file not found: $apiFile\n\n";
    exit(1);
}

echo "✅ API file exists\n";

// Check if required functions are available
$requiredFunctions = ['getAuthToken', 'getUserFromToken', 'errorResponse', 'jsonResponse', 'generateUUID'];
$missingFunctions = [];

foreach ($requiredFunctions as $func) {
    if (!function_exists($func)) {
        $missingFunctions[] = $func;
    }
}

if (!empty($missingFunctions)) {
    echo "❌ ERROR: Missing required functions: " . implode(', ', $missingFunctions) . "\n\n";
    exit(1);
}

echo "✅ All required functions available\n\n";

// Test 3: Test email sending via cURL (simulating API call)
echo "Test 3: Testing email sending via API endpoint...\n";
echo "   Note: This requires the PHP server to be running.\n";
echo "   Start server with: php -S localhost:8000 -t backend\n";
echo "   Then test with: curl -X POST http://localhost:8000/api/send-email.php\n\n";

// Test 4: Validate email payload structure
echo "Test 4: Validating email payload structure...\n";
$testPayload = [
    'to' => $testEmail,
    'subject' => 'Test Email from FlashCore',
    'message' => '<h1>Test Email</h1><p>This is a test email.</p>',
    'template' => 'custom',
    'data' => []
];

$requiredFields = ['to', 'subject'];
$missingFields = [];

foreach ($requiredFields as $field) {
    if (!isset($testPayload[$field])) {
        $missingFields[] = $field;
    }
}

if (!empty($missingFields)) {
    echo "❌ ERROR: Missing required fields: " . implode(', ', $missingFields) . "\n\n";
    exit(1);
}

echo "✅ Payload structure is valid\n";
echo "   Required fields: " . implode(', ', $requiredFields) . "\n";
echo "   Optional fields: message, template, data, from\n\n";

// Test 5: Test placeholder replacement with sample data
echo "Test 5: Testing template placeholder replacement...\n";
$templateContent = "Hello {name}, your verification code is {code}";
$templateData = ['name' => 'John Doe', 'code' => '123456'];
$expectedResult = "Hello John Doe, your verification code is 123456";

function replacePlaceholders($content, $data) {
    foreach ($data as $key => $value) {
        $placeholder = '{' . $key . '}';
        $content = str_replace($placeholder, $value, $content);
    }
    return $content;
}

$result = replacePlaceholders($templateContent, $templateData);

if ($result === $expectedResult) {
    echo "✅ Placeholder replacement works correctly\n";
    echo "   Template: $templateContent\n";
    echo "   Result: $result\n\n";
} else {
    echo "❌ ERROR: Placeholder replacement failed\n";
    echo "   Expected: $expectedResult\n";
    echo "   Got: $result\n\n";
}

// Test 6: Check email templates in database
echo "Test 6: Checking email templates...\n";
try {
    $stmt = $pdo->prepare("SELECT template_type, subject FROM email_templates WHERE is_active = TRUE");
    $stmt->execute();
    $templates = $stmt->fetchAll();
    
    if (count($templates) > 0) {
        echo "✅ Found " . count($templates) . " active template(s):\n";
        foreach ($templates as $template) {
            echo "   - {$template['template_type']}: {$template['subject']}\n";
        }
    } else {
        echo "⚠️  WARNING: No active email templates found\n";
        echo "   Custom messages can still be sent\n";
    }
    echo "\n";
} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n\n";
}

// Test 7: Test SMTP settings retrieval
echo "Test 7: Testing SMTP settings retrieval...\n";
try {
    $stmt = $pdo->prepare("SELECT provider, from_email, from_name, is_active FROM smtp_settings WHERE is_active = TRUE LIMIT 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if ($settings) {
        echo "✅ Active SMTP settings found:\n";
        echo "   Provider: {$settings['provider']}\n";
        echo "   From Email: " . ($settings['from_email'] ?: 'Not set') . "\n";
        echo "   From Name: " . ($settings['from_name'] ?: 'Not set') . "\n";
        
        // Check provider-specific requirements
        $provider = $settings['provider'] ?? 'smtp';
        switch ($provider) {
            case 'smtp':
            case 'gmail':
            case 'outlook':
            case 'yahoo':
                $stmt = $pdo->prepare("SELECT host, port, username FROM smtp_settings WHERE id = ?");
                $stmt->execute([$settings['id']]);
                $smtpDetails = $stmt->fetch();
                if ($smtpDetails) {
                    echo "   Host: " . ($smtpDetails['host'] ?: 'Not set') . "\n";
                    echo "   Port: " . ($smtpDetails['port'] ?: 'Not set') . "\n";
                    echo "   Username: " . ($smtpDetails['username'] ?: 'Not set') . "\n";
                }
                break;
            case 'resend':
                $stmt = $pdo->prepare("SELECT api_key FROM smtp_settings WHERE id = ?");
                $stmt->execute([$settings['id']]);
                $resendDetails = $stmt->fetch();
                if ($resendDetails) {
                    echo "   API Key: " . (empty($resendDetails['api_key']) ? 'Not set' : '***configured***') . "\n";
                }
                break;
            case 'emailjs':
                $stmt = $pdo->prepare("SELECT service_id, template_id, user_id FROM smtp_settings WHERE id = ?");
                $stmt->execute([$settings['id']]);
                $emailjsDetails = $stmt->fetch();
                if ($emailjsDetails) {
                    echo "   Service ID: " . ($emailjsDetails['service_id'] ?: 'Not set') . "\n";
                    echo "   Template ID: " . ($emailjsDetails['template_id'] ?: 'Not set') . "\n";
                    echo "   User ID: " . ($emailjsDetails['user_id'] ?: 'Not set') . "\n";
                }
                break;
        }
    } else {
        echo "❌ ERROR: No active SMTP settings found\n";
        echo "   Configure SMTP settings via admin panel\n";
    }
    echo "\n";
} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n\n";
}

// Cleanup test session
echo "Cleaning up test session...\n";
try {
    $stmt = $pdo->prepare("DELETE FROM sessions WHERE id = ?");
    $stmt->execute([$sessionId]);
    echo "✅ Test session cleaned up\n\n";
} catch (Exception $e) {
    echo "⚠️  WARNING: Could not clean up session: " . $e->getMessage() . "\n\n";
}

echo "========================================\n";
echo "Email API Testing Complete\n";
echo "========================================\n";
echo "\nNext Steps:\n";
echo "1. Ensure PHP server is running: php -S localhost:8000 -t backend\n";
echo "2. Test the API endpoint with a tool like Postman or curl\n";
echo "3. Use the test session token created above for authentication\n";
echo "4. Send POST request to: http://localhost:8000/api/send-email.php\n";
echo "5. Include Authorization header: Bearer {token}\n";
echo "6. Include JSON body with: to, subject, message (optional), template (optional)\n";

