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

// -------------------- 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;

    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;
            // $ret_total = $mt5->DealGetTotal($trade_id, 0, 0, $totalDeals);
            // if ($ret_total == MTRetCode::MT_RET_OK && $totalDeals > 0) {
            //     $deals = [];
            //     $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 volume from MT5 with paging ---
// $volume = 0;
// $from = 0;
// $to = 0;

// $totalDeals = 0;
// $ret_total = $mt5->DealGetTotal($trade_id, $from, $to, $totalDeals);

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

//     $pageSize = 500;
//     $offset = 0;

//     while ($offset < $totalDeals) {
//         $deals = [];
//         $ret_page = $mt5->DealGetPage($trade_id, $from, $to, $offset, $pageSize, $deals);

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

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

//         $offset += count($deals);
//     }
// }

// $volume = round($volume, 2);
// $total_volume_all += $volume;

// --- Fetch saved volume from DB (like MBS) ---
$stmtVol = $conn->prepare("SELECT total_volume FROM ib_volume WHERE trade_id = ? LIMIT 1");
$stmtVol->bind_param("i", $trade_id);
$stmtVol->execute();
$resVol = $stmtVol->get_result();
$volumeRow = $resVol->fetch_assoc();
$volume = floatval($volumeRow['total_volume'] ?? 0);
$stmtVol->close();

$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;

            // // -------------------- Calculate rebate using ranks table --------------------
            // $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;
            // }
            
            // -------------------- Calculate rebate using IB Dashboard logic --------------------
$rebate = 0;
$rank_commission = 0;
$ac_name = $liveRow['account_type'] ?? '';
$tier_level = 0;

// Determine tier level
for ($i = 1; $i <= 20; $i++) {
    if (($row["ib$i"] ?? '') === $email) {
        $tier_level = $i;
        break;
    }
}

// Check if account type is valid
$isValidAccount = false;
$account_group = '';
if (!empty($ac_name)) {
    $stmt_type = $conn->prepare("SELECT ac_name, ac_group FROM account_types WHERE ac_name = ?");
    $stmt_type->bind_param("s", $ac_name);
    $stmt_type->execute();
    $res_type = $stmt_type->get_result();
    if ($typeRow = $res_type->fetch_assoc()) {
        $ac_name = $typeRow['ac_name'];
        $account_group = $typeRow['ac_group'];
        $isValidAccount = true;
    }
    $stmt_type->close();
}

// Calculate active clients for this tier
$tierClients = [];
$stmt_tier = $conn->prepare("SELECT email FROM liveaccounts WHERE ib$tier_level = ?");
$stmt_tier->bind_param("s", $email);
$stmt_tier->execute();
$res_tier = $stmt_tier->get_result();
while ($r = $res_tier->fetch_assoc()) {
    $tierClients[] = $r['email'];
}
$stmt_tier->close();
$activeClientsForTier = count(array_unique($tierClients));

// Get rank data for this tier
$rankNumberTier = 1;
$rankDataTier = [];
$stmt_rank = $conn->prepare("SELECT * FROM ranks WHERE min_active_clients <= ? ORDER BY rank_number DESC LIMIT 1");
$stmt_rank->bind_param("i", $activeClientsForTier);
$stmt_rank->execute();
$res_rank = $stmt_rank->get_result();
if ($row_rank = $res_rank->fetch_assoc()) {
    $rankNumberTier = intval($row_rank['rank_number']);
    $rankDataTier = $row_rank;
}
$stmt_rank->close();

// ---------- Calculate commission using account_types table ----------
$rebate = 0;

if ($isValidAccount && $tier_level > 0 && $volume > 0) {

    // account_types column name example: ib_commission1, ib_commission2 ...
    $commissionColumn = "ib_commission" . $tier_level;

    if (isset($accountTypes[$ac_name][$commissionColumn])) {
        $rate = floatval($accountTypes[$ac_name][$commissionColumn]);
        $rebate = $volume * $rate;
    }
}



            $user_total_commission += $rebate;
            $total_commission_all += $rebate;

            $liveAccounts[] = [
                "trade_id" => $trade_id,
                "server" => $liveRow['server'],
                "balance" => $balance,
                "equity" => $equity,
                "status" => $liveRow['status'],
                "account_type" => $ac_name,
                "leverage" => $liveRow['leverage'],
                "volume" => $volume,
                "commission" => $rebate,
                "tier_level" => $tier_level
            ];

            // --- Store in database table `ib_accounts` ---
            $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
            ");
            $stmt->bind_param(
                "sissssssddddis",
                $email,
                $user_id,
                $row['first_name'],
                $row['last_name'],
                $trade_id,
                $liveRow['server'],
                $ac_name,
                $liveRow['leverage'],
                $balance,
                $equity,
                $volume,
                $rebate,
                $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" => round($user_total_commission, 2),
            "liveaccounts" => $liveAccounts
        ];
    }
}

// --- Calculate available commission ---
$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();

// -------------------- 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),
    "total_commission" => round($total_commission_all, 2),
    "available_commission" => round($available_commission, 2),
    "total_volume" => round($total_volume_all, 2),
    "rank" => [
        "rank_number" => $rankNumber,
        "rank_name" => $rankName,
        "active_clients" => $totalActiveClients
    ],
    "users" => $users
], JSON_PRETTY_PRINT);

exit;
?>
