<?php
define("FXH_PORTAL", true);
$pageTitle = "FX-HUNTER Strategy Lab";

require_once __DIR__ . "/config.php";
require_once __DIR__ . "/middleware/user_auth.php";
require_once __DIR__ . "/user/includes/header.php";
require_once __DIR__ . "/includes/sidebar.php";
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>FX-HUNTER Strategy Lab</title>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

<style>
/* ===============================================================
   THEME VARIABLES
   - body holds defaults
   - theme classes only override variables
================================================================ */
body{
    --bg:#05080e;
    --panel:#09121a;
    --blue:#0b6cff;
    --blueGlow:#2e9cff;
    --red:#ff2545;
    --text:#d8e7ff;

    background: var(--bg);
    color: var(--text);
    margin:0;
    font-family:"Segoe UI",sans-serif;
    overflow-x:hidden;
}

/* NEON RED */
body.theme-red{
    --bg:#0a0406;
    --panel:#150709;
    --blue:#ff2545;
    --blueGlow:#ff556a;
    --red:#ff2545;
    --text:#ffd6da;
}

/* GRAPHITE GOLD */
body.theme-gold{
    --bg:#050506;
    --panel:#111111;
    --blue:#f2c14e;
    --blueGlow:#ffd977;
    --red:#f05454;
    --text:#fff4dc;
}

/* ===============================================================
   LAYOUT
================================================================ */
.lab-wrapper{
    box-sizing:border-box;
    max-width:1400px;
    margin-left:260px;          /* sidebar width */
    padding:24px 24px 40px;
}

@media(max-width:960px){
    .lab-wrapper{
        margin-left:0;
        padding-top:90px;
        padding-left:16px;
        padding-right:16px;
    }
}

/* ===============================================================
   HEADER
================================================================ */
.lab-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    margin-bottom:12px;
}

.lab-header h1{
    font-size:26px;
    color:var(--blue);
    text-shadow:0 0 16px rgba(11,108,255,.8);
    margin:0;
}

/* Theme selector */
.theme-select{
    background:#02070e;
    color:var(--blueGlow);
    border:1px solid var(--blueGlow);
    border-radius:8px;
    padding:5px 10px;
    box-shadow:inset 0 0 10px rgba(0,0,0,.7);
}

/* ===============================================================
   PANELS
================================================================ */
.panel{
    background:linear-gradient(145deg,#050b12,#0a1622);
    border:1px solid rgba(46,156,255,.25);
    border-radius:14px;
    padding:18px;
    margin-bottom:18px;
    box-shadow:
        0 10px 25px rgba(0,0,0,.6),
        inset 0 0 30px rgba(46,156,255,.05);
}

/* ===============================================================
   PARAM GRID & INPUTS
================================================================ */
.param-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(180px,1fr));
    gap:14px;
}

label{
    font-size:12px;
    opacity:.7;
}

select,input{
    width:100%;
    background:#02070e;
    border:1px solid rgba(46,156,255,.5);
    border-radius:8px;
    padding:8px 10px;
    color:var(--blueGlow);
    box-shadow:inset 0 0 10px rgba(46,156,255,.18);
}

select:focus,input:focus{
    outline:none;
    border-color:var(--blueGlow);
    box-shadow:0 0 15px rgba(46,156,255,.7);
}

