<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

$path = dirname(__DIR__) . '/data/popup.json';
$empty = [
    'enabled' => false,
    'title' => '',
    'imageUrl' => '',
    'linkUrl' => '',
    'startAt' => null,
    'endAt' => null,
    'frequency' => 'session',
];

if (!is_readable($path)) {
    echo json_encode($empty, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$raw = (string) file_get_contents($path);
if (str_starts_with($raw, "\xEF\xBB\xBF")) {
    $raw = substr($raw, 3);
}
$j = json_decode($raw, true);
if (!is_array($j) || !array_key_exists('enabled', $j)) {
    echo json_encode($empty, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

echo json_encode($j, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
