#!/usr/bin/env php
<?php
/**
 * Magento 2.4.6 Health Monitor
 *
 * This script performs various health checks on a Magento 2.4.6 installation
 * to ensure the system is operating correctly.
 *
 * Usage: php magento_monitor.php [base_url] [options] [admin_path] [email_to]
 * Example: php magento_monitor.php https://mystore.com
 */

// Configuration
$config = [
    'timeout' => 30,          // Request timeout in seconds
    'user_agent' => 'Magento-Monitor/1.0',
    'alert_threshold' => 2.0, // Response time alert threshold in seconds
    'auth' => [
        'enabled' => false,    // Set to true to use HTTP Basic Auth
        'username' => 'agd',   // HTTP Basic Auth username
        'password' => 'agd',   // HTTP Basic Auth password
    ],
    'email' => [
        'enabled' => true,                      // Set to true to send email reports
        'to' => 'admin@example.com',             // Email recipient
        'from' => 'magento-monitor@example.com', // Email sender
        'subject_prefix' => '[Magento Monitor]', // Email subject prefix
        'only_on_error' => true,                 // Only send emails when errors are detected
        'smtp' => false,                         // Use command-line mail instead of PHP mail()
        'smtp_path' => '/usr/bin/mail',          // Path to mail command
    ],
    'endpoints' => [
        '/' => 'Homepage',
        '/customer/account/login/' => 'Login Page',
        '/carlige-de-remorcare.html' => 'Category Page',
        '/carlig-remorcare-toyota-avensis-verso-semidemontabil-hakpol-2001.html' => 'Product Page',
        '/checkout/cart/' => 'Cart Page',
        '/contact/' => 'Contact Page',
        '/catalogsearch/advanced/' => 'Advanced Search',
        '/rest/V1/modules' => 'REST API',
        '/health_check.php' => 'Custom Health Check'
    ],
    'admin_path' => 'admin',     // Default admin path
    'magento_root' => './',      // Magento root directory (current directory by default)
    'magento_bin' => './bin/magento', // Path to Magento CLI executable
    'enable_cli_checks' => true, // Whether to run CLI checks (database, indexers, cron)
];

// Parse command line arguments
$baseUrl = isset($argv[1]) ? $argv[1] : null;
$useAuth = false;
$emailArg = false;
$emailTo = null;
$adminPath = null;

// Process all arguments
for ($i = 2; $i < $argc; $i++) {
    $arg = $argv[$i];

    if ($arg === 'auth') {
        $useAuth = true;
    } elseif ($arg === 'email') {
        $emailArg = true;
    } elseif (filter_var($arg, FILTER_VALIDATE_EMAIL)) {
        $emailTo = $arg;
    } elseif ($arg === 'no-cli') {
        $config['enable_cli_checks'] = false;
    } elseif (!empty($arg) && !in_array($arg, ['auth', 'email', 'no-cli'])) {
        $adminPath = $arg;
    }
}

// Apply argument settings
if ($useAuth) {
    $config['auth']['enabled'] = true;
}

if ($emailArg) {
    $config['email']['enabled'] = true;
}

if ($emailTo) {
    $config['email']['to'] = $emailTo;
    $config['email']['enabled'] = true;
}

if ($adminPath) {
    $config['admin_path'] = $adminPath;
}

// Add protocol if missing
if ($baseUrl && !preg_match('/^https?:\/\//', $baseUrl)) {
    $baseUrl = "https://" . $baseUrl;
}

$baseUrl = rtrim($baseUrl, '/');

if (!$baseUrl) {
    echo "Please provide a base URL for your Magento installation.\n";
    echo "Usage: php magento_monitor.php [base_url] [options] [admin_path] [email_to]\n";
    echo "  [base_url]   : URL of your Magento installation\n";
    echo "  [options]    : Optional. Use 'auth', 'email', and/or 'no-cli'\n";
    echo "  [admin_path] : Optional. Override the default admin path\n";
    echo "  [email_to]   : Optional. Email address to send the report to\n";
    echo "\nExamples:\n";
    echo "  php magento_monitor.php example.com\n";
    echo "  php magento_monitor.php preprod.example.com auth\n";
    echo "  php magento_monitor.php example.com email admin@example.com\n";
    echo "  php magento_monitor.php example.com auth custom_admin\n";
    echo "  php magento_monitor.php example.com auth email admin@example.com\n";
    echo "  php magento_monitor.php example.com no-cli\n";
    exit(1);
}

