<?php
/**
 * سودانا — Hub Event Tracker v1
 * Receives: hub.visit | cta.click | provider.join | service.view
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth'=>false,'public'=>true]);
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
require_once '../../engine/QueueEngine.php';
require_once '../../engine/EventBus.php';
require_once '../../engine/SupportEngines.php';
require_once '../../engine/GrowthBrain.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { json_response(['error'=>'method_not_allowed'], 405); }

$body  = json_decode(file_get_contents('php://input'), true) ?? [];
$event = preg_replace('/[^a-z._]/', '', strtolower($body['event'] ?? ''));
$meta  = array_slice($body['meta'] ?? [], 0, 20);

$allowed = ['hub.visit','cta.click','provider.join','service.view'];
if (!in_array($event, $allowed)) json_response(['error'=>'unknown_event'], 400);

$userId = null;
try { $userId = (current_user() ?: [])['id'] ?? null; } catch (Throwable $ignored) {}

$context = array_merge($meta, [
    'user_id'   => $userId,
    'ip_hash'   => md5($_SERVER['REMOTE_ADDR'] ?? ''),
    'service'   => $body['service'] ?? null,
]);

try {
    db()->prepare(
        "INSERT INTO audit_logs (action, entity_type, entity_id, data, created_at) VALUES (?, 'hub_event', ?, ?, NOW())"
    )->execute([$event, $userId, json_encode($context, JSON_UNESCAPED_UNICODE)]);
} catch (Throwable $e) { error_log("[hub/track] " . $e->getMessage()); }

GrowthBrain::observe($event, $context);

json_response(['success'=>true,'event'=>$event]);
