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

$db = Database::getInstance();

echo "=== Testing Admin Test Email Feature ===\n\n";

// Simulate admin sending test email
$testEmail = 'ssandy8435@gmail.com';

echo "Target Email: $testEmail\n";
echo "Time: " . date('Y-m-d H:i:s') . "\n\n";

// Get email settings from database
echo "Current Email Configuration:\n";
$settings = [];
$keys = ['email_mode', 'mail_host', 'mail_port', 'mail_encryption', 'mail_username', 'mail_from_email', 'mail_from_name'];

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']);
echo "  mail_password_encrypted: " . (!empty($passwordSetting['setting_value']) ? '[ENCRYPTED]' : 'NOT SET') . "\n\n";

// Send test email using simple SMTP
echo "Sending Test Email...\n\n";

$host = $settings['mail_host'] ?? 'smtp.gmail.com';
$port = (int)($settings['mail_port'] ?? 465);
$encryption = $settings['mail_encryption'] ?? 'ssl';
$username = $settings['mail_username'] ?? '';
$password = !empty($passwordSetting['setting_value']) ? base64_decode($passwordSetting['setting_value']) : '';
$fromEmail = $settings['mail_from_email'] ?? '';
$fromName = $settings['mail_from_name'] ?? 'Advanced Mobile Info';

$protocol = ($encryption === 'tls') ? 'tls' : 'ssl';

echo "Connecting to: $host:$port ($encryption)\n";
$fp = fsockopen($protocol . '://' . $host, $port, $errno, $errstr, 10);

if (!$fp) {
    echo "❌ SMTP Connection Failed: $errstr ($errno)\n";
    echo "Trying PHP mail() fallback...\n\n";
    
    $subject = "Test Email from Advanced Mobile Info";
    $body = "This is a test email from Admin Email Settings panel.\n\n";
    $body .= "Time: " . date('Y-m-d H:i:s') . "\n";
    $body .= "From: $fromEmail\n";
    $body .= "App: Advanced Mobile Info\n\n";
    $body .= "If you received this, the email system is working!";
    
    $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 "Details:\n";
        echo "  To: $testEmail\n";
        echo "  Subject: $subject\n";
        echo "  Status: Queued for delivery\n";
    } else {
        echo "❌ Failed to send via PHP Mail\n";
    }
    exit;
}

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

// Helper function to read SMTP response
$readResponse = function($fp) {
    $response = '';
    while (!feof($fp)) {
        $line = fgets($fp, 1024);
        if ($line === false) break;
        $response .= $line;
        if (preg_match('/^\d{3} /', $line)) break;
    }
    return $response;
};

// Read greeting
$response = $readResponse($fp);
echo "✅ Connected!\n";

// EHLO
fwrite($fp, "EHLO localhost\r\n");
$response = $readResponse($fp);

// AUTH LOGIN
fwrite($fp, "AUTH LOGIN\r\n");
$response = fgets($fp, 1024);

// Username
fwrite($fp, base64_encode($username) . "\r\n");
$response = 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";
    fclose($fp);
    exit;
}

echo "✅ Authentication Successful!\n";

// MAIL FROM
fwrite($fp, "MAIL FROM:<$fromEmail>\r\n");
fgets($fp, 1024);

// RCPT TO
fwrite($fp, "RCPT TO:<$testEmail>\r\n");
fgets($fp, 1024);

// DATA
fwrite($fp, "DATA\r\n");
fgets($fp, 1024);

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

$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 "✅ Test Email Sent Successfully!\n\n";
    echo "Details:\n";
    echo "  To: $testEmail\n";
    echo "  Subject: Test Email from Advanced Mobile Info\n";
    echo "  Status: Successfully queued for delivery\n";
    echo "  Method: SMTP\n";
} else {
    echo "❌ Failed to send email: " . trim($result) . "\n";
}

fwrite($fp, "QUIT\r\n");
fclose($fp);

echo "\n✅ Test completed!\n";
?>