// Initialize results array
$results = [
    'timestamp' => date('Y-m-d H:i:s'),
    'base_url' => $baseUrl,
    'overall_status' => 'UNKNOWN',
    'checks' => [],
    'errors' => [],
    'warnings' => [],
    'network_diagnostics' => []
];

// Test DNS resolution first
echo "Checking DNS resolution for " . parse_url($baseUrl, PHP_URL_HOST) . "...\n";
$host = parse_url($baseUrl, PHP_URL_HOST);
$dnsCheck = checkdnsrr($host, 'A');
if (!$dnsCheck) {
    echo "  - " . colorizeStatus('ERROR') . ": Cannot resolve hostname '{$host}'\n";
    echo "    This indicates a DNS issue. Check your domain configuration.\n\n";
    $results['network_diagnostics']['dns'] = [
        'status' => 'ERROR',
        'message' => "Cannot resolve hostname '{$host}'"
    ];
} else {
    echo "  - " . colorizeStatus('OK') . ": Hostname '{$host}' resolved successfully\n";
    $results['network_diagnostics']['dns'] = [
        'status' => 'OK',
        'message' => "Hostname '{$host}' resolved successfully"
    ];
}

// Verify if we're in a Magento root directory
if ($config['enable_cli_checks']) {
    $magentoCliPath = $config['magento_bin'];
    if (!file_exists($magentoCliPath)) {
        echo "Warning: Magento CLI not found at {$magentoCliPath}. CLI checks will be skipped.\n";
        echo "Make sure you're running this script from the Magento root directory.\n";
        $config['enable_cli_checks'] = false;
    }
}

// Setup HTTP client options with Basic Authentication
$authHeader = '';
if ($config['auth']['enabled'] && $config['auth']['username'] && $config['auth']['password']) {
    $authHeader = "Authorization: Basic " . base64_encode($config['auth']['username'] . ':' . $config['auth']['password']) . "\r\n";
    echo "Using HTTP Basic Authentication with username: {$config['auth']['username']}\n";
}

$contextOptions = [
    'http' => [
        'method' => 'GET',
        'timeout' => $config['timeout'],
        'header' => "User-Agent: {$config['user_agent']}\r\n" .
            "Accept: text/html,application/json\r\n" .
            $authHeader,
        'ignore_errors' => true // Don't fail on HTTP error codes
    ],
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
];
$context = stream_context_create($contextOptions);

echo "Starting Magento 2.4.6 Health Monitor on {$baseUrl}\n";
echo "==================================================\n\n";

// Check if Magento is accessible
checkMagentoAccess($baseUrl, $context, $results);

// Check key endpoints
foreach ($config['endpoints'] as $endpoint => $name) {
    checkEndpoint($baseUrl . $endpoint, $name, $context, $results, $config['alert_threshold']);
}

// Check admin access
checkAdminAccess($baseUrl, $config['admin_path'], $context, $results);

// Check Media and Static files
checkStaticResources($baseUrl, $context, $results);

// Check Redis if available (optional)
checkRedis($results);

// Check Database connection via CLI
checkDatabase($config, $results);

// Check indexer status
checkIndexers($config, $results);

// Check cron jobs
checkCronJobs($config, $results);

// Run network diagnostics
testNetworkConnectivity($baseUrl, $results);

// Determine overall status
$errorCount = count($results['errors']);
$warningCount = count($results['warnings']);

if ($errorCount > 0) {
    $results['overall_status'] = 'ERROR';
} elseif ($warningCount > 0) {
    $results['overall_status'] = 'WARNING';
} else {
    $results['overall_status'] = 'OK';
}

