<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

    $stocks = $_POST['stocks'] ?? '';

    $list = array_values(array_filter(array_map(
        'trim',
        explode(',', strtoupper($stocks))
    )));

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

    $message = "Watchlist saved!";
}

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

$current_str = implode(', ', $current);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Stock Watchlist</title>
    <style>
        body { font-family: Arial; background:#111; color:#fff; }
        .box { max-width:500px; margin:60px auto; padding:20px; background:#1c1c1c; border-radius:10px; }
        input { width:100%; padding:10px; margin-top:10px; }
        button { margin-top:10px; padding:10px; width:100%; cursor:pointer; }
        .hint { font-size:12px; color:#aaa; margin-top:10px; }
        .msg { color:lightgreen; margin-top:10px; }
        pre { background:#000; padding:10px; border-radius:6px; }
    </style>
</head>
<body>

<div class="box">
    <h2>📊 Select Stocks</h2>

    <?php if ($message): ?>
        <div class="msg"><?= $message ?></div>
    <?php endif; ?>

    <form method="POST">
        <input name="stocks" placeholder="AAPL, TSLA, NVDA, SPY"
               value="<?= htmlspecialchars($current_str) ?>">

        <button type="submit">Save Watchlist</button>

        <div class="hint">
            Example: AAPL, TSLA, NVDA, SPY
        </div>
    </form>

    <hr style="margin:20px 0; border:1px solid #333;">

    <h4>Current Watchlist:</h4>
    <pre><?= print_r($current, true) ?></pre>
</div>

</body>
</html>