/* ===============================================================
   BUTTONS
================================================================ */
.run-btn{
    margin-top:14px;
    width:100%;
    background:linear-gradient(135deg,#143b87,var(--blue));
    border:none;
    color:white;
    font-weight:600;
    border-radius:10px;
    padding:12px;
    cursor:pointer;
    transition:.15s ease;
    box-shadow:0 6px 18px rgba(11,108,255,.8);
}
.run-btn:hover{
    filter:brightness(1.2);
}

/* Smaller replay buttons */
.replay-btn{
    flex:1;
    margin-top:0;
}

/* ===============================================================
   KPI TILES
================================================================ */
.stats{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
    gap:14px;
}

.kpi{
    background:linear-gradient(145deg,#060e16,#061623);
    border:1px solid rgba(46,156,255,.3);
    border-radius:14px;
    padding:14px 10px;
    text-align:center;
    box-shadow:0 0 14px rgba(46,156,255,.15);
}

.kpi h3{
    margin:0;
    opacity:.7;
    font-size:12px;
}

.kpi span{
    font-size:24px;
    margin-top:6px;
    display:block;
}

.kpi.blue span{
    color:var(--blueGlow);
    text-shadow:0 0 14px rgba(46,156,255,.9);
}
.kpi.orange span{
    color:#ff9800;
    text-shadow:0 0 16px rgba(255,152,0,.9);
}
.kpi.red span{
    color:var(--red);
    text-shadow:0 0 14px rgba(255,37,69,.9);
}

/* ===============================================================
   CHARTS
================================================================ */
.chart-title{
    color:var(--blue);
    text-shadow:0 0 14px rgba(46,156,255,.9);
    margin-bottom:8px;
}

#equity_chart,
#candle_chart{
    height:420px;
}

#candle_chart{
    background:#05070c;
    border-radius:14px;
}
</style>
</head>

<body>

<div class="lab-wrapper">

    <!-- HEADER -->
    <div class="lab-header">
        <h1>⚡ FX-HUNTER Strategy Lab</h1>

        <select id="themePicker" class="theme-select" onchange="setTheme(this.value)">
            <option value="">Neon Blue</option>
            <option value="theme-red">Neon Red</option>
            <option value="theme-gold">Graphite Gold</option>
        </select>
    </div>

    <!-- PARAMETERS -->
    <div class="panel">
        <h3 class="chart-title">⚙ Strategy Parameters</h3>

        <div class="param-grid">
            <div>
                <label>Symbol</label>
                <select id="symbol">
                    <option value="XAUUSD">XAUUSD</option>
                </select>
            </div>

            <div>
                <label>Timeframe</label>
                <select id="tf">
                    <option value="M5">M5</option>
                </select>
            </div>

            <div>
                <label>EMA FAST</label>
                <input id="ema_fast" type="number" value="20">
            </div>

            <div>
                <label>EMA SLOW</label>
                <input id="ema_slow" type="number" value="200">
            </div>

            <div>
                <label>RSI BUY MIN</label>
                <input id="rsi_buy" type="number" value="55">
            </div>

            <div>
                <label>RSI SELL MAX</label>
                <input id="rsi_sell" type="number" value="45">
            </div>
        </div>

        <button class="run-btn" onclick="runBacktest()">▶ RUN STRATEGY BACKTEST</button>
    </div>

    <!-- KPI SUMMARY -->
    <div class="panel">
        <h3 class="chart-title">📊 Performance Summary</h3>

        <div class="stats">
            <div class="kpi blue">
                <h3>Total Trades</h3>
                <span id="trades">0</span>
            </div>
            <div class="kpi orange">
                <h3>Win Rate</h3>
                <span id="winrate">0%</span>
            </div>
            <div class="kpi red">
                <h3>Net PnL (R)</h3>
                <span id="pnl">0</span>
            </div>
        </div>
    </div>

    <!-- EQUITY CURVE -->
    <div class="panel">
        <h3 class="chart-title">📈 Equity Curve</h3>
        <div id="equity_chart"></div>
    </div>

    <!-- BAR REPLAY -->
    <div class="panel">
        <h3 class="chart-title">🎬 Bar Replay (Candle Simulator)</h3>

        <div style="display:flex;gap:10px;margin-bottom:12px;flex-wrap:wrap;">
            <button class="run-btn replay-btn" onclick="startReplay()">▶ Play</button>
            <button class="run-btn replay-btn" onclick="pauseReplay()">⏸ Pause</button>
            <button class="run-btn replay-btn" onclick="stepReplay()">⏭ Step</button>
        </div>

        <div id="candle_chart"></div>
    </div>

</div> <!-- /.lab-wrapper -->

<script>
// ======================
// THEME SWITCHER
// ======================
function setTheme(theme){
    document.body.className = theme;
    localStorage.setItem("fxh_theme", theme);
}

// restore on load
const savedTheme = localStorage.getItem("fxh_theme");
if(savedTheme){
    document.body.className = savedTheme;
    const picker = document.getElementById("themePicker");
    if(picker) picker.value = savedTheme;
}