// Output summary
echo "\nMonitoring Summary\n";
echo "=================\n";
echo "Status: " . colorizeStatus($results['overall_status']) . "\n";
echo "Errors: {$errorCount}, Warnings: {$warningCount}\n";
echo "Timestamp: {$results['timestamp']}\n\n";

if ($errorCount > 0) {
    echo "ERRORS:\n";
    foreach ($results['errors'] as $error) {
        echo "- {$error}\n";
    }
    echo "\n";
}

if ($warningCount > 0) {
    echo "WARNINGS:\n";
    foreach ($results['warnings'] as $warning) {
        echo "- {$warning}\n";
    }
    echo "\n";
}

// Save results to JSON file
$outputFile = 'magento_monitor_' . date('Ymd_His') . '.json';
file_put_contents($outputFile, json_encode($results, JSON_PRETTY_PRINT));
echo "Results saved to: {$outputFile}\n";

// Send email report if enabled
if ($config['email']['enabled']) {
    sendEmailReport($results, $config['email'], $baseUrl);
}

// Helper Functions

function checkMagentoAccess($baseUrl, $context, &$results) {
    echo "Checking Magento access...\n";

    $start = microtime(true);
    $http_response_header = null;
    $content = @file_get_contents($baseUrl, false, $context);
    $duration = microtime(true) - $start;

    // Check HTTP headers if available
    $statusCode = null;
    $statusMessage = '';
    if (!empty($http_response_header)) {
        foreach ($http_response_header as $header) {
            if (strpos($header, 'HTTP/') === 0) {
                $parts = explode(' ', $header, 3);
                if (isset($parts[1])) {
                    $statusCode = (int)$parts[1];
                    $statusMessage = isset($parts[2]) ? $parts[2] : '';
                }
                break;
            }
        }
    }

    if ($content === false) {
        $errorMessage = 'Cannot access Magento installation';
        if ($statusCode) {
            $errorMessage .= " (HTTP $statusCode $statusMessage)";
        } elseif (isset($php_errormsg)) {
            $errorMessage .= " (Error: $php_errormsg)";
        } elseif (error_get_last()) {
            $error = error_get_last();
            $errorMessage .= " (Error: {$error['message']})";
        }

        $results['checks']['magento_access'] = [
            'status' => 'ERROR',
            'message' => $errorMessage,
            'duration' => $duration
        ];
        $results['errors'][] = 'Cannot access Magento at ' . $baseUrl;
        echo "  - " . colorizeStatus('ERROR') . ": $errorMessage ({$duration}s)\n";
        return;
    }

    // Check if it's really Magento by looking for specific patterns
    $isMagento = (
        strpos($content, 'Magento') !== false ||
        strpos($content, 'mage/') !== false ||
        strpos($content, 'Mage.') !== false
    );

    if (!$isMagento) {
        $results['checks']['magento_access'] = [
            'status' => 'WARNING',
            'message' => 'Page accessed but Magento signatures not found',
            'duration' => $duration
        ];
        $results['warnings'][] = 'Site accessible but may not be Magento';
        echo "  - " . colorizeStatus('WARNING') . ": Site accessible but may not be Magento ({$duration}s)\n";
    } else {
        $results['checks']['magento_access'] = [
            'status' => 'OK',
            'message' => 'Magento installation accessible',
            'duration' => $duration
        ];
        echo "  - " . colorizeStatus('OK') . ": Magento installation accessible ({$duration}s)\n";
    }
}

