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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

ini_set('display_errors', 1);
error_reporting(E_ALL);

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

// Connect to DB
if ($conn->connect_error) {
    echo json_encode(["success" => false, "message" => "Database connection failed"]);
    exit;
}

// Initialize MT5 connection
$mt5 = new MT5Connection();
if (!$mt5->connect()) {
    echo json_encode([
        "success" => false,
        "message" => "MT5 connection failed",
        "error_code" => $mt5->lastError()
    ]);
    exit;
}

// Fetch all live MT5 trade IDs
$sql = "SELECT trade_id FROM liveaccounts WHERE trade_id IS NOT NULL AND trade_id != ''";
$result = $conn->query($sql);

if (!$result || $result->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "No live accounts found"]);
    exit;
}

// Time ranges
$todayStart = strtotime("today 00:00:00");
$todayEnd   = strtotime("today 23:59:59");
$weekStart  = strtotime("monday this week 00:00:00");
$monthStart = strtotime("first day of this month 00:00:00");
$yearStart  = strtotime("first day of January " . date("Y") . " 00:00:00");

/**
 * Fetch total traded lots for a time period
 */
function getTotalLots($api, $logins, $from, $to) {
    $totalLots = 0;
    $offset = 0;
    $limit = 1000; // MT5 usually returns 1000 records max per page

    foreach ($logins as $login) {
        do {
            $deals = [];
            $ret = $api->DealGetPage($login, $from, $to, $offset, $limit, $deals);

            if ($ret !== MTRetCode::MT_RET_OK || empty($deals)) {
                break;
            }

            foreach ($deals as $deal) {
                if (isset($deal->Entry) && $deal->Entry == 0) { // only real trades
                    // Convert from raw MT5 volume (usually micro-lots)
                    $totalLots += $deal->Volume / 10000.0; // ✅ use 10000.0 instead of 100.0
                }
            }

            // If fewer than limit returned, stop paging
            if (count($deals) < $limit) {
                break;
            }

            $offset += $limit;
        } while (true);
    }

    // Round to 2 decimal places for neat display
    return round($totalLots, 2);
}

// Collect all trade IDs
$tradeIds = [];
while ($row = $result->fetch_assoc()) {
    $tradeIds[] = $row['trade_id'];
}

// Calculate total lots for each time frame
$data = [
    "daily"   => getTotalLots($mt5->api, $tradeIds, $todayStart, $todayEnd),
    "weekly"  => getTotalLots($mt5->api, $tradeIds, $weekStart, time()),
    "monthly" => getTotalLots($mt5->api, $tradeIds, $monthStart, time()),
    "yearly"  => getTotalLots($mt5->api, $tradeIds, $yearStart, time())
];

// Final JSON response
echo json_encode([
    "success" => true,
    "message" => "Total traded lots fetched successfully",
    "data" => $data,
    "date_ranges" => [
        "daily" => date("Y-m-d", $todayStart),
        "weekly_start" => date("Y-m-d", $weekStart),
        "monthly_start" => date("Y-m-d", $monthStart),
        "yearly_start" => date("Y-m-d", $yearStart)
    ]
], JSON_PRETTY_PRINT);
?>
