<?php

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: public, max-age=60');

$dataDir = dirname(__DIR__) . '/data/';

$readJson = static function (string $path): array {
    if (!is_readable($path)) {
        return [];
    }
    $j = json_decode((string) file_get_contents($path), true);

    return is_array($j) ? $j : [];
};

$sponsorsRaw = $readJson($dataDir . 'sponsors.json');
$sponsorsById = [];
foreach ($sponsorsRaw as $row) {
    if (!is_array($row)) {
        continue;
    }
    $id = isset($row['id']) ? trim((string) $row['id']) : '';
    if ($id === '') {
        continue;
    }
    $sponsorsById[$id] = $row;
}

$bonusesRaw = $readJson($dataDir . 'bonuses.json');
$now = time();
$items = [];

foreach ($bonusesRaw as $row) {
    if (!is_array($row)) {
        continue;
    }
    if (isset($row['isActive']) && $row['isActive'] === false) {
        continue;
    }
    $title = isset($row['title']) ? trim((string) $row['title']) : '';
    if ($title === '') {
        continue;
    }
    $sponsorId = isset($row['sponsorId']) ? trim((string) $row['sponsorId']) : '';
    $sponsorTitle = isset($row['sponsorTitle']) ? trim((string) $row['sponsorTitle']) : '';
    $expiresAt = isset($row['expiresAt']) && $row['expiresAt'] !== null && $row['expiresAt'] !== ''
        ? (int) $row['expiresAt']
        : null;
    if ($expiresAt !== null && $expiresAt > 0 && $expiresAt <= $now) {
        continue;
    }

    $sponsor = $sponsorId !== '' && isset($sponsorsById[$sponsorId]) ? $sponsorsById[$sponsorId] : null;
    if ($sponsorTitle === '' && $sponsor) {
        $sponsorTitle = isset($sponsor['title']) ? trim((string) $sponsor['title']) : '';
    }
    if ($sponsorTitle === '') {
        continue;
    }

    $logo = '';
    $url = '';
    if ($sponsor) {
        $logo = isset($sponsor['logo']) ? trim((string) $sponsor['logo']) : '';
        $url = isset($sponsor['url']) ? trim((string) $sponsor['url']) : '';
    }
    $linkUrl = isset($row['url']) ? trim((string) $row['url']) : '';
    if ($linkUrl !== '' && !preg_match('#^https?://#i', $linkUrl)) {
        $linkUrl = '';
    }
    if ($linkUrl === '' && $url !== '' && preg_match('#^https?://#i', $url)) {
        $linkUrl = $url;
    }

    $promoCode = isset($row['promoCode']) ? trim((string) $row['promoCode']) : '';

    $items[] = [
        'id' => isset($row['id']) ? trim((string) $row['id']) : '',
        'sponsorId' => $sponsorId,
        'sponsorTitle' => $sponsorTitle,
        'logo' => $logo,
        'title' => $title,
        'badge' => isset($row['badge']) ? trim((string) $row['badge']) : '',
        'description' => isset($row['description']) ? trim((string) $row['description']) : '',
        'promoCode' => $promoCode,
        'expiresAt' => $expiresAt,
        'url' => $linkUrl,
    ];
}

usort(
    $items,
    static function (array $a, array $b): int {
        $ea = $a['expiresAt'] ?? PHP_INT_MAX;
        $eb = $b['expiresAt'] ?? PHP_INT_MAX;
        if ($ea !== $eb) {
            return $ea <=> $eb;
        }

        return strcasecmp((string) ($a['sponsorTitle'] ?? ''), (string) ($b['sponsorTitle'] ?? ''));
    }
);

echo json_encode(
    ['ok' => true, 'items' => $items],
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
