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

$user_id = $_SESSION['user_id'];

$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);

$search = $_GET['search'] ?? "";
$from   = $_GET['date_from'] ?? "";
$to     = $_GET['date_to'] ?? "";
$mt5    = $_GET['mt5'] ?? "";

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

if($search){
    $s = $conn->real_escape_string($search);
    $where .= " AND (ticket LIKE '%$s%' OR symbol LIKE '%$s%' OR type LIKE '%$s%')";
}
if($from){
    $where .= " AND DATE(close_time) >= '".$conn->real_escape_string($from)."'";
}
if($to){
    $where .= " AND DATE(close_time) <= '".$conn->real_escape_string($to)."'";
}
if($mt5){
    $where .= " AND mt5_account = '".$conn->real_escape_string($mt5)."'";
}

header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=fxhunter_history.csv");

$out = fopen("php://output", "w");

fputcsv($out, ["Ticket","Symbol","Type","Volume","Open Price","Close Price","Profit","Open Time","Close Time","MT5"]);

$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
");

while($t = $q->fetch_assoc()){
    fputcsv($out, $t);
}

fclose($out);
exit;
