<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/click_analytics_lib.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'payload'], JSON_UNESCAPED_UNICODE);
    exit;
}

$kind = isset($input['kind']) ? trim((string) $input['kind']) : '';
$itemId = isset($input['itemId']) ? trim((string) $input['itemId']) : '';
$label = isset($input['label']) ? trim((string) $input['label']) : '';

if (!in_array($kind, mocker_click_analytics_allowed_kinds(), true)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'kind'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = mocker_db();
    mocker_click_analytics_record($pdo, $kind, $itemId, $label);
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode(['ok' => true], JSON_UNESCAPED_UNICODE);
