<?php
namespace App\Utils;

use App\Config\Database;

class DaemonMonitor {
    public static function checkAndAlert() {
        try {
            $db = Database::getInstance()->getConnection();
            
            // Fetch relevant settings in one query
            $stmt = $db->query("
                SELECT setting_key, setting_value 
                FROM settings 
                WHERE setting_key IN ('scheduler_active', 'scheduler_last_heartbeat', 'scheduler_downtime_emails', 'scheduler_downtime_alert_sent')
            ");
            $settings = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR);
            
            $isActive = $settings['scheduler_active'] ?? '0';
            if ($isActive !== '1') {
                return; // Scheduler is stopped intentionally, no alert needed
            }
            
            $downtimeEmails = trim($settings['scheduler_downtime_emails'] ?? '');
            if (empty($downtimeEmails)) {
                return; // No recipients configured
            }
            
            $lastHeartbeat = $settings['scheduler_last_heartbeat'] ?? null;
            if (!$lastHeartbeat) {
                return; // Never started
            }
            
            $alertSent = $settings['scheduler_downtime_alert_sent'] ?? '0';
            
            // Check if heartbeat is older than 5 minutes
            $lastHbTime = strtotime($lastHeartbeat);
            $now = time();
            $diffMinutes = floor(($now - $lastHbTime) / 60);
            
            if ($diffMinutes > 5) {
                // It is disconnected!
                if ($alertSent === '0') {
                    // Send alert!
                    $subject = "🚨 URGENT: NexCore Pharma Scheduler is Disconnected";
                    $body = <<<HTML
<!DOCTYPE html>
<html>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
    <h2 style="color: #e11d48;">Scheduler Daemon Disconnected</h2>
    <p>The background scheduler engine for NexCore Pharma has stopped responding.</p>
    <p><strong>Last Heartbeat:</strong> {$lastHeartbeat}</p>
    <p><strong>Downtime:</strong> {$diffMinutes} minutes</p>
    <p>Please log in to the Superadmin Portal and restart the scheduler daemon immediately to ensure expiry alerts are sent.</p>
</body>
</html>
HTML;
                    SimpleMailer::send($downtimeEmails, $subject, $body);
                    
                    // Mark as sent
                    $db->exec("
                        INSERT INTO settings (setting_key, setting_value) 
                        VALUES ('scheduler_downtime_alert_sent', '1') 
                        ON DUPLICATE KEY UPDATE setting_value = '1'
                    ");
                }
            } else {
                // It is connected. Reset the alert sent flag if it was 1
                if ($alertSent === '1') {
                    $db->exec("UPDATE settings SET setting_value = '0' WHERE setting_key = 'scheduler_downtime_alert_sent'");
                }
            }
        } catch (\Exception $e) {
            // Silently fail to not interrupt the user's web request
            error_log("DaemonMonitor Error: " . $e->getMessage());
        }
    }
}
