<?php
/**
 * سودانا — SupportEngines v2
 * SystemHealthMonitor | Monitoring | ReinforcementEngine | SelfLearningEngine | RevenueBrain
 */

class SystemHealthMonitor {
    public static function isSystemHealthy(): bool {
        try {
            $failures = (int)db()->query(
                "SELECT COUNT(*) FROM tasks WHERE status='failed' AND created_at > DATE_SUB(NOW(), INTERVAL 5 MINUTE)"
            )->fetchColumn();
            if ($failures > 10) { Monitoring::log('safety.kill_switch', 1, ['failures'=>$failures]); return false; }
            return true;
        } catch (Throwable $e) { error_log("[SystemHealthMonitor] " . $e->getMessage()); return false; }
    }
}

class Monitoring {
    public static function log(string $metric, float $value, array $context = []): void {
        try {
            db()->prepare("INSERT INTO ai_metrics (metric, value, context, created_at) VALUES (?,?,?,NOW())")
                ->execute([$metric, $value, $context ? json_encode($context, JSON_UNESCAPED_UNICODE) : null]);
        } catch (Throwable $e) { error_log("[Monitoring] " . $e->getMessage()); }
    }
    public static function failureRate(int $minutes = 5): int {
        try { return (int)db()->query("SELECT COUNT(*) FROM tasks WHERE status='failed' AND created_at > DATE_SUB(NOW(), INTERVAL $minutes MINUTE)")->fetchColumn(); }
        catch (Throwable $e) { return -1; }
    }
}

class ReinforcementEngine {
    public static function update(string $event): void {
        try { db()->prepare("INSERT INTO ai_metrics (metric, value, created_at) VALUES (?,1,NOW())")->execute([$event]); }
        catch (Throwable $e) { error_log("[ReinforcementEngine] " . $e->getMessage()); }
    }
}

class SelfLearningEngine {
    public static function learn(): void {
        try {
            $count = (int)db()->query("SELECT COUNT(*) FROM ai_metrics WHERE created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)")->fetchColumn();
            db()->prepare("INSERT INTO ai_metrics (metric, value, created_at) VALUES ('learning_score',?,NOW())")->execute([$count]);
        } catch (Throwable $e) { error_log("[SelfLearningEngine] " . $e->getMessage()); }
    }
}

class RevenueBrain {
    public static function optimize(int $userId): void {
        try {
            $st = db()->prepare("SELECT COUNT(*) FROM bookings WHERE user_id=? AND status='completed'");
            $st->execute([$userId]);
            if ((int)$st->fetchColumn() > 2) {
                QueueEngine::schedule('event', ['event'=>'subscription.offer','user_id'=>$userId,'service'=>'medical','trigger'=>'revenue_brain'], date('Y-m-d H:i:s'));
            }
        } catch (Throwable $e) { error_log("[RevenueBrain] " . $e->getMessage()); }
    }
}
