
// TAB SWITCHING
document.querySelectorAll(".tab").forEach(b=>{

  b.onclick=()=>{
    document.querySelectorAll(".tab").forEach(x=>x.classList.remove("active"));
    document.querySelectorAll(".tab-content").forEach(x=>x.classList.remove("active"));

    b.classList.add("active");
    document.getElementById(b.dataset.tab).classList.add("active");
  };

});


// LOT STEPPER
function adjLot(v){
  lot.value = Math.max(0.01, parseFloat(lot.value) + v).toFixed(2);
}


// SEND ORDER
send_trade.onclick = ()=>{

 let f=new FormData();

 f.append("license",license.value);
 f.append("symbol",sym.value);
 f.append("side",side.value);
 f.append("lot",lot.value);
 f.append("sl",sl.value);
 f.append("tp",tp.value);

 fetch("/webhook/admin/send_manual_trade.php",{method:"POST",body:f})
 .then(r=>r.json())
 .then(x=>{
   trade_status.innerHTML = JSON.stringify(x);
 });
};



// LOAD POSITIONS
function loadPositions(){

 fetch("/webhook/admin/get_live_positions.php")
 .then(r=>r.json())
 .then(rows=>{

  let h="";

  rows.forEach(p=>{

    h+=`
    <tr>
     <td>${p.ticket}</td>
     <td>${p.symbol}</td>
     <td>${p.side}</td>
     <td>${p.lot}</td>
     <td>${p.entry}</td>
     <td style="color:${p.pnl>=0?'#00ff88':'#ff5577'}">${p.pnl}</td>
     <td>
       <button onclick="cmd('${p.license_key}',${p.ticket},'CLOSE_PARTIAL',50)">50%</button>
       <button onclick="cmd('${p.license_key}',${p.ticket},'CLOSE_FULL',0)">X</button>
     </td>
    </tr>
    `;
  });

   document.querySelector("#pos-table tbody").innerHTML=h;

 });
}


function cmd(license,ticket,action,param){

 let f=new FormData();
 f.append("license",license);
 f.append("ticket",ticket);
 f.append("action",action);
 f.append("param",param);

 fetch("/webhook/admin/send_trade_command.php",{method:"POST",body:f});
}



// LOAD LOGS
function loadLogs(){
 fetch("/webhook/admin/get_execution_logs.php")
 .then(r=>r.text())
 .then(d=>{
    exec_feed.innerHTML = d;
 });
}


// POLL
setInterval(()=>{
 loadPositions();
 loadLogs();
},2000);


loadPositions();
loadLogs();