function checkEndpoint($url, $name, $context, &$results, $thresholdSeconds) {
    echo "Checking {$name}...\n";

    $start = microtime(true);
    $http_response_header = null;
    $content = @file_get_contents($url, false, $context);
    $duration = microtime(true) - $start;

    // Check HTTP headers if available
    $statusCode = null;
    $statusMessage = '';
    if (!empty($http_response_header)) {
        foreach ($http_response_header as $header) {
            if (strpos($header, 'HTTP/') === 0) {
                $parts = explode(' ', $header, 3);
                if (isset($parts[1])) {
                    $statusCode = (int)$parts[1];
                    $statusMessage = isset($parts[2]) ? $parts[2] : '';
                }
                break;
            }
        }
    }

    $status = 'OK';
    $message = "{$name} accessible";

    if ($content === false) {
        $status = 'ERROR';
        $message = "Cannot access {$name}";
        if ($statusCode) {
            $message .= " (HTTP $statusCode $statusMessage)";
        } elseif (isset($php_errormsg)) {
            $message .= " (Error: $php_errormsg)";
        } elseif (error_get_last()) {
            $error = error_get_last();
            $message .= " (Error: {$error['message']})";
        }
        $results['errors'][] = "Cannot access {$name} at {$url}";
    } elseif ($statusCode && ($statusCode < 200 || $statusCode >= 400)) {
        $status = 'ERROR';
        $message = "{$name} returned HTTP $statusCode $statusMessage";
        $results['errors'][] = "{$name} at {$url} returned HTTP $statusCode $statusMessage";
    } elseif ($duration > $thresholdSeconds) {
        $status = 'WARNING';
        $message = "{$name} accessible but response time exceeds threshold";
        $results['warnings'][] = "{$name} response time ({$duration}s) exceeds threshold of {$thresholdSeconds}s";
    }

    $results['checks'][strtolower(str_replace(' ', '_', $name))] = [
        'status' => $status,
        'message' => $message,
        'duration' => $duration,
        'url' => $url
    ];

    echo "  - " . colorizeStatus($status) . ": {$message} ({$duration}s)\n";
}

function checkAdminAccess($baseUrl, $adminPath, $context, &$results) {
    $adminUrl = "{$baseUrl}/{$adminPath}";
    echo "Checking Admin access...\n";

    $start = microtime(true);
    $content = @file_get_contents($adminUrl, false, $context);
    $duration = microtime(true) - $start;

    if ($content === false) {
        $results['checks']['admin_access'] = [
            'status' => 'WARNING',
            'message' => 'Cannot access Admin area - path may be customized',
            'duration' => $duration
        ];
        $results['warnings'][] = "Cannot access Admin area at {$adminUrl} - path may be customized";
        echo "  - " . colorizeStatus('WARNING') . ": Cannot access Admin area - path may be customized ({$duration}s)\n";
    } else {
        // Check if it's really the admin login page
        $isAdminLogin = (
            strpos($content, 'admin/login') !== false ||
            strpos($content, 'adminhtml') !== false ||
            strpos($content, 'login-form') !== false
        );

        if ($isAdminLogin) {
            $results['checks']['admin_access'] = [
                'status' => 'OK',
                'message' => 'Admin login page accessible',
                'duration' => $duration
            ];
            echo "  - " . colorizeStatus('OK') . ": Admin login page accessible ({$duration}s)\n";
        } else {
            $results['checks']['admin_access'] = [
                'status' => 'WARNING',
                'message' => 'Admin URL accessible but login page not detected',
                'duration' => $duration
            ];
            $results['warnings'][] = "Admin URL accessible but login page not detected";
            echo "  - " . colorizeStatus('WARNING') . ": Admin URL accessible but login page not detected ({$duration}s)\n";
        }
    }
}

function checkStaticResources($baseUrl, $context, &$results) {
    echo "Checking static resources...\n";

    $resourcePaths = [
        '/static/frontend/Magento/luma/en_US/mage/calendar.css' => 'CSS Resource',
        '/static/frontend/Magento/luma/en_US/jquery.js' => 'JavaScript Resource',
        '/media/catalog/product/placeholder/default/placeholder.jpg' => 'Media Resource'
    ];

    foreach ($resourcePaths as $path => $name) {
        $url = $baseUrl . $path;
        $start = microtime(true);
        $content = @file_get_contents($url, false, $context);
        $duration = microtime(true) - $start;

        if ($content === false) {
            $results['checks'][strtolower(str_replace(' ', '_', $name))] = [
                'status' => 'WARNING',
                'message' => "Cannot access {$name}",
                'duration' => $duration,
                'url' => $url
            ];
            $results['warnings'][] = "Cannot access {$name} at {$url}";
            echo "  - " . colorizeStatus('WARNING') . ": Cannot access {$name} ({$duration}s)\n";
        } else {
            $results['checks'][strtolower(str_replace(' ', '_', $name))] = [
                'status' => 'OK',
                'message' => "{$name} accessible",
                'duration' => $duration,
                'url' => $url
            ];
            echo "  - " . colorizeStatus('OK') . ": {$name} accessible ({$duration}s)\n";
        }
    }
}