// ======================
// EQUITY CURVE
// ======================
let equityChart = null;

function drawEquity(data){
    const options = {
        chart:{
            type:'area',
            height:420,
            foreColor:'#d8e7ff',
            toolbar:{ show:false },
            background:'#05070c'
        },
        grid:{ borderColor:"#10243d" },
        series:[{ name:"Equity", data:data }],
        stroke:{ curve:"smooth", width:3 },
        fill:{
            type:"gradient",
            gradient:{ opacityFrom:.6, opacityTo:0.05 }
        },
        tooltip:{ theme:"dark" }
    };

    if(equityChart) equityChart.destroy();

    equityChart = new ApexCharts(
        document.querySelector("#equity_chart"),
        options
    );
    equityChart.render();
}

// ======================
// RUN BACKTEST
// ======================
async function runBacktest(){
    const symbolEl   = document.getElementById("symbol");
    const tfEl       = document.getElementById("tf");
    const emaFastEl  = document.getElementById("ema_fast");
    const emaSlowEl  = document.getElementById("ema_slow");
    const rsiBuyEl   = document.getElementById("rsi_buy");
    const rsiSellEl  = document.getElementById("rsi_sell");

    const payload = {
        strategy:{
            name:"EMA20_200_RSI",
            symbol:symbolEl.value,
            timeframe:tfEl.value,
            ema_fast:+emaFastEl.value,
            ema_slow:+emaSlowEl.value,
            rsi_buy_min:+rsiBuyEl.value,
            rsi_sell_max:+rsiSellEl.value
        }
    };

    try{
        const res = await fetch("/portal/api/run_backtest.php",{
            method:"POST",
            headers:{ "Content-Type":"application/json" },
            body:JSON.stringify(payload)
        });

        const d = await res.json();

        document.getElementById("trades").innerText  = d.total_trades;
        document.getElementById("winrate").innerText = d.winrate + "%";
        document.getElementById("pnl").innerText     = d.net_pnl;

        drawEquity(d.equity_curve || []);
    }catch(e){
        alert("⚠ Strategy Engine Offline");
    }
}

// ======================
// BAR REPLAY ENGINE
// ======================
let replayBars = [];
let replayIndex = 0;
let replayTimer = null;
let candleChart = null;
const MAX_VISIBLE = 80;   // bars visible at once

async function loadReplayData(){
    const symbol = document.getElementById("symbol").value;
    const tf     = document.getElementById("tf").value;

    const res = await fetch(`/portal/api/replay_feed.php?symbol=${symbol}&timeframe=${tf}`);
    const d   = await res.json();

    replayBars  = d.bars || d.candles || [];
    replayIndex = 0;

    drawCandleChart([]);
}

function drawCandleChart(bars){
    const series = [{
        name:"Price",
        data:bars.map(b => ({
            x:new Date(b.time),
            y:[b.open,b.high,b.low,b.close]
        }))
    }];

    const options = {
        chart:{
            height:420,
            type:"candlestick",
            background:"#05070c",
            foreColor:"#ffffff",
            toolbar:{ show:false }
        },
        series:series,
        xaxis:{ type:"datetime" },
        yaxis:{ tooltip:{ enabled:true } },
        grid:{ borderColor:"#132135" }
    };

    if(candleChart) candleChart.destroy();

    candleChart = new ApexCharts(
        document.querySelector("#candle_chart"),
        options
    );
    candleChart.render();
}

function updateReplay(){
    if(replayIndex >= replayBars.length){
        pauseReplay();
        return;
    }

    const start = Math.max(0, replayIndex - MAX_VISIBLE);
    const slice = replayBars.slice(start, replayIndex + 1);

    drawCandleChart(slice);
    replayIndex++;
}

async function startReplay(){
    if(!replayBars.length){
        await loadReplayData();
    }
    if(replayTimer) return;
    replayTimer = setInterval(updateReplay, 250);  // smoother speed
}

function pauseReplay(){
    if(replayTimer){
        clearInterval(replayTimer);
        replayTimer = null;
    }
}

async function stepReplay(){
    if(!replayBars.length){
        await loadReplayData();
    }
    updateReplay();
}
</script>

</body>
</html>
