<?php
/**
 * SMTP Environment Check
 * Verifies all requirements for SMTP email sending
 */

echo "=== SMTP Environment Check ===\n\n";

// 1. Check PHP version
echo "1. PHP Version: " . phpversion() . "\n";

// 2. Check OpenSSL
if (extension_loaded('openssl')) {
    echo "2. OpenSSL Extension: ✓ LOADED\n";
} else {
    echo "2. OpenSSL Extension: ✗ NOT LOADED (REQUIRED for SSL/TLS)\n";
}

// 3. Check Socket
if (function_exists('fsockopen')) {
    echo "3. fsockopen Function: ✓ AVAILABLE\n";
} else {
    echo "3. fsockopen Function: ✗ NOT AVAILABLE\n";
}

// 4. Test DNS resolution
echo "\n4. DNS Resolution Test:\n";
$host = 'mail.webappsofttech.com';
$ip = gethostbyname($host);
if ($ip !== $host) {
    echo "   {$host} resolves to: {$ip} ✓\n";
} else {
    echo "   {$host} DNS resolution FAILED ✗\n";
}

// 5. Test SMTP Port Connection
echo "\n5. SMTP Port 465 Connection Test:\n";
$errno = 0;
$errstr = '';
$timeout = 10;

// Test SSL connection to port 465
$fp = @fsockopen('ssl://' . $host, 465, $errno, $errstr, $timeout);
if ($fp) {
    echo "   Connection to ssl://{$host}:465 - ✓ SUCCESS\n";
    fclose($fp);
} else {
    echo "   Connection to ssl://{$host}:465 - ✗ FAILED\n";
    echo "   Error ({$errno}): {$errstr}\n";
}

// 6. Test alternative port 587 (TLS)
echo "\n6. Alternative SMTP Port 587 Test:\n";
$fp = @fsockopen($host, 587, $errno, $errstr, $timeout);
if ($fp) {
    echo "   Connection to {$host}:587 - ✓ SUCCESS\n";
    fclose($fp);
} else {
    echo "   Connection to {$host}:587 - ✗ FAILED\n";
}

// 7. Check CodeIgniter Email class
echo "\n7. CodeIgniter Email Library:\n";
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    echo "   Vendor autoload: ✓ FOUND\n";
} else {
    echo "   Vendor autoload: ✗ NOT FOUND\n";
}

// 8. Check writable logs directory
echo "\n8. Writable Directories:\n";
$logsDir = __DIR__ . '/../writable/logs/';
if (is_writable($logsDir)) {
    echo "   writable/logs/: ✓ WRITABLE\n";
} else {
    echo "   writable/logs/: ✗ NOT WRITABLE\n";
}

// 9. Check email config
echo "\n9. Email Configuration:\n";
$configFile = __DIR__ . '/../app/Config/Email.php';
if (file_exists($configFile)) {
    echo "   Email.php config: ✓ FOUND\n";
    require_once $configFile;
    if (class_exists('Config\Email')) {
        $config = new Config\Email();
        echo "   SMTP Host: {$config->SMTPHost}\n";
        echo "   SMTP Port: {$config->SMTPPort}\n";
        echo "   SMTP User: {$config->SMTPUser}\n";
        echo "   SMTP Crypto: {$config->SMTPCrypto}\n";
        echo "   Protocol: {$config->protocol}\n";
        echo "   Timeout: {$config->SMTPTimeout}s\n";
    }
} else {
    echo "   Email.php config: ✗ NOT FOUND\n";
}

echo "\n=== End of Check ===\n";
