<?php
/**
 * Test Email Sending Directly
 */

require_once 'config/config.php';
require_once 'classes/Database.php';

$db = Database::getInstance();

echo "=== Testing Email to ssandy8435@gmail.com ===\n\n";

// Get email settings from database
$settings = [];
$keys = ['mail_host', 'mail_port', 'mail_encryption', 'mail_username', 'mail_from_email', 'mail_from_name'];

echo "Fetching Email Configuration...\n";
foreach ($keys as $key) {
    $setting = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key = ?', [$key]);
    if ($setting) {
        $value = $setting['setting_value'];
        if ($key === 'mail_username') {
            echo "  $key: " . substr($value, 0, 5) . "***\n";
        } else {
            echo "  $key: $value\n";
        }
        $settings[$key] = $value;
    }
}

$passwordSetting = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key = ?', ['mail_password_encrypted']);
$password = !empty($passwordSetting['setting_value']) ? base64_decode($passwordSetting['setting_value']) : '';
echo "  mail_password_encrypted: " . (!empty($password) ? '[SET]' : 'NOT SET') . "\n\n";

$host = $settings['mail_host'] ?? 'smtp.gmail.com';
$port = (int)($settings['mail_port'] ?? 465);
$encryption = $settings['mail_encryption'] ?? 'ssl';
$username = $settings['mail_username'] ?? '';
$fromEmail = $settings['mail_from_email'] ?? '';
$fromName = $settings['mail_from_name'] ?? 'Advanced Mobile Info';
$testEmail = 'ssandy8435@gmail.com';

echo "SMTP Connection Details:\n";
echo "  Host: $host\n";
echo "  Port: $port\n";
echo "  Encryption: $encryption\n";
echo "  Username: $username\n";
echo "  From Email: $fromEmail\n";
echo "  Test To: $testEmail\n\n";

// Prepare email content
$subject = "Test Email from Advanced Mobile Info";
$body = "This is a test email from your Admin Email Settings panel.\n\n";
$body .= "Time: " . date('Y-m-d H:i:s') . "\n";
$body .= "From: $fromEmail\n";
$body .= "Application: Advanced Mobile Info\n\n";
$body .= "If you received this, your email configuration is working correctly!";

echo "Connecting to SMTP server...\n";

$protocol = ($encryption === 'tls') ? 'tls' : 'ssl';
$fp = fsockopen($protocol . '://' . $host, $port, $errno, $errstr, 10);

if (!$fp) {
    echo "❌ SMTP Connection Failed: $errstr ($errno)\n";
    echo "Falling back to PHP mail()...\n\n";
    
    $headers = "From: $fromName <$fromEmail>\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    
    if (mail($testEmail, $subject, $body, $headers)) {
        echo "✅ Test Email Sent Successfully via PHP Mail!\n\n";
        echo "Email Details:\n";
        echo "  To: $testEmail\n";
        echo "  Subject: $subject\n";
        echo "  From: $fromName <$fromEmail>\n";
        echo "  Status: Queued for delivery\n";
        echo "  Note: Email should arrive within 1-5 minutes on XAMPP\n";
    } else {
        echo "❌ Failed to send via PHP Mail\n";
    }
    exit;
}

echo "✅ Connected to SMTP!\n";

stream_set_blocking($fp, true);
stream_set_timeout($fp, 10);

try {
    // Read greeting
    $response = fgets($fp, 1024);
    echo "Server: " . trim($response) . "\n";
    
    // EHLO
    fwrite($fp, "EHLO localhost\r\n");
    while ($line = fgets($fp, 1024)) {
        if (preg_match('/^\d{3} /', $line)) break;
    }
    echo "✅ EHLO sent\n";
    
    // AUTH LOGIN
    fwrite($fp, "AUTH LOGIN\r\n");
    fgets($fp, 1024);
    
    // Username
    fwrite($fp, base64_encode($username) . "\r\n");
    fgets($fp, 1024);
    
    // Password
    fwrite($fp, base64_encode($password) . "\r\n");
    $response = fgets($fp, 1024);
    
    if (strpos($response, '235') === false) {
        echo "❌ SMTP Authentication Failed\n";
        echo "Response: " . trim($response) . "\n";
        fclose($fp);
        exit;
    }
    
    echo "✅ Authentication Successful!\n";
    
    // MAIL FROM
    fwrite($fp, "MAIL FROM:<$fromEmail>\r\n");
    $response = fgets($fp, 1024);
    echo "✅ MAIL FROM set\n";
    
    // RCPT TO
    fwrite($fp, "RCPT TO:<$testEmail>\r\n");
    $response = fgets($fp, 1024);
    echo "✅ RCPT TO set\n";
    
    // DATA
    fwrite($fp, "DATA\r\n");
    fgets($fp, 1024);
    
    // Compose message
    $headers = "From: $fromName <$fromEmail>\r\n";
    $headers .= "To: $testEmail\r\n";
    $headers .= "Subject: $subject\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    
    $message = $headers . "\r\n" . $body . "\r\n.\r\n";
    
    fwrite($fp, $message);
    $result = fgets($fp, 1024);
    
    if (strpos($result, '250') === 0) {
        echo "✅ Email Data Accepted\n\n";
        
        echo "🎉 Test Email Sent Successfully!\n\n";
        echo "Email Details:\n";
        echo "  To: $testEmail\n";
        echo "  Subject: Test Email from Advanced Mobile Info\n";
        echo "  From: $fromName <$fromEmail>\n";
        echo "  Status: Successfully queued for delivery\n";
        echo "  Method: SMTP over SSL\n";
        echo "  Note: Email should arrive within 1-5 minutes\n";
    } else {
        echo "❌ Failed to send: " . trim($result) . "\n";
    }
    
    fwrite($fp, "QUIT\r\n");
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}

fclose($fp);
?>