function checkRedis($results) {
    echo "Checking Redis connection...\n";

    if (!class_exists('Redis')) {
        echo "  - " . colorizeStatus('SKIPPED') . ": Redis PHP extension not installed\n";
        return;
    }

    try {
        $redis = new Redis();
        $connected = $redis->connect('127.0.0.1', 6379, 2);

        if (!$connected) {
            $results['checks']['redis'] = [
                'status' => 'WARNING',
                'message' => 'Cannot connect to Redis'
            ];
            $results['warnings'][] = "Cannot connect to Redis";
            echo "  - " . colorizeStatus('WARNING') . ": Cannot connect to Redis\n";
            return;
        }

        $ping = $redis->ping();
        if ($ping) {
            $results['checks']['redis'] = [
                'status' => 'OK',
                'message' => 'Redis connection successful'
            ];
            echo "  - " . colorizeStatus('OK') . ": Redis connection successful\n";
        } else {
            $results['checks']['redis'] = [
                'status' => 'WARNING',
                'message' => 'Redis connected but ping failed'
            ];
            $results['warnings'][] = "Redis connected but ping failed";
            echo "  - " . colorizeStatus('WARNING') . ": Redis connected but ping failed\n";
        }
    } catch (Exception $e) {
        $results['checks']['redis'] = [
            'status' => 'WARNING',
            'message' => 'Redis exception: ' . $e->getMessage()
        ];
        $results['warnings'][] = "Redis exception: " . $e->getMessage();
        echo "  - " . colorizeStatus('WARNING') . ": Redis exception: " . $e->getMessage() . "\n";
    }
}

function checkDatabase($config, &$results) {
    echo "Checking database connection...\n";

    if (!$config['enable_cli_checks']) {
        echo "  - " . colorizeStatus('SKIPPED') . ": CLI checks disabled\n";
        return;
    }

    $command = $config['magento_bin'] . " setup:db:status";
    exec($command . " 2>&1", $output, $returnCode);

    if ($returnCode === 0) {
        $results['checks']['database'] = [
            'status' => 'OK',
            'message' => 'Database connection successful and schema is up-to-date'
        ];
        echo "  - " . colorizeStatus('OK') . ": Database connection successful and schema is up-to-date\n";
    } elseif ($returnCode === 1) {
        // Code 1 typically means database upgrades are available
        $results['checks']['database'] = [
            'status' => 'WARNING',
            'message' => 'Database schema is not up-to-date'
        ];
        $results['warnings'][] = "Database schema is not up-to-date";
        echo "  - " . colorizeStatus('WARNING') . ": Database schema is not up-to-date\n";
        echo "    Run 'bin/magento setup:upgrade' to update the database schema\n";
    } else {
        // Any other return code indicates a problem
        $errorMessage = implode("\n", $output);
        $results['checks']['database'] = [
            'status' => 'ERROR',
            'message' => 'Database connection error: ' . $errorMessage
        ];
        $results['errors'][] = "Database connection error: " . $errorMessage;
        echo "  - " . colorizeStatus('ERROR') . ": Database connection error\n";
        echo "    " . $errorMessage . "\n";
    }
}

