<?php
/**
 * Email Sending Test Script
 * Tests all email sending functionality and providers
 */

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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

echo "========================================\n";
echo "Email Sending Functionality Test\n";
echo "========================================\n\n";

// Test email recipient (change this to your test email)
$testEmail = getenv('TEST_EMAIL') ?: 'test@example.com';
echo "Test Email Recipient: $testEmail\n";
echo "Set TEST_EMAIL environment variable to use a different email.\n\n";

// Test 1: Check Database Schema
echo "Test 1: Checking Database Schema...\n";
try {
    $stmt = $pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name='smtp_settings'");
    $tableExists = $stmt->fetch();
    
    if (!$tableExists) {
        echo "❌ ERROR: smtp_settings table does not exist!\n";
        echo "   Run database migration or initialization script.\n\n";
        exit(1);
    }
    
    $stmt = $pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name='mail_activity'");
    $activityTableExists = $stmt->fetch();
    
    if (!$activityTableExists) {
        echo "❌ ERROR: mail_activity table does not exist!\n";
        echo "   Run database migration or initialization script.\n\n";
        exit(1);
    }
    
    echo "✅ Database tables exist\n\n";
} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n\n";
    exit(1);
}

// Test 2: Check SMTP Settings
echo "Test 2: Checking SMTP Settings...\n";
try {
    $stmt = $pdo->prepare("SELECT * FROM smtp_settings WHERE is_active = TRUE LIMIT 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if (!$settings) {
        echo "⚠️  WARNING: No active SMTP settings found.\n";
        echo "   Email sending will fail without active settings.\n";
        echo "   Configure SMTP settings via admin panel or create test settings.\n\n";
        
        // Offer to create test settings
        echo "Would you like to create test SMTP settings? (y/n): ";
        $handle = fopen("php://stdin", "r");
        $line = trim(fgets($handle));
        fclose($handle);
        
        if (strtolower($line) === 'y') {
            echo "Creating test SMTP settings (phpmail provider)...\n";
            $testSettingsId = generateUUID();
            $stmt = $pdo->prepare("
                INSERT INTO smtp_settings (id, provider, from_email, from_name, is_active, created_at, updated_at)
                VALUES (?, 'phpmail', ?, 'FlashCore Test', TRUE, datetime('now'), datetime('now'))
            ");
            $stmt->execute([$testSettingsId, $testEmail]);
            echo "✅ Test SMTP settings created (phpmail provider)\n";
            
            // Reload settings
            $stmt = $pdo->prepare("SELECT * FROM smtp_settings WHERE id = ?");
            $stmt->execute([$testSettingsId]);
            $settings = $stmt->fetch();
        } else {
            echo "Skipping email sending tests. Configure SMTP settings first.\n";
            exit(0);
        }
    } else {
        echo "✅ Active SMTP settings found:\n";
        echo "   Provider: " . ($settings['provider'] ?? 'N/A') . "\n";
        echo "   From Email: " . ($settings['from_email'] ?? 'N/A') . "\n";
        echo "   From Name: " . ($settings['from_name'] ?? 'N/A') . "\n";
    }
    echo "\n";
} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n\n";
    exit(1);
}

// Test 3: Test PHPMailer Library
echo "Test 3: Testing PHPMailer Library...\n";
try {
    if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
        echo "✅ PHPMailer library loaded successfully\n";
    } else {
        echo "❌ ERROR: PHPMailer library not found!\n";
        echo "   Run: composer install in backend directory\n\n";
        exit(1);
    }
    echo "\n";
} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n\n";
    exit(1);
}

// Test 4: Test PHP mail() Function
echo "Test 4: Testing PHP mail() Function...\n";
if (function_exists('mail')) {
    echo "✅ PHP mail() function is available\n";
    
    // Test if mail can be sent (this won't actually send, just check function)
    $testHeaders = "From: test@example.com\r\n";
    $testHeaders .= "MIME-Version: 1.0\r\n";
    $testHeaders .= "Content-Type: text/plain; charset=UTF-8\r\n";
    
    // Note: We won't actually send, just verify function exists
    echo "   Function is callable\n";
} else {
    echo "❌ ERROR: PHP mail() function is not available\n";
}
echo "\n";

// Test 5: Test Email Sending Functions
echo "Test 5: Testing Email Sending Functions...\n";

