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

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

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

$input = json_decode(file_get_contents("php://input"), true);
$email = trim($input['email'] ?? '');
if (!$email) {
    echo json_encode(["success" => false, "message" => "Email is required"]);
    exit;
}

// -------------------- Connect MT5 API --------------------
$mt5 = new MTWebAPI("WebAPITesterLocal", "./logs", true);
$ret = $mt5->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
if ($ret != MTRetCode::MT_RET_OK) {
    echo json_encode(["success" => false, "message" => "MT5 connection failed"]);
    exit;
}

// -------------------- Fetch IB users --------------------
$query = "SELECT * FROM loginusers WHERE ? IN (ib1,ib2,ib3,ib4,ib5,ib6,ib7,ib8,ib9,ib10,
                                               ib11,ib12,ib13,ib14,ib15,ib16,ib17,ib18,ib19,ib20)";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$ib_users = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

if (!$ib_users) {
    echo json_encode([
        "success" => true,
        "total_users" => 0,
        "total_liveaccounts" => 0,
        "total_balance" => 0,
        "total_equity" => 0,
        "total_commission" => 0,
        "total_volume" => 0,
        "users" => []
    ], JSON_PRETTY_PRINT);
    exit;
}

// -------------------- Fetch all account types --------------------
$accountTypesResult = $conn->query("SELECT * FROM account_types");
$accountTypes = [];
while ($row = $accountTypesResult->fetch_assoc()) {
    $accountTypes[$row['ac_name']] = $row;
}

// -------------------- Fetch all live accounts for these users --------------------
$user_ids = array_column($ib_users, 'id');
$user_ids_placeholder = implode(',', array_fill(0, count($user_ids), '?'));
$types = str_repeat('i', count($user_ids));

$liveQuery = "SELECT * FROM liveaccounts WHERE user_id IN ($user_ids_placeholder) AND status='active'";
$liveStmt = $conn->prepare($liveQuery);
$liveStmt->bind_param($types, ...$user_ids);
$liveStmt->execute();
$liveResult = $liveStmt->get_result();
$all_live_accounts = $liveResult->fetch_all(MYSQLI_ASSOC);
$liveStmt->close();

// Map live accounts by user
$live_accounts_by_user = [];
foreach ($all_live_accounts as $acct) {
    $live_accounts_by_user[$acct['user_id']][] = $acct;
}

// -------------------- Determine Rank based on total IB users --------------------
$totalActiveClients = count($ib_users);
$rankNumber = 1;
$rankName = "Rank 1";
$rankData = [];

$stmt_rank = $conn->prepare("SELECT * FROM ranks WHERE min_active_clients <= ? ORDER BY rank_number DESC LIMIT 1");
$stmt_rank->bind_param("i", $totalActiveClients);
$stmt_rank->execute();
$res_rank = $stmt_rank->get_result();
if ($row_rank = $res_rank->fetch_assoc()) {
    $rankNumber = intval($row_rank['rank_number']);
    $rankName = $row_rank['rank_name'];
    $rankData = $row_rank;
}
$stmt_rank->close();

// -------------------- Initialize totals --------------------
$users = [];
$total_liveaccounts = 0;
$total_balance_all = 0;
$total_equity_all = 0;
$total_commission_all = 0;
$total_volume_all = 0;
$total_profit_commission_all = 0; // runtime-calculated profit commission total

