<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/checkout/common.php';

kapvoe_require_post();

$config = kapvoe_load_config();
$data = kapvoe_json_input();

$allowedEvents = [
    'page_view',
    'view_large',
    'whatsapp_click',
    'buy_click',
    'checkout_open',
    'checkout_submit',
    'filter_use',
    'refresh_click',
    'payment_cancel',
];

$eventType = trim((string)($data['event_type'] ?? ''));
if ($eventType === '' || !in_array($eventType, $allowedEvents, true)) {
    kapvoe_json_response([
        'ok' => false,
        'error' => 'event_type invalid',
    ], 422);
}

$payload = [
    'timestamp' => date('c'),
    'event_type' => $eventType,
    'product_code' => trim((string)($data['product_code'] ?? '')),
    'model' => trim((string)($data['model'] ?? '')),
    'category' => trim((string)($data['category'] ?? '')),
    'price' => trim((string)($data['price'] ?? '')),
    'stock' => trim((string)($data['stock'] ?? '')),
    'page_url' => trim((string)($data['page_url'] ?? '')),
    'user_agent' => trim((string)($data['user_agent'] ?? ($_SERVER['HTTP_USER_AGENT'] ?? ''))),
    'session_id' => trim((string)($data['session_id'] ?? '')),
    'event_id' => trim((string)($data['event_id'] ?? ('evt_' . bin2hex(random_bytes(8))))),
    'order_id' => trim((string)($data['order_id'] ?? '')),
    'stripe_session_id' => trim((string)($data['stripe_session_id'] ?? '')),
    'payment_status' => trim((string)($data['payment_status'] ?? '')),
    'quantity' => trim((string)($data['quantity'] ?? '')),
    'shipping_method' => trim((string)($data['shipping_method'] ?? '')),
    'total_amount' => trim((string)($data['total_amount'] ?? '')),
    'referrer' => trim((string)($data['referrer'] ?? ($_SERVER['HTTP_REFERER'] ?? ''))),
    'utm_source' => trim((string)($data['utm_source'] ?? '')),
    'utm_medium' => trim((string)($data['utm_medium'] ?? '')),
    'utm_campaign' => trim((string)($data['utm_campaign'] ?? '')),
    'device_type' => trim((string)($data['device_type'] ?? '')),
    'page_type' => trim((string)($data['page_type'] ?? 'catalog')),
];

$ok = kapvoe_track_analytics_event($config, $payload);

kapvoe_json_response([
    'ok' => $ok,
    'event_type' => $eventType,
], $ok ? 200 : 202);
