<?php
require_once "/var/www/config.php"; // your hidden key
header("Content-Type: text/html; charset=UTF-8");

$file = __DIR__ . "/watchlist.json";

/* ---------------------------
   SAVE WATCHLIST (AJAX)
----------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $stocks = $_POST['stocks'] ?? '';
    $newSymbols = array_filter(array_map(
        'trim',
        explode(',', strtoupper($stocks))
    ));

    // load existing
    $existing = [];
    if (file_exists($file)) {
        $existing = json_decode(file_get_contents($file), true) ?: [];
    }

    // merge + remove duplicates
    $merged = array_values(array_unique(array_merge($existing, $newSymbols)));

    file_put_contents(
        $file,
        json_encode($merged, JSON_PRETTY_PRINT),
        LOCK_EX
    );

    echo "OK";
    exit;
}

/* ---------------------------
   LOAD WATCHLIST
----------------------------*/
$watchlist = [];
if (file_exists($file)) {
    $watchlist = json_decode(file_get_contents($file), true) ?: [];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Live Stock Dashboard</title>
    <style>
        body { background:#0f0f0f; color:#fff; font-family:Arial; }
        .wrap { max-width:700px; margin:40px auto; }
        .row {
            display:flex;
            justify-content:space-between;
            padding:12px;
            margin:6px 0;
            background:#1c1c1c;
            border-radius:8px;
        }
        input { width:70%; padding:10px; }
        button { padding:10px; cursor:pointer; }
        .green { color:#00ff99; }
        .red { color:#ff4d4d; }
    </style>
</head>
<body>

<div class="wrap">

    <h2>📊 Live Stock Dashboard</h2>

    <!-- ADD TICKER -->
    <input id="ticker" placeholder="Not, working, yet">
<button onclick="addTicker()">Hello</button>

<select id="sortMode" onchange="loadPrices()">
    <option value="percent">% Gain</option>
    <option value="alpha">A–Z</option>
</select>

<hr>

    <!-- LIVE LIST -->
    <div id="list">Loading...</div>

</div>

<script>
let watchlist = [];

/* ---------------------------
   FETCH LIVE PRICES
----------------------------*/
async function loadPrices() {
    const res = await fetch('prices.php?' + Date.now());
    const data = await res.json();

    watchlist = Object.keys(data); // keep local copy

    // convert object → array so we can sort it
    const sortMode = document.getElementById("sortMode")?.value || "percent";

    let sorted = Object.entries(data)
        .map(([symbol, info]) => ({
        symbol,
        price: info.price,
        percent: parseFloat(info.percent || 0)
    }));

if (sortMode === "alpha") {
    sorted.sort((a, b) => a.symbol.localeCompare(b.symbol));
} else {
    sorted.sort((a, b) => b.percent - a.percent);
} // HIGH → LOW

    let html = "";

    for (const item of sorted) {

        const color = item.percent >= 0 ? 'green' : 'red';

        html += `
        <div class="row">
            <div><b>${item.symbol}</b></div>
            <div>$${item.price ?? "-"}</div>
            <div class="${color}">
                ${item.percent.toFixed(2)}%
            </div>
        </div>`;
    }

    document.getElementById("list").innerHTML = html;
}

/* ---------------------------
   ADD TICKER
----------------------------*/
async function addTicker() {
    const sym = document.getElementById("ticker").value.trim().toUpperCase();
    if (!sym) return;

    const res = await fetch('prices.php');
    const data = await res.json();

    if (Object.keys(data).includes(sym)) {
        alert("Already in watchlist");
        return;
    }

    await fetch('', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'stocks=' + sym
    });

    document.getElementById("ticker").value = "";
    loadPrices();
}

/* ---------------------------
   AUTO REFRESH
----------------------------*/
loadPrices();
setInterval(loadPrices, 30 * 1000);

</script>

</body>
</html>
