<?php
/**
 * Send Test Email
 * Sends a test email to the specified recipient
 */

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;

$recipientEmail = 'kvng@catgroup.uk';

echo "========================================\n";
echo "Sending Test Email\n";
echo "========================================\n\n";
echo "Recipient: $recipientEmail\n\n";

try {
    // Get active SMTP settings
    $stmt = $pdo->prepare("SELECT * FROM smtp_settings WHERE is_active = TRUE LIMIT 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if (!$settings) {
        echo "❌ ERROR: No active SMTP settings found!\n";
        exit(1);
    }
    
    echo "SMTP Settings:\n";
    echo "  Host: {$settings['host']}\n";
    echo "  Port: {$settings['port']}\n";
    echo "  From: {$settings['from_email']} ({$settings['from_name']})\n\n";
    
    // Send email
    $mail = new PHPMailer(true);
    
    // Server settings
    $mail->isSMTP();
    $mail->Host = $settings['host'];
    $mail->SMTPAuth = true;
    $mail->Username = $settings['username'];
    $mail->Password = $settings['password'];
    
    // Port 465 uses SSL, port 587 uses STARTTLS
    $port = $settings['port'] ?? 587;
    if ($port == 465) {
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    } else {
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    }
    
    $mail->Port = $port;
    
    // Recipients
    $mail->setFrom($settings['from_email'], $settings['from_name']);
    $mail->addAddress($recipientEmail);
    
    // Content
    $mail->isHTML(true);
    $mail->Subject = 'FlashCore Test Email - ' . date('Y-m-d H:i:s');
    $mail->Body = '
    <html>
    <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
        <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
            <h1 style="color: #2563eb;">FlashCore Test Email</h1>
            <p>This is a test email from FlashCore to verify SMTP configuration.</p>
            <div style="background-color: #f3f4f6; padding: 15px; border-radius: 5px; margin: 20px 0;">
                <p><strong>Email Details:</strong></p>
                <ul>
                    <li>Sent at: ' . date('Y-m-d H:i:s') . '</li>
                    <li>From: ' . htmlspecialchars($settings['from_email']) . '</li>
                    <li>SMTP Server: ' . htmlspecialchars($settings['host']) . '</li>
                </ul>
            </div>
            <p>If you received this email, the SMTP configuration is working correctly!</p>
            <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 20px 0;">
            <p style="color: #6b7280; font-size: 12px;">This is an automated test email from FlashCore.</p>
        </div>
    </body>
    </html>
    ';
    $mail->AltBody = "FlashCore Test Email\n\nThis is a test email from FlashCore to verify SMTP configuration.\n\nSent at: " . date('Y-m-d H:i:s') . "\nFrom: {$settings['from_email']}\n\nIf you received this email, the SMTP configuration is working correctly!";
    
    echo "Sending email...\n";
    $mail->send();
    
    echo "✅ SUCCESS: Test email sent successfully!\n\n";
    echo "Email Details:\n";
    echo "  To: $recipientEmail\n";
    echo "  From: {$settings['from_email']} ({$settings['from_name']})\n";
    echo "  Subject: {$mail->Subject}\n";
    echo "  Sent at: " . date('Y-m-d H:i:s') . "\n\n";
    echo "Please check your inbox (and spam folder) for the test email.\n";
    
    // Log the email activity
    try {
        $stmt = $pdo->query("SELECT id FROM users LIMIT 1");
        $user = $stmt->fetch();
        $userId = $user ? $user['id'] : null;
        
        if ($userId) {
            $activityId = generateUUID();
            $stmt = $pdo->prepare("
                INSERT INTO mail_activity (user_id, email_type, recipient_email, status, details, created_at)
                VALUES (?, 'test', ?, 'sent', ?, datetime('now'))
            ");
            $stmt->execute([
                $userId,
                $recipientEmail,
                json_encode([
                    'subject' => $mail->Subject,
                    'message' => 'Test email sent successfully',
                    'provider' => $settings['provider']
                ])
            ]);
            echo "✅ Email activity logged\n";
        }
    } catch (Exception $e) {
        echo "⚠️  Warning: Could not log email activity: " . $e->getMessage() . "\n";
    }
    
} catch (Exception $e) {
    echo "❌ ERROR: Failed to send email\n";
    echo "  Error: {$mail->ErrorInfo}\n";
    echo "  Exception: {$e->getMessage()}\n";
    exit(1);
}

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