// -------------------- Process each IB user --------------------
foreach ($ib_users as $row) {
    $user_id = $row['id'];
    $liveAccounts = [];
    $user_total_balance = 0;
    $user_total_equity = 0;
    $user_total_commission = 0;
    $user_total_profit_commission = 0; // per-user runtime profit commission

    if (isset($live_accounts_by_user[$user_id])) {
        foreach ($live_accounts_by_user[$user_id] as $liveRow) {
            $trade_id = intval($liveRow['trade_id']);

            // --- Fetch volume from MT5 ---
            $volume = 0;
            $totalDeals = 0;
            $deals = [];
            $ret_total = $mt5->DealGetTotal($trade_id, 0, 0, $totalDeals);
            if ($ret_total == MTRetCode::MT_RET_OK && $totalDeals > 0) {
                $ret_page = $mt5->DealGetPage($trade_id, 0, 0, 0, $totalDeals, $deals);
                if ($ret_page == MTRetCode::MT_RET_OK) {
                    foreach ($deals as $deal) {
                        $volume += isset($deal->VolumeClosed) ? $deal->VolumeClosed * 0.0001 : 0;
                    }
                }
            }
            $volume = round($volume, 2);
            $total_volume_all += $volume;

            // --- Fetch balance & equity from MT5 ---
            $userMT5 = new MTUser();
            $mt5->UserGet($trade_id, $userMT5);
            $balance = floatval($userMT5->Balance ?? 0);
            $equity = floatval($userMT5->Equity ?? 0);

            $user_total_balance += $balance;
            $user_total_equity += $equity;
            $total_balance_all += $balance;
            $total_equity_all += $equity;

            /* ------------------------------------------------------------------
               COMMENTED OUT: Rebate calculation (disabled for now)
               ------------------------------------------------------------------
            */

            // // old rebate logic (commented)
            // $rebate = 0;
            // $ac_name = $liveRow['account_type'];
            // if (!empty($ac_name)) {
            //     // Determine tier level for this account
            //     $tier_level = 0;
            //     for ($i = 1; $i <= 20; $i++) {
            //         if ($row["ib$i"] == $email) {
            //             $tier_level = $i;
            //             break;
            //         }
            //     }
            //     // Determine commission from ranks table
            //     $commission_type = strtolower($ac_name);
            //     $commission_field_type = "level_{$tier_level}_{$commission_type}_commission";
            //     $rank_commission = isset($rankData[$commission_field_type])
            //         ? floatval($rankData[$commission_field_type])
            //         : floatval($rankData["level_{$tier_level}_basic_commission"] ?? 0);
            //     $rebate = $volume * $rank_commission;
            // }

            // -------------------- PROFIT COMMISSION: compute and show instead of rebate --------------------
            $profit_commission = 0.0;
            $sumProfit = 0.0;

            // Sum profits from deals if available
            if (is_array($deals) && count($deals) > 0) {
                foreach ($deals as $d) {
                    $order_id = $d->Order ?? 0;
                    $vol_closed = floatval($d->VolumeClosed ?? 0) * 0.0001;
                    if ($order_id != 0 && $vol_closed > 0) {
                        $sumProfit += floatval($d->Profit ?? 0);
                    }
                }
            } else {
                // fallback: fetch deals specifically for profit calculation
                $totalDealsProfit = 0;
                $ret_total_profit = $mt5->DealGetTotal($trade_id, 0, 0, $totalDealsProfit);
                if ($ret_total_profit == MTRetCode::MT_RET_OK && $totalDealsProfit > 0) {
                    $dealsProfit = [];
                    $ret_page_profit = $mt5->DealGetPage($trade_id, 0, 0, 0, $totalDealsProfit, $dealsProfit);
                    if ($ret_page_profit == MTRetCode::MT_RET_OK && is_array($dealsProfit)) {
                        foreach ($dealsProfit as $dp) {
                            $order_id = $dp->Order ?? 0;
                            $vol_closed = floatval($dp->VolumeClosed ?? 0) * 0.0001;
                            if ($order_id != 0 && $vol_closed > 0) {
                                $sumProfit += floatval($dp->Profit ?? 0);
                            }
                        }
                    }
                }
            }

            // Determine tier level (which ib slot the IB occupies for this user)
            $tier_level = 0;
            for ($i = 1; $i <= 20; $i++) {
                if (($row["ib$i"] ?? '') === $email) {
                    $tier_level = $i;
                    break;
                }
            }

            // Get IB percent from account_types for this account type
            $account_type_name = $liveRow['account_type'] ?? '';
            if (!empty($account_type_name) && $tier_level > 0) {
                $stmt_type_pc = $conn->prepare("SELECT * FROM account_types WHERE ac_name = ?");
                if ($stmt_type_pc) {
                    $stmt_type_pc->bind_param("s", $account_type_name);
                    $stmt_type_pc->execute();
                    $res_type_pc = $stmt_type_pc->get_result();
                    if ($typeRowPC = $res_type_pc->fetch_assoc()) {
                        $ib_comm_field = "ib_commission" . $tier_level; // e.g., ib_commission1
                        $ib_percent = isset($typeRowPC[$ib_comm_field]) ? floatval($typeRowPC[$ib_comm_field]) : 0;
                        if ($ib_percent > 0 && $sumProfit > 0) {
                            $profit_commission = ($sumProfit * $ib_percent) / 100.0;
                        }
                    }
                    $stmt_type_pc->close();
                }
            }

            // For compatibility with existing front-end expecting "commission", map it to profit_commission
            $display_commission = $profit_commission;

            // accumulate totals
            // rebate is disabled so existing commission totals remain unchanged (left as 0)
            $user_total_profit_commission += $profit_commission;
            $total_profit_commission_all += $profit_commission;

            $liveAccounts[] = [
                "trade_id" => $trade_id,
                "server" => $liveRow['server'],
                "balance" => $balance,
                "equity" => $equity,
                "status" => $liveRow['status'],
                "account_type" => $account_type_name,
                "leverage" => $liveRow['leverage'],
                "volume" => $volume,
                // commission field now contains profit_commission for display
                "commission" => round($display_commission, 2),
                "profit_commission" => round($profit_commission, 2),
                "tier_level" => $tier_level
            ];

            // --- Store in database table `ib_accounts` ---
            // NOTE: keep DB insert unchanged (commission column gets 0.0 since rebate is disabled)
            $stmt = $conn->prepare("
                INSERT INTO ib_accounts 
                (ib_email, user_id, first_name, last_name, trade_id, server, account_type, leverage, balance, equity, volume, commission, tier_level, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE 
                    balance = VALUES(balance),
                    equity = VALUES(equity),
                    volume = VALUES(volume),
                    commission = VALUES(commission),
                    tier_level = VALUES(tier_level),
                    updated_at = CURRENT_TIMESTAMP
            ");
            $zero_commission = 0.0; // since rebate is disabled
            $stmt->bind_param(
                "sissssssddddis",
                $email,
                $user_id,
                $row['first_name'],
                $row['last_name'],
                $trade_id,
                $liveRow['server'],
                $account_type_name,
                $liveRow['leverage'],
                $balance,
                $equity,
                $volume,
                $zero_commission,
                $tier_level,
                $liveRow['status']
            );
            $stmt->execute();
            $stmt->close();
        }

        $total_liveaccounts += count($liveAccounts);
    }

    if (!empty($liveAccounts)) {
        $users[] = [
            "id" => $user_id,
            "first_name" => $row['first_name'],
            "last_name" => $row['last_name'],
            "email" => $row['email'],
            "total_balance" => round($user_total_balance, 2),
            "total_equity" => round($user_total_equity, 2),
            // total_commission (rebate) left as-is (rebates disabled)
            "total_commission" => round($user_total_commission, 2),
            // runtime-calculated profit commission per user
            "total_profit_commission" => round($user_total_profit_commission, 2),
            "liveaccounts" => $liveAccounts
        ];
    }
}

// --- Calculate available commission (rebate withdraws) ---
$stmt_withdraw = $conn->prepare("SELECT IFNULL(SUM(withdraw_amount),0) AS withdrawn FROM ib_withdraw WHERE email = ? AND Status = 1");
$stmt_withdraw->bind_param("s", $email);
$stmt_withdraw->execute();
$result_withdraw = $stmt_withdraw->get_result();
$row_withdraw = $result_withdraw->fetch_assoc();
$withdrawn_amount = floatval($row_withdraw['withdrawn'] ?? 0);
$stmt_withdraw->close();

$available_commission = $total_commission_all - $withdrawn_amount;

$stmt_total = $conn->prepare("
    INSERT INTO ib_total_commission (ib_email, total_commission, available_commission)
    VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE
        total_commission = VALUES(total_commission),
        available_commission = VALUES(available_commission),
        updated_at = CURRENT_TIMESTAMP
");
$stmt_total->bind_param("sdd", $email, $total_commission_all, $available_commission);
$stmt_total->execute();
$stmt_total->close();

// -------------------- Fetch total profit commission from ib_total_profit_commission (DB stored) --------------------
$stmt_profit = $conn->prepare("SELECT total_profit_commission, available_profit_commission FROM ib_total_profit_commission WHERE ib_email = ?");
$stmt_profit->bind_param("s", $email);
$stmt_profit->execute();
$result_profit = $stmt_profit->get_result();
$row_profit = $result_profit->fetch_assoc();
$total_profit_commission_db = floatval($row_profit['total_profit_commission'] ?? 0);
$available_profit_commission_db = floatval($row_profit['available_profit_commission'] ?? 0);
$stmt_profit->close();

// -------------------- Disconnect MT5 --------------------
$mt5->Disconnect();

// -------------------- Response --------------------
echo json_encode([
    "success" => true,
    "total_users" => count($users),
    "total_liveaccounts" => $total_liveaccounts,
    "total_balance" => round($total_balance_all, 2),
    "total_equity" => round($total_equity_all, 2),
    // rebate totals remain (disabled)
    "total_commission" => round($total_commission_all, 2),
    "available_commission" => round($available_commission, 2),
    // both DB-stored profit commission and runtime-calculated totals
    "total_profit_commission" => round($total_profit_commission_db, 4),
    "available_profit_commission" => round($available_profit_commission_db, 4),
    "total_profit_commission_runtime" => round($total_profit_commission_all, 2),
    "total_volume" => round($total_volume_all, 2),
    "rank" => [
        "rank_number" => $rankNumber,
        "rank_name" => $rankName,
        "active_clients" => $totalActiveClients
    ],
    "users" => $users
], JSON_PRETTY_PRINT);

exit;
?>