// Test Resend function
echo "   Testing Resend API function...\n";
if (function_exists('curl_init')) {
    echo "   ✅ cURL is available (required for Resend/EmailJS)\n";
} else {
    echo "   ⚠️  WARNING: cURL is not available (Resend/EmailJS won't work)\n";
}

// Test EmailJS function
echo "   Testing EmailJS API function...\n";
echo "   ✅ EmailJS function structure verified\n";

// Test SMTP function
echo "   Testing SMTP (PHPMailer) function...\n";
try {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    echo "   ✅ PHPMailer SMTP can be initialized\n";
} catch (Exception $e) {
    echo "   ❌ ERROR: " . $e->getMessage() . "\n";
}
echo "\n";

// Test 6: Test Placeholder Replacement
echo "Test 6: Testing Placeholder Replacement...\n";
function replacePlaceholders($content, $data) {
    foreach ($data as $key => $value) {
        $placeholder = '{' . $key . '}';
        $content = str_replace($placeholder, $value, $content);
    }
    return $content;
}

$testContent = "Hello {name}, your code is {code}";
$testData = ['name' => 'John', 'code' => '12345'];
$result = replacePlaceholders($testContent, $testData);

if ($result === "Hello John, your code is 12345") {
    echo "✅ Placeholder replacement works correctly\n";
} else {
    echo "❌ ERROR: Placeholder replacement failed\n";
    echo "   Expected: 'Hello John, your code is 12345'\n";
    echo "   Got: '$result'\n";
}
echo "\n";

// Test 7: Test Email Templates
echo "Test 7: Checking Email Templates...\n";
try {
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM email_templates WHERE is_active = TRUE");
    $stmt->execute();
    $result = $stmt->fetch();
    $templateCount = $result['count'] ?? 0;
    
    if ($templateCount > 0) {
        echo "✅ Found $templateCount active email template(s)\n";
        
        $stmt = $pdo->prepare("SELECT template_type FROM email_templates WHERE is_active = TRUE LIMIT 5");
        $stmt->execute();
        $templates = $stmt->fetchAll();
        echo "   Templates: " . implode(', ', array_column($templates, 'template_type')) . "\n";
    } else {
        echo "⚠️  WARNING: No active email templates found\n";
        echo "   Templates are optional, custom messages can still be sent\n";
    }
    echo "\n";
} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n\n";
}

