<?php
/**
 * سودانا — TaskEngine v3
 * Real DB execution. Called only by AIOrchestrator.
 */
class TaskEngine {

    public static function dispatch(array $actions): void {
        foreach ($actions as $action) {
            try {
                switch ($action['type']) {
                    case 'pharmacy.suggest':   self::pharmSuggest($action['data']);      break;
                    case 'followup.schedule':  self::followupSchedule($action['data']);  break;
                    case 'followup.recovery':  self::followupRecovery($action['data']);  break;
                    case 'subscription.offer': self::subscriptionOffer($action['data']); break;
                    case 'usage.track':        self::usageTrack($action['data']);        break;
                    case 'payment.post_confirm':  self::postConfirm($action['data']);    break;
                    case 'payment.gateway.notify': self::gatewayNotify($action['data']); break;
                    case 'payment.post_refund':   self::postRefund($action['data']);     break;
                    case 'financial.audit.run':   self::financialAudit($action['data']); break;
                    default: error_log("[TaskEngine] Unknown: " . $action['type']);
                }
            } catch (Throwable $e) {
                error_log("[TaskEngine] {$action['type']}: " . $e->getMessage());
            }
        }
    }
    private static function pharmSuggest(array $data): void {
        $userId = (int)($data['user_id'] ?? 0); if (!$userId) return;
        $bookingId = (int)($data['booking_id'] ?? 0);
        db()->prepare(
            "INSERT INTO notifications (user_id, type, title, body, data, created_at)
             VALUES (?, 'pharmacy_suggest', '💊 صيدليات قريبة منك',
             'وصفتك الطبية جاهزة — اختر الصيدلية المناسبة لاستلامها', ?, NOW())"
        )->execute([$userId, json_encode(['booking_id'=>$bookingId], JSON_UNESCAPED_UNICODE)]);
        if ($bookingId) {
            db()->prepare(
                "INSERT IGNORE INTO prescription_requests (booking_id, user_id, status, created_at) VALUES (?,?,'pending',NOW())"
            )->execute([$bookingId, $userId]);
        }
    }

    private static function followupSchedule(array $data): void {
        $userId = (int)($data['user_id'] ?? 0); if (!$userId) return;
        $bookingId = (int)($data['booking_id'] ?? 0);
        $followAt = date('Y-m-d H:i:s', strtotime('+48 hours'));
        db()->prepare(
            "INSERT INTO notifications (user_id, type, title, body, data, created_at)
             VALUES (?, 'followup_scheduled', '📅 متابعة مجدولة',
             'سنتواصل معك بعد 48 ساعة للاطمئنان على صحتك', ?, NOW())"
        )->execute([$userId, json_encode(['booking_id'=>$bookingId,'followup_at'=>$followAt], JSON_UNESCAPED_UNICODE)]);
        QueueEngine::schedule('event', [
            'event'=>'followup.deliver','user_id'=>$userId,'booking_id'=>$bookingId
        ], $followAt);
        if ($bookingId) {
            db()->prepare(
                "UPDATE bookings SET notes=CONCAT(COALESCE(notes,''),' [followup_scheduled]')
                 WHERE id=? AND (notes IS NULL OR notes NOT LIKE '%followup_scheduled%')"
            )->execute([$bookingId]);
        }
    }

    private static function followupRecovery(array $data): void {
        $userId = (int)($data['user_id'] ?? 0); if (!$userId) return;
        db()->prepare(
            "INSERT INTO notifications (user_id, type, title, body, data, created_at)
             VALUES (?, 'flow_recovery', '🔔 أكمل طلبك',
             'لم تكمل حجزك — المزودون متاحون الآن. هل تريد المتابعة؟', ?, NOW())"
        )->execute([$userId, json_encode(['service'=>$data['service']??null,'step'=>$data['step']??null], JSON_UNESCAPED_UNICODE)]);
    }

    private static function subscriptionOffer(array $data): void {
        $userId = (int)($data['user_id'] ?? 0); if (!$userId) return;
        $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;
        $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;
        db()->prepare(
            "INSERT INTO notifications (user_id, type, title, body, data, created_at)
             VALUES (?, 'subscription_offer', '⭐ ارقَ تجربتك مع سودانا بريميوم',
             'احصل على أولوية حجز + ذاكرة طبية + خدمات غير محدودة — خصم 20% لك اليوم', ?, NOW())"
        )->execute([$userId, json_encode(['discount'=>20,'expires'=>date('Y-m-d',strtotime('+48 hours'))], JSON_UNESCAPED_UNICODE)]);
    }