function checkIndexers($config, &$results) {
    echo "Checking indexer status...\n";

    if (!$config['enable_cli_checks']) {
        echo "  - " . colorizeStatus('SKIPPED') . ": CLI checks disabled\n";
        return;
    }

    $command = $config['magento_bin'] . " indexer:status";
    exec($command . " 2>&1", $output, $returnCode);

    if ($returnCode !== 0) {
        $errorMessage = implode("\n", $output);
        $results['checks']['indexers'] = [
            'status' => 'ERROR',
            'message' => 'Error checking indexer status: ' . $errorMessage
        ];
        $results['errors'][] = "Error checking indexer status: " . $errorMessage;
        echo "  - " . colorizeStatus('ERROR') . ": Error checking indexer status\n";
        echo "    " . $errorMessage . "\n";
        return;
    }

    $reindexNeeded = false;
    $invalidIndexers = [];

    foreach ($output as $line) {
        if (strpos($line, 'Reindex required') !== false) {
            $reindexNeeded = true;
            // Extract indexer name from the output line
            if (preg_match('/^([^:]+):/', $line, $matches)) {
                $indexerName = trim($matches[1]);
                $invalidIndexers[] = $indexerName;
            }
        }
    }

    if ($reindexNeeded) {
        $results['checks']['indexers'] = [
            'status' => 'WARNING',
            'message' => 'Some indexers need reindexing',
            'invalid_indexers' => $invalidIndexers
        ];
        $results['warnings'][] = "Some indexers need reindexing: " . implode(", ", $invalidIndexers);
        echo "  - " . colorizeStatus('WARNING') . ": Some indexers need reindexing\n";
        echo "    Run 'bin/magento indexer:reindex' to reindex all or specify indexers to reindex\n";

        foreach ($invalidIndexers as $indexer) {
            echo "    - {$indexer}: Reindex required\n";
        }
    } else {
        $results['checks']['indexers'] = [
            'status' => 'OK',
            'message' => 'All indexers are up-to-date'
        ];
        echo "  - " . colorizeStatus('OK') . ": All indexers are up-to-date\n";
    }
}

function checkCronJobs($config, &$results) {
    echo "Checking cron jobs...\n";

    if (!$config['enable_cli_checks']) {
        echo "  - " . colorizeStatus('SKIPPED') . ": CLI checks disabled\n";
        return;
    }

    // First check if cron is set up properly
    $command = $config['magento_bin'] . " cron:status";
    exec($command . " 2>&1", $output, $returnCode);

    if ($returnCode !== 0) {
        $errorMessage = implode("\n", $output);
        $results['checks']['cron_jobs'] = [
            'status' => 'ERROR',
            'message' => 'Error checking cron status: ' . $errorMessage
        ];
        $results['errors'][] = "Error checking cron status: " . $errorMessage;
        echo "  - " . colorizeStatus('ERROR') . ": Error checking cron status\n";
        echo "    " . $errorMessage . "\n";
        return;
    }

    // Check if we have any running crons that are stuck
    // This uses direct database access via bin/magento
    $commandRunningCrons = $config['magento_bin'] . " cron:status";
    exec($commandRunningCrons . " 2>&1", $runningOutput, $runningReturnCode);

    if (count($runningOutput) > 0 && strpos(implode("\n", $runningOutput), "Cron works") !== false) {
        $results['checks']['cron_jobs'] = [
            'status' => 'OK',
            'message' => 'Cron is properly set up and functioning'
        ];
        echo "  - " . colorizeStatus('OK') . ": Cron is properly set up and functioning\n";
    } else {
        $results['checks']['cron_jobs'] = [
            'status' => 'WARNING',
            'message' => 'Cron may not be properly configured'
        ];
        $results['warnings'][] = "Cron may not be properly configured";
        echo "  - " . colorizeStatus('WARNING') . ": Cron may not be properly configured\n";
        echo "    Make sure cron is set up properly following Magento documentation\n";
    }

    // Check for any stuck cron jobs
    $commandStuckCrons = $config['magento_bin'] . " dev:query \"SELECT * FROM cron_schedule WHERE status = 'running' AND TIMESTAMPDIFF(MINUTE, updated_at, NOW()) > 30\"";
    exec($commandStuckCrons . " 2>&1", $stuckOutput, $stuckReturnCode);

    if ($stuckReturnCode === 0 && !empty($stuckOutput) && count($stuckOutput) > 1) {
        // First line is usually header, so more than 1 line means we have results
        $results['checks']['stuck_crons'] = [
            'status' => 'WARNING',
            'message' => 'Stuck cron jobs detected'
        ];
        $results['warnings'][] = "Stuck cron jobs detected that have been running for over 30 minutes";
        echo "  - " . colorizeStatus('WARNING') . ": Stuck cron jobs detected\n";
        echo "    Run 'bin/magento cron:unlock' to release locks on stuck cron jobs\n";
    }
}

