<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);

include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

// Load MT5
try {
    include_once __DIR__ . "/mt5_api/mt5_api.php";
} catch (Throwable $e) {
    echo json_encode([
        "success" => false,
        "message" => "MT5 include error: " . $e->getMessage()
    ], JSON_PRETTY_PRINT);
    exit;
}

// Read JSON
$input = json_decode(file_get_contents("php://input"), true);

if (!$input) {
    echo json_encode([
        "success" => false,
        "message" => "Invalid JSON input"
    ], JSON_PRETTY_PRINT);
    exit;
}

$email = $input["email"] ?? null;

if (!$email) {
    echo json_encode([
        "success" => false,
        "message" => "Email is required"
    ], JSON_PRETTY_PRINT);
    exit;
}

try {

    // Fetch trade_id and extra info
    $stmt = $conn->prepare("SELECT trade_id, account_name, account_type FROM liveaccounts WHERE email = ? LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $acc = $stmt->get_result()->fetch_assoc();

    if (!$acc) {
        throw new Exception("No liveaccount found for this email");
    }

    $trade_id     = $acc["trade_id"];
    $account_name = $acc["account_name"];
    $account_type = $acc["account_type"];

    // ------------------------------------------
    //      MT5 LOT CALCULATION
    // ------------------------------------------
    $mt5 = new MT5Connection();
    if (!$mt5->connect()) throw new Exception("MT5 connection failed");

    $total_lots = 0;
    $from = 0;
    $to = 0;
    $total = 0;

    $ret_total = $mt5->api->DealGetTotal($trade_id, $from, $to, $total);

    $trade_start = null;
    $trade_end = null;

    if ($ret_total == MTRetCode::MT_RET_OK && $total > 0) {

        $page_size = 100; // batch limit
        $offset = 0;

        while ($offset < $total) {

            $deals = [];
            $ret_page = $mt5->api->DealGetPage($trade_id, $from, $to, $offset, $page_size, $deals);

            if ($ret_page != MTRetCode::MT_RET_OK) break;

            foreach ($deals as $d) {
                if (isset($d->VolumeClosed) && $d->VolumeClosed > 0) {
                    $total_lots += ($d->VolumeClosed * 0.0001);
                }

                // Track trade start and end dates
                if (isset($d->Time)) {
                    $time = $d->Time; // MT5 timestamp
                    if (!$trade_start || $time < $trade_start) $trade_start = $time;
                    if (!$trade_end || $time > $trade_end) $trade_end = $time;
                }
            }

            $offset += $page_size;

            if ($offset > 100000) break;
        }
    }

    $mt5->api->Disconnect();

    // Convert MT5 timestamps to readable datetime
    $trade_start = $trade_start ? date("Y-m-d H:i:s", $trade_start) : null;
    $trade_end   = $trade_end ? date("Y-m-d H:i:s", $trade_end) : null;

    // -----------------------------
    //  FETCH REWARD RULES
    // -----------------------------
    $rules = $conn->query("SELECT * FROM lots_reward WHERE status = 1 ORDER BY lots_required ASC LIMIT 50");

    if (!$rules) throw new Exception("Reward rules fetch failed");

    $required_lots = 0;
    $reward_amount = 0;

    while ($r = $rules->fetch_assoc()) {
        if ($total_lots >= (float)$r["lots_required"]) {
            $required_lots = (float)$r["lots_required"];
            $reward_amount = (float)$r["reward_amount"];
        }
    }

    // -----------------------------
    //  STORE IN lots_reward_users (with extra fields)
    // -----------------------------
    $store_status = false;

    if ($required_lots > 0 && $reward_amount > 0) {

        $stmt2 = $conn->prepare("
            INSERT INTO lots_reward_users 
            (user_email, trade_id, lots_done, reward_amount, account_name, account_type, trade_start, trade_end) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");

        if (!$stmt2) throw new Exception("Insert prepare error");

        $stmt2->bind_param(
            "ssddssss",
            $email,
            $trade_id,
            $total_lots,
            $reward_amount,
            $account_name,
            $account_type,
            $trade_start,
            $trade_end
        );
        $store_status = $stmt2->execute();
    }

    // -----------------------------
    //  FINAL RESPONSE
    // -----------------------------
    echo json_encode([
        "success" => true,
        "email" => $email,
        "trade_id" => $trade_id,
        "lots_done" => round($total_lots, 2),
        "required_lots" => $required_lots,
        "reward_amount" => $reward_amount,
        "trade_start" => $trade_start,
        "trade_end" => $trade_end,
        "reward_range" => $required_lots > 0 ? "Eligible for $required_lots lots reward" : "Not eligible",
        "stored_in_db" => $store_status
    ], JSON_PRETTY_PRINT);

} catch (Throwable $e) {

    echo json_encode([
        "success" => false,
        "message" => $e->getMessage()
    ], JSON_PRETTY_PRINT);
}
