<?php
require_once "/var/www/config.php";

header('Content-Type: application/json');

$file = __DIR__ . "/watchlist.json";
$cacheFile = __DIR__ . "/prices_cache.json";
$cacheTtl = 60; // seconds

/* ---------------------------
   RETURN CACHE IF FRESH
----------------------------*/
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTtl)) {
    echo file_get_contents($cacheFile);
    exit;
}

/* ---------------------------
   LOAD WATCHLIST
----------------------------*/
$symbols = file_exists($file)
    ? json_decode(file_get_contents($file), true)
    : [];

$results = [];

/* ---------------------------
   FETCH FRESH PRICES
----------------------------*/
foreach ($symbols as $symbol) {
    $symbol = strtoupper(trim($symbol));
    if (!$symbol) continue;

    $url = "https://finnhub.io/api/v1/quote?symbol=$symbol&token=" . FINNHUB_KEY;

    $response = @file_get_contents($url);
    $data = $response ? json_decode($response, true) : null;

    $results[$symbol] = [
        "price"   => $data["c"]  ?? null,
        "change"  => $data["d"]  ?? null,
        "percent" => $data["dp"] ?? null
    ];
}

/* ---------------------------
   SAVE CACHE
----------------------------*/
$json = json_encode($results);
file_put_contents($cacheFile, $json, LOCK_EX);

/* ---------------------------
   RETURN DATA
----------------------------*/
echo $json;