function testNetworkConnectivity($baseUrl, &$results) {
    $host = parse_url($baseUrl, PHP_URL_HOST);
    $scheme = parse_url($baseUrl, PHP_URL_SCHEME);
    $port = ($scheme == 'https') ? 443 : 80;

    echo "\nNetwork Diagnostics\n";
    echo "=================\n";

    // Test basic connectivity
    echo "Testing TCP connectivity to $host:$port...\n";
    $connection = @fsockopen($host, $port, $errno, $errstr, 5);

    if ($connection) {
        echo "  - " . colorizeStatus('OK') . ": Connection to $host:$port successful\n";
        $results['network_diagnostics']['tcp_connection'] = [
            'status' => 'OK',
            'message' => "Connection to $host:$port successful"
        ];
        fclose($connection);
    } else {
        echo "  - " . colorizeStatus('ERROR') . ": Cannot connect to $host:$port - Error $errno: $errstr\n";
        $results['network_diagnostics']['tcp_connection'] = [
            'status' => 'ERROR',
            'message' => "Cannot connect to $host:$port - Error $errno: $errstr"
        ];
        $results['errors'][] = "Network connectivity issue: Cannot connect to $host:$port";
    }

    // Add traceroute if available
    if (function_exists('exec')) {
        $tracerouteCmd = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? "tracert $host" : "traceroute -m 10 $host";
        echo "\nTraceroute to $host:\n";
        echo "-------------------\n";

        $tracerouteOutput = [];
        @exec($tracerouteCmd . " 2>&1", $tracerouteOutput, $tracerouteReturnVar);

        if ($tracerouteReturnVar === 0 || $tracerouteReturnVar === 1) {
            // On some systems, traceroute exits with code 1 but still provides useful output
            foreach ($tracerouteOutput as $line) {
                echo "  $line\n";
            }
            $results['network_diagnostics']['traceroute'] = [
                'output' => $tracerouteOutput
            ];
        } else {
            echo "  Traceroute command not available or failed\n";
            $results['network_diagnostics']['traceroute'] = [
                'status' => 'SKIPPED',
                'message' => "Traceroute command not available or failed"
            ];
        }
    }
}

