<?php
/* ==========================================================
   FXHUNTER PORTAL — POST TRADE RECEIVER (FINAL)
   Receives trade logs from MT5 EA and stores in DB
   ========================================================== */

// DEBUG — record raw request
file_put_contents(__DIR__ . "/debug_post_trade_raw.txt",
    "---- " . date("Y-m-d H:i:s") . " ----\n" .
    "GET: " . print_r($_GET, true) .
    "POST: " . print_r($_POST, true) .
    "RAW: " . file_get_contents("php://input") . "\n\n",
    FILE_APPEND
);

// ---------------------------------------------
// Load config (DB + decrypt + password)
// ---------------------------------------------
require_once __DIR__ . "/../config.php";

// ---------------------------------------------
// SAFE POST PARSER
// ---------------------------------------------
function fxh_get_post_data() {
    $data = $_POST;

    // If empty, read raw body (application/x-www-form-urlencoded)
    if (empty($data)) {
        $raw = file_get_contents("php://input");
        parse_str($raw, $parsed);
        if (!empty($parsed)) {
            $data = $parsed;
        }
    }
    return $data;
}

// ---------------------------------------------
// MT5 TIME FORMAT FIXER
//  - MT5 sends: 2025.11.26 17:46:14
//  - MySQL needs: 2025-11-26 17:46:14
// ---------------------------------------------
function fxh_fix_mt5_time($str) {
    $str = trim((string)$str);
    if ($str === '' || $str === '0') {
        return null;
    }

    // Try MT5 format: Y.m.d H:i:s
    $dt = DateTime::createFromFormat('Y.m.d H:i:s', $str);
    if ($dt instanceof DateTime) {
        return $dt->format('Y-m-d H:i:s');
    }

    // Try already-correct format
    $dt = DateTime::createFromFormat('Y-m-d H:i:s', $str);
    if ($dt instanceof DateTime) {
        return $dt->format('Y-m-d H:i:s');
    }

    // Fallback to strtotime
    $ts = strtotime($str);
    if ($ts !== false && $ts > 0) {
        return date('Y-m-d H:i:s', $ts);
    }

    // Final fallback → NULL (let MySQL default, or handle upstream)
    return null;
}

$data = fxh_get_post_data();

// If still empty → stop
if (empty($data)) {
    file_put_contents(__DIR__ . "/debug_post_trade_error.txt",
        date("Y-m-d H:i:s") . " — ERROR: EMPTY POST\n",
        FILE_APPEND
    );
    echo "NO_DATA";
    exit;
}

// ---------------------------------------------
// Extract fields
// ---------------------------------------------
$license_key = $conn->real_escape_string($data["license_key"] ?? "");
$mt5_account = $conn->real_escape_string($data["mt5_account"] ?? "");
$ticket      = $conn->real_escape_string($data["ticket"] ?? "");
$symbol      = $conn->real_escape_string($data["symbol"] ?? "");
$type        = $conn->real_escape_string($data["type"] ?? "");
$volume      = $conn->real_escape_string($data["volume"] ?? "0");
$open_price  = $conn->real_escape_string($data["open_price"] ?? "0");
$close_price = $conn->real_escape_string($data["close_price"] ?? "0");
$profit      = $conn->real_escape_string($data["profit"] ?? "0");

// raw MT5 time strings
$open_time_raw  = $data["open_time"]  ?? "";
$close_time_raw = $data["close_time"] ?? "";

// convert to MySQL format
$open_time  = fxh_fix_mt5_time($open_time_raw);
$close_time = fxh_fix_mt5_time($close_time_raw);

// if conversion failed, you can optionally default to created_at time
if ($open_time === null)  $open_time  = date('Y-m-d H:i:s');
if ($close_time === null) $close_time = date('Y-m-d H:i:s');

$sl      = $conn->real_escape_string($data["sl"] ?? "0");
$tp      = $conn->real_escape_string($data["tp"] ?? "0");
$comment = $conn->real_escape_string($data["comment"] ?? "");

// ---------------------------------------------
// Insert into database
// ---------------------------------------------
$sql = "
INSERT INTO fxh_trade_logs
(license_key, mt5_account, ticket, symbol, type, volume,
 open_price, close_price, profit, open_time, close_time,
 sl, tp, comment)
VALUES
('$license_key', '$mt5_account', '$ticket', '$symbol', '$type', '$volume',
 '$open_price', '$close_price', '$profit', '$open_time', '$close_time',
 '$sl', '$tp', '$comment')
";

// DEBUG: log SQL
file_put_contents(__DIR__ . "/debug_post_trade_sql.txt",
    "---- " . date("Y-m-d H:i:s") . " ----\n" . $sql . "\n\n",
    FILE_APPEND
);

if ($conn->query($sql)) {
    echo "OK";
} else {
    file_put_contents(__DIR__ . "/debug_post_trade_sql_error.txt",
        date("Y-m-d H:i:s") . " — SQL ERROR: " . $conn->error . "\n\n",
        FILE_APPEND
    );
    echo "SQL_ERROR";
}
?>