    private static function usageTrack(array $data): void {
        $userId = (int)($data['user_id'] ?? 0); if (!$userId) return;
        try {
            db()->prepare(
                "INSERT INTO ai_usage (user_id, agent_id, event_type, service, created_at)
                 VALUES (?, ?, 'ai_engine.used', ?, NOW())"
            )->execute([$userId, $data['agent_id']??null, $data['service']??'general']);
        } catch (Throwable $e) { error_log("[TaskEngine::usageTrack] " . $e->getMessage()); }
    }

    private static function postConfirm(array $data): void {
        $userId    = (int)($data['user_id']    ?? 0); if (!$userId) return;
        $invoiceId = (int)($data['invoice_id'] ?? 0);
        $amount    = (float)($data['amount']   ?? 0);
        db()->prepare(
            "INSERT INTO notifications (user_id, type, title, body, data, created_at)
             VALUES (?, 'payment_confirmed', '✅ تم استلام دفعتك', ?, ?, NOW())"
        )->execute([$userId,
            "تم استلام {$amount} جنيه وإضافتها لمحفظتك.",
            json_encode(['invoice_id'=>$invoiceId,'amount'=>$amount], JSON_UNESCAPED_UNICODE)
        ]);
    }

    private static function postRefund(array $data): void {
        $userId    = (int)($data['user_id']    ?? 0); if (!$userId) return;
        $invoiceId = (int)($data['invoice_id'] ?? 0);
        $amount    = (float)($data['amount']   ?? 0);
        db()->prepare(
            "INSERT INTO notifications (user_id, type, title, body, data, created_at)
             VALUES (?, 'payment_refunded', '↩️ تم الاسترداد', ?, ?, NOW())"
        )->execute([$userId,
            "تم استرداد {$amount} جنيه من محفظتك.",
            json_encode(['invoice_id'=>$invoiceId,'amount'=>$amount], JSON_UNESCAPED_UNICODE)
        ]);
    }

    private static function riskNotify(array $data): void {
        $userId = (int)($data['user_id'] ?? 0); if(!$userId) return;
        $level  = $data['risk_level'] ?? 'high';
        db()->prepare(
            "INSERT INTO notifications (user_id,type,title,body,data,created_at)
             VALUES (?,'risk_block','⚠️ معاملة محجوبة',?,?,NOW())"
        )->execute([$userId,
            "تم حجب معاملة بسبب مستوى مخاطر: $level. تواصل مع الدعم.",
            json_encode($data, JSON_UNESCAPED_UNICODE)
        ]);
    }

    private static function reconAlert(array $data): void {
        db()->prepare(
            "INSERT INTO notifications (user_id,type,title,body,data,created_at)
             VALUES (1,'recon_alert','🚨 فشل التسوية',?,?,NOW())"
        )->execute([json_encode($data['mismatches']??[]), json_encode($data, JSON_UNESCAPED_UNICODE)]);
    }

    private static function settlement(array $data): void {
        require_once __DIR__ . '/SettlementEngine.php';
        $date = $data['date'] ?? date('Y-m-d', strtotime('yesterday'));
        SettlementEngine::processDate($date);
    }

    private static function gatewayNotify(array $data): void {
        $userId  = (int)($data['user_id']  ?? 0);
        $amount  = (float)($data['amount'] ?? 0);
        $gateway = $data['gateway'] ?? 'gateway';
        $txnId   = $data['txn_id'] ?? '';
        if (!$userId) return;
        db()->prepare(
            "INSERT INTO notifications (user_id, type, title, body, data, created_at)
             VALUES (?, 'gateway_payment', '✅ تم الدفع إلكترونياً', ?, ?, NOW())"
        )->execute([$userId,
            "تم استلام {$amount} جنيه عبر {$gateway}. المعاملة: {$txnId}",
            json_encode(['amount'=>$amount,'gateway'=>$gateway,'txn_id'=>$txnId], JSON_UNESCAPED_UNICODE)
        ]);
    }

    private static function financialAudit(array $data): void {
        require_once __DIR__ . '/FinancialAgent.php';
        $result = FinancialAgent::run($data);
        error_log('[TaskEngine::financialAudit] balanced=' .
            ($result['ledger_check']['balanced'] ? 'true' : 'false') .
            ' issues=' . count($result['issues'] ?? []));
    }
}