function colorizeStatus($status) {
// Check if we're running in a terminal that supports colors
    $useColors = (function_exists('posix_isatty') && posix_isatty(STDOUT)) ||
        (getenv('TERM') && getenv('TERM') != 'dumb');

    if (!$useColors) {
        return $status;
    }

    switch ($status) {
        case 'OK':
            return "\033[32mOK\033[0m";        // Green
        case 'WARNING':
            return "\033[33mWARNING\033[0m";   // Yellow
        case 'ERROR':
            return "\033[31mERROR\033[0m";     // Red
        case 'SKIPPED':
            return "\033[36mSKIPPED\033[0m";   // Cyan
        default:
            return $status;
    }
}function sendAlternativeEmail($to, $subject, $body, $from) {
// Try several different mail methods for Ubuntu

// Method 1: Using mail command
    $mailCmd = "mail -s " . escapeshellarg($subject) . " " .
        escapeshellarg($to) . " -- " .
        "-f " . escapeshellarg($from);

    $tempFile = tempnam(sys_get_temp_dir(), 'magento_monitor_');
    file_put_contents($tempFile, $body);

    $mailOutput = [];
    exec("cat " . escapeshellarg($tempFile) . " | " . $mailCmd, $mailOutput, $mailResult);
    unlink($tempFile);

    if ($mailResult === 0) {
        echo "Email report sent to {$to} using mail command\n";
        return true;
    }

// Method 2: Using sendmail directly
    $sendmailPath = '/usr/sbin/sendmail';
    if (file_exists($sendmailPath)) {
        try {
            $handle = popen($sendmailPath . " -t -i", "w");
            fputs($handle, "To: {$to}\r\n");
            fputs($handle, "Subject: {$subject}\r\n");
            fputs($handle, "From: {$from}\r\n");
            fputs($handle, "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
            fputs($handle, $body);
            $result = pclose($handle);

            if ($result === 0) {
                echo "Email report sent to {$to} using sendmail\n";
                return true;
            }
        } catch (Exception $e) {
            echo "Error using sendmail: " . $e->getMessage() . "\n";
        }
    }

// Method 3: Write to a file that can be manually sent
    $emailFile = 'magento_monitor_email_' . date('Ymd_His') . '.txt';
    file_put_contents($emailFile, "To: {$to}\r\nSubject: {$subject}\r\nFrom: {$from}\r\n\r\n{$body}");
    echo "Email report saved to file: {$emailFile}\n";
    echo "Could not send email automatically. Please send this file manually.\n";

    return false;
}function sendEmailReport($results, $emailConfig, $baseUrl) {
// Check if we should send email (only on error or always)
    $errorCount = count($results['errors']);
    if ($emailConfig['only_on_error'] && $errorCount === 0) {
        echo "No errors detected, skipping email report.\n";
        return;
    }

// Create email subject based on status
    $subject = $emailConfig['subject_prefix'];

    if ($results['overall_status'] === 'ERROR') {
        $subject .= " [ERROR] ";
    } elseif ($results['overall_status'] === 'WARNING') {
        $subject .= " [WARNING] ";
    } else {
        $subject .= " [OK] ";
    }

    $subject .= $baseUrl . " - " . $results['timestamp'];

// Create email body
    $body = "Magento Health Monitor Report\n";
    $body .= "===========================\n\n";
    $body .= "Site: $baseUrl\n";
    $body .= "Status: {$results['overall_status']}\n";
    $body .= "Timestamp: {$results['timestamp']}\n";
    $body .= "Errors: {$errorCount}, Warnings: " . count($results['warnings']) . "\n\n";

    if ($errorCount > 0) {
        $body .= "ERRORS:\n";
        foreach ($results['errors'] as $error) {
            $body .= "- {$error}\n";
        }
        $body .= "\n";
    }

    if (count($results['warnings']) > 0) {
        $body .= "WARNINGS:\n";
        foreach ($results['warnings'] as $warning) {
            $body .= "- {$warning}\n";
        }
        $body .= "\n";
    }

    $body .= "DETAILED RESULTS:\n";
    foreach ($results['checks'] as $checkName => $check) {
        $body .= "- " . ucfirst(str_replace('_', ' ', $checkName)) . ": {$check['status']}";
        if (isset($check['duration'])) {
            $body .= " ({$check['duration']}s)";
        }
        $body .= "\n";
    }

// Check if we should use command-line mail
    if ($emailConfig['smtp']) {
// Try to use the system mail command
        $mailCmd = $emailConfig['smtp_path'] . " -s " . escapeshellarg($subject) . " " .
            escapeshellarg($emailConfig['to']) . " -- " .
            "-f " . escapeshellarg($emailConfig['from']);

// Write body to a temporary file
        $tempFile = tempnam(sys_get_temp_dir(), 'magento_monitor_');
        file_put_contents($tempFile, $body);

// Send email with system mail command
        $mailOutput = [];
        exec("cat " . escapeshellarg($tempFile) . " | " . $mailCmd, $mailOutput, $mailResult);
        unlink($tempFile);

        if ($mailResult === 0) {
            echo "Email report sent to {$emailConfig['to']} using system mail command\n";
        } else {
            echo "Failed to send email report: " . implode("\n", $mailOutput) . "\n";
            echo "Trying alternative method...\n";
            sendAlternativeEmail($emailConfig['to'], $subject, $body, $emailConfig['from']);
        }
    } else {
// Try PHP's mail function
        $headers = "From: {$emailConfig['from']}\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

        if (mail($emailConfig['to'], $subject, $body, $headers)) {
            echo "Email report sent to {$emailConfig['to']}\n";
        } else {
            echo "Failed to send email with PHP mail(). Trying alternative method...\n";
            sendAlternativeEmail($emailConfig['to'], $subject, $body, $emailConfig['from']);
        }
    }
}
