<?php
define("FXH_PORTAL", true);
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../middleware/user_auth.php';

$user_id = $_SESSION['user_id'];

/* ------------------------------
   GET LICENSES FOR USER
--------------------------------*/
$licenses_arr = ["'NO-LICENSE'"];
$q = $conn->prepare("SELECT license_key FROM fxhai_lmfwc_licenses WHERE user_id = ?");
$q->bind_param("i", $user_id);
$q->execute();
$r = $q->get_result();
while($x = $r->fetch_assoc()){
    $plain = fxh_decrypt_license($x['license_key']);
    if($plain) $licenses_arr[] = "'" . $conn->real_escape_string($plain) . "'";
}
$license_filter = implode(",", $licenses_arr);


/* ------------------------------
   RETURN MT5 LIST
--------------------------------*/
if(isset($_GET['mt5_list'])){
    $r = $conn->query("
        SELECT DISTINCT mt5_account 
        FROM fxh_trade_logs 
        WHERE license_key IN ($license_filter)
        AND mt5_account <> ''
    ");
    while($m = $r->fetch_assoc()){
        echo "<option value='{$m['mt5_account']}'>MT5 {$m['mt5_account']}</option>";
    }
    exit;
}


/* ------------------------------
   MAIN FILTER QUERY
--------------------------------*/
$page     = intval($_POST['page'] ?? 1);
$rows     = intval($_POST['rows'] ?? 50);
$search   = $_POST['search'] ?? "";
$from     = $_POST['date_from'] ?? "";
$to       = $_POST['date_to'] ?? "";
$mt5      = $_POST['mt5'] ?? "";

$offset = ($page - 1) * $rows;

$where = "WHERE license_key IN ($license_filter)";

/* SEARCH FILTER */
if($search !== ""){
    $s = $conn->real_escape_string($search);
    $where .= " AND (ticket LIKE '%$s%' OR symbol LIKE '%$s%' OR type LIKE '%$s%')";
}

/* DATE RANGE */
if($from !== ""){
    $where .= " AND DATE(close_time) >= '".$conn->real_escape_string($from)."'";
}
if($to !== ""){
    $where .= " AND DATE(close_time) <= '".$conn->real_escape_string($to)."'";
}

/* MT5 FILTER */
if($mt5 !== ""){
    $where .= " AND mt5_account = '".$conn->real_escape_string($mt5)."'";
}

/* COUNT TOTAL */
$total = $conn->query("SELECT COUNT(*) AS c FROM fxh_trade_logs $where")->fetch_assoc()['c'];
$pages = ceil($total / $rows);

/* FETCH DATA */
$q = $conn->query("
    SELECT ticket, symbol, type, volume, open_price, close_price, profit, open_time, close_time, mt5_account
    FROM fxh_trade_logs
    $where
    ORDER BY id DESC
    LIMIT $offset, $rows
");

echo "<table class='fxh-history-table'>";
echo "<tr>
        <th>Ticket</th>
        <th>Symbol</th>
        <th>Type</th>
        <th>Lots</th>
        <th>Open</th>
        <th>Close</th>
        <th>Profit</th>
        <th>Open Time</th>
        <th>Close Time</th>
        <th>MT5</th>
    </tr>";

if($q->num_rows == 0){
    echo "<tr><td colspan='20'>No trades found</td></tr>";
} else {
    while($t = $q->fetch_assoc()){
        echo "
        <tr>
            <td>{$t['ticket']}</td>
            <td>{$t['symbol']}</td>
            <td>".strtoupper($t['type'])."</td>
            <td>{$t['volume']}</td>
            <td>{$t['open_price']}</td>
            <td>{$t['close_price']}</td>
            <td style='color:" . ($t['profit'] >= 0 ? "#27e08a" : "#ff4e4e") . "'>
                {$t['profit']}
            </td>
            <td>{$t['open_time']}</td>
            <td>{$t['close_time']}</td>
            <td>{$t['mt5_account']}</td>
        </tr>";
    }
}
echo "</table>";

/* PAGINATION */
echo "<div class='fxh-pagination'>";
for($i=1; $i <= $pages; $i++){
    $cls = ($i==$page) ? "fxh-page-btn active" : "fxh-page-btn";
    echo "<div class='$cls' data-page='$i'>$i</div>";
}
echo "</div>";
