<?php
/**
 * سودانا — ControlEngine v2
 * Live DB fact-check before execution. Fail-safe: deny on error.
 */
class ControlEngine {

    public static function approve(array $action, array $ctx): bool {
        $type      = $action['type'] ?? '';
        $userId    = (int)($ctx['user_id']    ?? 0);
        $bookingId = (int)($ctx['booking_id'] ?? 0);
        $service   = $ctx['service'] ?? '';
        try {
            switch ($type) {
                case 'subscription.offer':
                    if (!$userId) return false;
                    $st = db()->prepare("SELECT COUNT(*) FROM user_subscriptions WHERE user_id=? AND status='active' AND expires_at > NOW()");
                    $st->execute([$userId]);
                    if ((int)$st->fetchColumn() > 0) return false;
                    $st2 = db()->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND type='subscription_offer' AND created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)");
                    $st2->execute([$userId]);
                    if ((int)$st2->fetchColumn() > 0) return false;
                    break;
                case 'pharmacy.suggest':
                    if (!in_array($service, ['medical','family'])) return false;
                    if (!$userId || !$bookingId) return false;
                    $st = db()->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND type='pharmacy_suggest' AND data->>'$.booking_id' = ?");
                    $st->execute([$userId, $bookingId]);
                    if ((int)$st->fetchColumn() > 0) return false;
                    break;
                case 'followup.schedule':
                    if (!$bookingId || !$userId) return false;
                    $st = db()->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND type='followup_scheduled' AND data->>'$.booking_id' = ?");
                    $st->execute([$userId, $bookingId]);
                    if ((int)$st->fetchColumn() > 0) return false;
                    break;
                case 'followup.recovery':
                    if (!$userId) return false;
                    $st = db()->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND type='flow_recovery' AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)");
                    $st->execute([$userId]);
                    if ((int)$st->fetchColumn() > 0) return false;
                    break;
                case 'payment.post_confirm':
                case 'payment.post_refund':
                    $invoiceId = (int)($ctx['invoice_id'] ?? 0);
                    if (!$invoiceId || !$userId) return false;
                    // Must be paid invoice
                    $st = db()->prepare("SELECT status, expires_at FROM invoices WHERE id=?");
                    $st->execute([$invoiceId]);
                    $inv = $st->fetch(PDO::FETCH_ASSOC);
                    if (!$inv) return false;
                    // Block expired invoices
                    if (!empty($inv['expires_at']) && strtotime($inv['expires_at']) < time()
                        && $inv['status'] !== 'paid') {
                        error_log("[ControlEngine] Blocked expired invoice $invoiceId");
                        return false;
                    }
                    break;
                case 'financial.audit.run':
                    return true; // always allow audit
                case 'payment.gateway.notify':
                    return true; // gateway already verified externally
            }
        } catch (Throwable $e) {
            error_log("[ControlEngine] " . $e->getMessage());
            return false;
        }
        return true;
    }
}
