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

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

/* ---------- HELPERS ---------- */
const PRICE_DEC = 3;
const VOL_DEC   = 2;
function r($n, $dec = 2) { return $n === null ? null : round((float)$n, $dec); }
function lot($raw) { return r(((float)$raw) * 0.0001, VOL_DEC); }
function ts_kolkata($sec, $ms = null) {
    if ($sec === null) return null;
    if ($ms !== null) {
        $dt = (new DateTime('@'.floor($ms/1000)))->setTimezone(new DateTimeZone("Asia/Kolkata"));
        $msOnly = $ms % 1000;
        return $dt->format("Y-m-d H:i:s") . "." . $msOnly;
    }
    return (new DateTime('@'.$sec))->setTimezone(new DateTimeZone("Asia/Kolkata"))->format("Y-m-d H:i:s");
}

/* ---------- INPUT ---------- */
$input = json_decode(file_get_contents("php://input"), true);
$account_id = $input['account_id'] ?? null;
$email = $input['email'] ?? null;

if (!$account_id || !$email) {
    echo json_encode(["success" => false, "message" => "account_id and email are required"]);
    exit;
}

try {
    /* ---------- FETCH USER ---------- */
    $sql = "SELECT trade_id, email, account_type, Balance, equity, leverage, currency 
            FROM liveaccounts 
            WHERE trade_id = ? AND email = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $account_id, $email);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if (!$user) {
        echo json_encode(["success" => false, "message" => "User not found in liveaccounts"]);
        exit;
    }

    /* ---------- CONNECT TO MT5 ---------- */
    $api = new MTWebAPI("WebAPITesterLocal", "./logs", true);
    $ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 10, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
    if ($ret != MTRetCode::MT_RET_OK) {
        echo json_encode(["success" => false, "message" => "Failed to connect to MT5", "error_code" => $ret]);
        exit;
    }

    /* ---------- FETCH MT5 USER ---------- */
    $userMT5 = new MTUser();
    $ret = $api->UserGet((int)$account_id, $userMT5);
    if ($ret != MTRetCode::MT_RET_OK) {
        $api->Disconnect();
        echo json_encode(["success" => false, "message" => "User not found in MT5", "error_code" => $ret]);
        exit;
    }

    $personal_details = [
        "email"        => $user['email'],
        "trade_id"     => $user['trade_id'],
        "account_type" => $user['account_type'] ?? null,
        "balance"      => $userMT5->Balance ?? $user['Balance'] ?? 0,
        "equity"       => $userMT5->Equity ?? $user['equity'] ?? 0,
        "leverage"     => $user['leverage'] ?? null,
        "currency"     => $user['currency'] ?? "USD"
    ];

    /* ---------- IB CLIENTS ---------- */
    $ib_clients = [];
    $conditions = [];
    for ($i = 1; $i <= 20; $i++) {
        $conditions[] = "ib{$i} = ?";
    }
    $where = implode(' OR ', $conditions);

    $query = "SELECT * FROM loginusers WHERE ($where) ORDER BY id DESC";
    $stmtIB = $conn->prepare($query);
    $types = str_repeat('s', 20);
    $bindParams = array_merge([$types], array_fill(0, 20, $email));
    $stmtIB->bind_param(...$bindParams);
    $stmtIB->execute();
    $resIB = $stmtIB->get_result();

    while ($client = $resIB->fetch_assoc()) {
        $clientEmail = $client['email'];
        $totalCommission = 0.00;
        $availableCommission = 0.00;

        $commissionQuery = $conn->prepare("SELECT total_commission, available_commission FROM ib_total_commission WHERE ib_email = ?");
        $commissionQuery->bind_param("s", $clientEmail);
        $commissionQuery->execute();
        $resC = $commissionQuery->get_result();
        if ($rowC = $resC->fetch_assoc()) {
            $totalCommission = floatval($rowC['total_commission']);
            $availableCommission = floatval($rowC['available_commission']);
        }
        $commissionQuery->close();

        $ib_clients[] = [
            "client_name" => trim($client['first_name'] . ' ' . $client['last_name']),
            "client_email" => $clientEmail,
            "country" => $client['country'],
            "phone" => $client['phone'],
            "reg_date" => $client['reg_date'],
            "status" => ($client['status'] == 1) ? "Active" : "Inactive",
            "commission_earned" => round($totalCommission, 2),
            "available_commission" => round($availableCommission, 2)
        ];
    }
    $stmtIB->close();

    /* ---------- FOLLOWERS / INVESTORS SECTION ---------- */
    $followers = [];
    $stmtFollowers = $conn->prepare("SELECT slavename, slavetrade, email, followdate, status FROM copyaccounts WHERE mastertrade = ?");
    $stmtFollowers->bind_param("s", $account_id);
    $stmtFollowers->execute();
    $resFollowers = $stmtFollowers->get_result();
    while ($f = $resFollowers->fetch_assoc()) {
        $followers[] = [
            "follower_name" => $f['slavename'],
            "follower_trade" => $f['slavetrade'],
            "email" => $f['email'],
            "status" => ($f['status'] == 1 ? "Active" : "Inactive"),
            "follow_date" => $f['followdate']
        ];
    }
    $stmtFollowers->close();
    $followers_count = count($followers);

    /* ---------- OPEN POSITIONS ---------- */
    $open_positions = [];
    $total_open = 0;
    if (method_exists($api, 'PositionGetTotal') && $api->PositionGetTotal($userMT5->Login, $total_open) == MTRetCode::MT_RET_OK && $total_open > 0) {
        $positions = [];
        if (method_exists($api, 'PositionGetPage') && $api->PositionGetPage($userMT5->Login, 0, $total_open, $positions) == MTRetCode::MT_RET_OK) {
            foreach ($positions as $pos) {
                $open_positions[] = [
                    "Symbol"       => $pos->Symbol ?? null,
                    "PriceOpen"    => r($pos->PriceOpen ?? null, PRICE_DEC),
                    "PriceCurrent" => r($pos->PriceCurrent ?? null, PRICE_DEC),
                    "Volume"       => lot($pos->Volume ?? 0),
                    "Action"       => (($pos->Action ?? 0) == 1 ? "Sell" : "Buy"),
                    "Profit"       => r($pos->Profit ?? 0, 2),
                    "TimeCreate"   => ts_kolkata($pos->TimeCreate ?? null)
                ];
            }
        }
    }

    /* ---------- CLOSED POSITIONS ---------- */
    $closed_positions = [];
    $total = 0;
    if (($err = $api->DealGetTotal((int)$account_id, 0, 0, $total)) == MTRetCode::MT_RET_OK && $total > 0) {
        $deals = [];
        if (($err = $api->DealGetPage((int)$account_id, 0, 0, 0, $total, $deals)) == MTRetCode::MT_RET_OK && is_array($deals)) {
            foreach ($deals as $deal) {
                if (($deal->Order ?? 0) != 0 && lot($deal->VolumeClosed ?? 0) > 0) {
                    $closed_positions[] = [
                        "Ticket"     => $deal->Order ?? null,
                        "Action"     => (($deal->Action ?? 0) == 1 ? "Sell" : "Buy"),
                        "Volume"     => lot($deal->VolumeClosed ?? 0),
                        "Symbol"     => $deal->Symbol ?? null,
                        "OpenPrice"  => r($deal->PricePosition ?? null, PRICE_DEC),
                        "ClosePrice" => r($deal->Price ?? null, PRICE_DEC),
                        "Profit"     => r($deal->Profit ?? 0, 2),
                        "Commission" => r($deal->Commission ?? 0, 2),
                        "Swap"       => r($deal->Storage ?? 0, 2),
                        "CloseTime"  => ts_kolkata($deal->Time ?? null)
                    ];
                }
            }
        }
    }

    $api->Disconnect();

    /* ---------- RESPONSE ---------- */
    echo json_encode([
        "success" => true,
        "message" => "Master account details fetched successfully",
        "data" => [
            "personal_details" => $personal_details,
            "ib_clients" => $ib_clients,
            "followers" => [
                "count" => $followers_count,
                "list"  => $followers
            ],
            "open_positions" => $open_positions,
            "closed_positions" => $closed_positions
        ]
    ], JSON_PRETTY_PRINT);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Internal Server Error: " . $e->getMessage(),
        "data" => []
    ]);
}
?>