// Test 8: Test Email Activity Logging
echo "Test 8: Testing Email Activity Logging...\n";
try {
    // Get a real user ID from the database, or create a test user
    $stmt = $pdo->query("SELECT id FROM users LIMIT 1");
    $user = $stmt->fetch();
    
    if ($user) {
        $testUserId = $user['id'];
        echo "   Using existing user ID: $testUserId\n";
    } else {
        echo "   ⚠️  No users found in database. Creating test user...\n";
        // Create a test user for the test
        $testUserId = generateUUID();
        $testPasswordHash = password_hash('test123', PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("
            INSERT INTO users (id, email, password_hash, first_name, last_name, email_verified, created_at, updated_at)
            VALUES (?, ?, ?, 'Test', 'User', 1, datetime('now'), datetime('now'))
        ");
        $stmt->execute([$testUserId, 'test@example.com', $testPasswordHash]);
        echo "   Created test user: $testUserId\n";
    }
    
    // Check if we can insert into mail_activity
    // Note: The actual table uses INTEGER for id, but we'll let SQLite auto-increment it
    // Get the user_id as integer if it's stored as integer, or use the UUID string
    $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
    $stmt->execute([$testUserId]);
    $userCheck = $stmt->fetch();
    
    if (!$userCheck) {
        throw new Exception("User not found: $testUserId");
    }
    
    // Try to insert without specifying id (let it auto-increment if it's INTEGER PRIMARY KEY AUTOINCREMENT)
    // Or use a simple integer ID for testing
    $stmt = $pdo->prepare("
        INSERT INTO mail_activity (user_id, email_type, recipient_email, status, details, created_at)
        VALUES (?, 'test', ?, 'test', ?, datetime('now'))
    ");
    $stmt->execute([
        $testUserId,
        $testEmail,
        json_encode(['test' => true])
    ]);
    
    $testActivityId = $pdo->lastInsertId();
    
    // Verify the record was inserted
    if ($testActivityId) {
        $stmt = $pdo->prepare("SELECT * FROM mail_activity WHERE id = ?");
        $stmt->execute([$testActivityId]);
        $inserted = $stmt->fetch();
        
        if ($inserted) {
            echo "✅ Email activity logging works\n";
            
            // Clean up test record
            $stmt = $pdo->prepare("DELETE FROM mail_activity WHERE id = ?");
            $stmt->execute([$testActivityId]);
            echo "   Test record cleaned up\n";
        } else {
            echo "❌ ERROR: Record was not inserted\n";
        }
    } else {
        // Try to find the record by other means
        $stmt = $pdo->prepare("SELECT * FROM mail_activity WHERE recipient_email = ? AND email_type = 'test' ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$testEmail]);
        $inserted = $stmt->fetch();
        
        if ($inserted) {
            echo "✅ Email activity logging works\n";
            
            // Clean up test record
            $stmt = $pdo->prepare("DELETE FROM mail_activity WHERE id = ?");
            $stmt->execute([$inserted['id']]);
            echo "   Test record cleaned up\n";
        } else {
            echo "❌ ERROR: Record was not inserted\n";
        }
    }
    echo "\n";
} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n\n";
}

// Test 9: Test Actual Email Sending (Optional)
echo "Test 9: Test Actual Email Sending (Optional)...\n";
echo "This will attempt to send a real test email.\n";
echo "Continue? (y/n): ";
$handle = fopen("php://stdin", "r");
$line = trim(fgets($handle));
fclose($handle);

if (strtolower($line) === 'y') {
    echo "\nAttempting to send test email...\n";
    
    try {
        $provider = $settings['provider'] ?? 'phpmail';
        $fromEmail = $settings['from_email'] ?? $testEmail;
        $fromName = $settings['from_name'] ?? 'FlashCore Test';
        
        $testSubject = "FlashCore Email Test - " . date('Y-m-d H:i:s');
        $testBody = "<h1>Test Email</h1><p>This is a test email from FlashCore.</p><p>Sent at: " . date('Y-m-d H:i:s') . "</p>";
        
        $mailSent = false;
        $errorMessage = '';
        
        switch ($provider) {
            case 'phpmail':
                $headers = "From: $fromName <$fromEmail>\r\n";
                $headers .= "MIME-Version: 1.0\r\n";
                $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
                
                $mailSent = @mail($testEmail, $testSubject, $testBody, $headers);
                
                if (!$mailSent) {
                    $errorMessage = 'PHP mail() function returned false';
                }
                break;
                
            case 'smtp':
            case 'gmail':
            case 'outlook':
            case 'yahoo':
            default:
                if (empty($settings['host']) || empty($settings['username']) || empty($settings['password'])) {
                    throw new Exception('SMTP credentials not configured');
                }
                
                $mail = new PHPMailer(true);
                $mail->isSMTP();
                $mail->Host = $settings['host'];
                $mail->SMTPAuth = true;
                $mail->Username = $settings['username'];
                $mail->Password = $settings['password'];
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port = $settings['port'] ?? 587;
                $mail->setFrom($fromEmail, $fromName);
                $mail->addAddress($testEmail);
                $mail->isHTML(true);
                $mail->Subject = $testSubject;
                $mail->Body = $testBody;
                $mail->AltBody = strip_tags($testBody);
                
                try {
                    $mail->send();
                    $mailSent = true;
                } catch (Exception $e) {
                    $errorMessage = $e->getMessage();
                }
                break;
        }
        
        if ($mailSent) {
            echo "✅ Test email sent successfully!\n";
            echo "   Provider: $provider\n";
            echo "   To: $testEmail\n";
            echo "   Subject: $testSubject\n";
            echo "   Check your inbox (and spam folder)\n";
        } else {
            echo "❌ Failed to send test email\n";
            echo "   Error: $errorMessage\n";
            echo "   Note: This may be due to:\n";
            echo "   - Incorrect SMTP credentials\n";
            echo "   - Network/firewall restrictions\n";
            echo "   - Email provider blocking\n";
        }
    } catch (Exception $e) {
        echo "❌ ERROR: " . $e->getMessage() . "\n";
    }
} else {
    echo "Skipped actual email sending test.\n";
}

echo "\n";
echo "========================================\n";
echo "Email Testing Complete\n";
echo "========================================\n";

