<?php
/**
 * سودانا — GrowthBrain v2
 * observe → detect → decide → execute
 */
class GrowthBrain {

    public static function observe(string $event, array $context): void {
        self::persistSignal($event, $context);
        $action = self::detect($event, $context);
        if ($action) self::act($action, $context);
    }

    private static function detect(string $event, array $context): ?string {
        switch ($event) {
            case 'flow.abandoned':    return 'recovery.notify';
            case 'booking.completed': return 'kpi.booking_increment';
            default:                  return null;
        }
    }

    private static function act(string $action, array $context): void {
        switch ($action) {
            case 'recovery.notify':
                $userId = (int)($context['user_id'] ?? 0); if (!$userId) return;
                try {
                    db()->prepare(
                        "INSERT INTO notifications (user_id, type, title, body, data, created_at)
                         VALUES (?, 'flow_recovery', '🔔 أكمل طلبك',
                         'لم تكمل حجزك — المزودون متاحون الآن. هل تريد المتابعة؟', ?, NOW())"
                    )->execute([$userId, json_encode(['step'=>$context['step']??null,'service'=>$context['service']??null], JSON_UNESCAPED_UNICODE)]);
                } catch (Throwable $e) { error_log("[GrowthBrain::recovery] " . $e->getMessage()); }
                break;
            case 'kpi.booking_increment':
                try {
                    db()->prepare(
                        "INSERT INTO kpi_daily (kpi_date, bookings_created) VALUES (CURDATE(), 1)
                         ON DUPLICATE KEY UPDATE bookings_created = bookings_created + 1"
                    )->execute();
                } catch (Throwable $e) { error_log("[GrowthBrain::kpi] " . $e->getMessage()); }
                break;
        }
    }

    private static function persistSignal(string $event, array $context): void {
        try {
            db()->prepare(
                "INSERT INTO audit_logs (action, entity_type, entity_id, data, created_at)
                 VALUES (?, 'growth_signal', ?, ?, NOW())"
            )->execute([
                $event, $context['user_id'] ?? null,
                json_encode(['event'=>$event,'service'=>$context['service']??null,'provider'=>$context['provider_id']??null,'step'=>$context['step']??null], JSON_UNESCAPED_UNICODE),
            ]);
        } catch (Throwable $e) { error_log("[GrowthBrain] " . $e->getMessage()); }
    }
}
