<?php
require_once "/var/www/config.php";
$token = FINNHUB_KEY;

$log_file = __DIR__ . '/stock_webhook_log.txt';
$watch_file = __DIR__ . '/watchlist.json';

/* ---------------------------
   LOAD WATCHLIST
----------------------------*/
$watchlist = [];
if (file_exists($watch_file)) {
    $decoded = json_decode(file_get_contents($watch_file), true);
    if (is_array($decoded)) $watchlist = $decoded;
}

/* ---------------------------
   READ REQUEST (WEBHOOK)
----------------------------*/
$payload_raw = file_get_contents('php://input');
$data = json_decode($payload_raw, true) ?: [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $symbol = strtoupper(
        $data['symbol']
        ?? $data['s']
        ?? $data['data']['symbol']
        ?? $data['data']['s']
        ?? ''
    );

    // filter
    $watchlist_upper = array_map('strtoupper', $watchlist);

    if (!empty($watchlist_upper) && !in_array($symbol, $watchlist_upper)) {
        http_response_code(200);
        echo "ignored";
        exit;
    }

    // log event
    $log_entry = [
        'time' => date('Y-m-d H:i:s'),
        'symbol' => $symbol,
        'payload' => $data
    ];

    file_put_contents(
        $log_file,
        json_encode($log_entry) . PHP_EOL,
        FILE_APPEND | LOCK_EX
    );

    http_response_code(200);
    echo "OK";
    exit;
}

/* ---------------------------
   FETCH PRICE (AJAX helper)
----------------------------*/
if (isset($_GET['price'])) {
    $symbol = $_GET['price'];

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

    header('Content-Type: application/json');
    echo file_get_contents($url);
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Live Stock Dashboard</title>
    <style>
        body { font-family: Arial; background:#0f0f0f; color:#fff; }
        .box { max-width:900px; margin:40px auto; padding:20px; }

        .card {
            background:#1c1c1c;
            padding:15px;
            margin:10px 0;
            border-radius:10px;
        }

        .symbol { font-size:18px; font-weight:bold; color:#00ff99; }
        .price { font-size:16px; margin-top:5px; }

        .log {
            margin-top:20px;
            font-size:12px;
            color:#aaa;
        }
    </style>
</head>
<body>

<div class="box">
    <h2>📡 Live Stock Dashboard</h2>
    <div id="feed">Loading...</div>
</div>

<script>
async function fetchPrice(symbol) {
    const res = await fetch('?price=' + symbol);
    return await res.json();
}

async function loadFeed() {
    const res = await fetch('stock_webhook_log.txt?' + Date.now());
    const text = await res.text();

    const lines = text.trim().split("\n").filter(Boolean);

    let symbols = [];
    let html = "";

    for (const line of lines.slice(-20).reverse()) {
        try {
            const item = JSON.parse(line);

            const sym = item.symbol || item.payload?.symbol || item.payload?.s;
            if (sym) symbols.push(sym);

            html += `
                <div class="card">
                    <div class="symbol">${sym || ''}</div>
                    <div class="price" id="price-${sym}">Loading price...</div>
                    <div class="log">${item.time}</div>
                </div>
            `;
        } catch(e) {}
    }

    document.getElementById("feed").innerHTML = html || "Waiting for data...";

    // remove duplicates
    symbols = [...new Set(symbols)];

    // update prices
    symbols.forEach(async (s) => {
        try {
            const r = await fetch('?price=' + s);
            const d = await r.json();

            const el = document.getElementById('price-' + s);
            if (el) {
                el.innerHTML = `
                    $${d.c}
                    <span style="color:${d.d >= 0 ? 'lime' : 'red'}">
                        (${d.dp}%)
                    </span>
                `;
            }
        } catch(e) {}
    });
}

loadFeed();
setInterval(loadFeed, 5000);
</script>

</body>
</html>
