<?php

declare(strict_types=1);

header('Content-Type: application/json');
header('Cache-Control: no-cache');

const SYMBOL = 'SPCX';
const CACHE_FILE = __DIR__ . '/cache/spcx-quote.json';
const CACHE_TTL = 30; // seconds — keeps repeat page loads instant without hammering Yahoo
const UPSTREAM_TIMEOUT = 5; // seconds

function fetchUpstreamQuote(): ?string
{
    $url = 'https://query1.finance.yahoo.com/v8/finance/chart/' . SYMBOL . '?interval=1d&range=1d';

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => UPSTREAM_TIMEOUT,
        CURLOPT_CONNECTTIMEOUT => UPSTREAM_TIMEOUT,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; SpaceXFoundationStockTicker/1.0)',
        CURLOPT_HTTPHEADER => ['Accept: application/json'],
    ]);
    $body = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($body === false || $httpCode !== 200) {
        return null;
    }

    $decoded = json_decode($body, true);
    if (!isset($decoded['chart']['result'][0]['meta']['regularMarketPrice'])) {
        return null;
    }

    return $body;
}

function readCache(): ?array
{
    if (!is_file(CACHE_FILE)) {
        return null;
    }
    $raw = file_get_contents(CACHE_FILE);
    $data = json_decode($raw, true);
    if (!is_array($data) || !isset($data['body'], $data['time'])) {
        return null;
    }
    return $data;
}

function writeCache(string $body): void
{
    @file_put_contents(CACHE_FILE, json_encode(['body' => $body, 'time' => time()]));
}

$cache = readCache();

if ($cache && (time() - $cache['time']) < CACHE_TTL) {
    echo $cache['body'];
    exit;
}

$fresh = fetchUpstreamQuote();

if ($fresh !== null) {
    writeCache($fresh);
    echo $fresh;
    exit;
}

if ($cache !== null) {
    // Upstream is down/rate-limited — serve the last known-good quote rather than nothing.
    echo $cache['body'];
    exit;
}

http_response_code(502);
echo json_encode(['error' => 'Unable to fetch live quote.']);
