<?php
declare(strict_types=1);

function mocker_migrate_site_click_events(PDO $pdo): void
{
    $pdo->exec(
        'CREATE TABLE IF NOT EXISTS site_click_events (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            kind TEXT NOT NULL,
            item_id TEXT NOT NULL DEFAULT \'\',
            label TEXT NOT NULL DEFAULT \'\',
            created_at INTEGER NOT NULL
        )'
    );
    $pdo->exec('CREATE INDEX IF NOT EXISTS idx_site_clicks_kind_time ON site_click_events(kind, created_at)');
    $pdo->exec('CREATE INDEX IF NOT EXISTS idx_site_clicks_item ON site_click_events(kind, item_id, created_at)');
}

function mocker_click_analytics_allowed_kinds(): array
{
    return ['sponsor', 'bonus', 'promo'];
}

function mocker_click_analytics_record(PDO $pdo, string $kind, string $itemId, string $label): void
{
    if (!in_array($kind, mocker_click_analytics_allowed_kinds(), true)) {
        return;
    }
    $itemId = mb_substr(trim($itemId), 0, 64);
    $label = mb_substr(trim($label), 0, 160);
    if ($itemId === '' && $label === '') {
        return;
    }
    $st = $pdo->prepare(
        'INSERT INTO site_click_events (kind, item_id, label, created_at) VALUES (:k, :i, :l, :t)'
    );
    $st->execute([
        ':k' => $kind,
        ':i' => $itemId,
        ':l' => $label,
        ':t' => time(),
    ]);
}

function mocker_click_analytics_top(PDO $pdo, string $kind, int $from, int $to, int $limit = 15): array
{
    if (!in_array($kind, mocker_click_analytics_allowed_kinds(), true)) {
        return [];
    }
    $limit = max(1, min(50, $limit));
    $st = $pdo->prepare(
        'SELECT item_id, label, COUNT(*) AS clicks
         FROM site_click_events
         WHERE kind = :k AND created_at >= :f AND created_at <= :t
         GROUP BY item_id, label
         ORDER BY clicks DESC, label ASC
         LIMIT ' . $limit
    );
    $st->execute([':k' => $kind, ':f' => $from, ':t' => $to]);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

    return array_map(static function (array $row): array {
        return [
            'itemId' => (string) ($row['item_id'] ?? ''),
            'label' => (string) ($row['label'] ?? ''),
            'clicks' => (int) ($row['clicks'] ?? 0),
        ];
    }, $rows);
}
