<?php
define("FXH_PORTAL", true);

// 1) Load config FIRST — session_start here
require_once __DIR__ . '/../config.php';

// 2) Authentication check BEFORE output
require_once __DIR__ . '/../middleware/user_auth.php';

// AJAX files must NOT include header/sidebar or ANY HTML before the output begins.

$user_id = $_SESSION['user_id'];

// Get user licenses
$stmt = $conn->prepare("SELECT license_key FROM fxhai_lmfwc_licenses WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

$licenses = [];
while ($row = $res->fetch_assoc()) {
    $dec = fxh_decrypt_license($row['license_key']);
    if ($dec && strpos($dec, "def5020") !== 0) {
        $licenses[] = "'" . $conn->real_escape_string($dec) . "'";
    }
}

if (empty($licenses)) {
    exit; // nothing to show
}

$filter = implode(",", $licenses);

// fetch open trades
$q = "SELECT * FROM fxh_positions_live WHERE license_key IN ($filter) ORDER BY ticket ASC";
$rows = $conn->query($q);

if (!$rows || $rows->num_rows === 0) {
    exit;
}

while ($r = $rows->fetch_assoc()):
?>
<tr>
    <td><?= $r['ticket'] ?></td>
    <td><?= $r['symbol'] ?></td>
    <td><?= strtoupper($r['type']) ?></td>
    <td><?= $r['volume'] ?></td>
    <td><?= number_format($r['open_price'], 2) ?></td>
    <td><?= number_format($r['sl'], 2) ?></td>
    <td><?= number_format($r['tp'], 2) ?></td>
    <td><?= number_format($r['profit'], 2) ?></td>
    <td><?= number_format($r['swap'], 2) ?></td>
    <td><?= number_format($r['commission'], 2) ?></td>
    <td><?= $r['open_time'] ?></td>
    <td>
        <button class="btn btn-danger btn-sm close-trade" data-ticket="<?= $r['ticket'] ?>">Close</button>
        <button class="btn btn-warning btn-sm partial-close" data-ticket="<?= $r['ticket'] ?>">Partial</button>
    </td>
</tr>
<?php endwhile; ?>
