<?php
define("FXH_PORTAL", true);
$pageTitle = "Signals";

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../middleware/user_auth.php';

include __DIR__ . "/includes/header.php";
include __DIR__ . "/includes/sidebar.php";
?>

<div class="fxh-main">
    
    <h1>📡 Webhook Signals</h1>

    <div class="fx-card">

    <table class="fx-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Symbol</th>
                <th>Dir</th>
                <th>TF</th>
                <th>Time</th>
                <th>Raw Signal</th>
            </tr>
        </thead>

        <tbody id="signalTable"></tbody>
    </table>

    <!-- PAGINATION -->
    <div class="fx-pagination">
        <button id="prevPage" disabled>« Prev</button>
        <span id="pageInfo">Page 1</span>
        <button id="nextPage">Next »</button>
    </div>

</div>

<script>
let allSignals = [];
let page = 1;
let perPage = 15;

// Load Data
function loadSignals(){
    fetch("/portal/api/get_signals.php")
    .then(r => r.json())
    .then(data => {
        allSignals = data;
        renderTable();
        updateButtons();
    });
}

function renderTable() {
    let start = (page - 1) * perPage;
    let end = start + perPage;
    let slice = allSignals.slice(start, end);

    let html = "";

    slice.forEach(s => {

        let dir = s.direction.toLowerCase();
        let dirColor = "";
        
        if (dir === "buy")          dirColor = "dir-buy";
        else if (dir === "sell")    dirColor = "dir-sell";
        else if (dir === "closelong")  dirColor = "dir-closelong";
        else if (dir === "closeshort") dirColor = "dir-closeshort";
        else if (dir === "newslplong" || dir === "newsltplong") 
            dirColor = "dir-news-long";
        else if (dir === "newsltpshort" || dir === "newslpshort")
            dirColor = "dir-news-short";
        else 
            dirColor = "dir-neutral";

        html += `
            <tr>
                <td>${s.id}</td>
                <td>${s.symbol}</td>
                <td class="${dirColor}">${s.direction}</td>
                <td>${s.tf}</td>
                <td>${s.ts}</td>
                <td class="raw-cell"><pre>${s.raw}</pre></td>
            </tr>
        `;
    });

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

function updateButtons() {
    document.getElementById("prevPage").disabled = page === 1;
    document.getElementById("nextPage").disabled = page * perPage >= allSignals.length;
    document.getElementById("pageInfo").innerText = "Page " + page;
}

document.getElementById("prevPage").onclick = () => {
    if (page > 1) {
        page--;
        renderTable();
        updateButtons();
    }
};

document.getElementById("nextPage").onclick = () => {
    if (page * perPage < allSignals.length) {
        page++;
        renderTable();
        updateButtons();
    }
};

loadSignals();
</script>

<?php include __DIR__ . "/includes/footer.php"; ?>
