<?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'] ?? '');
$withdraw_amount = floatval($input['withdraw_amount'] ?? 0);
$withdraw_type = trim($input['withdraw_type'] ?? '');
$company_bank = trim($input['company_bank'] ?? '');
$client_bank = trim($input['client_bank'] ?? '');
$account_holder_name = trim($input['account_holder_name'] ?? '');
$account_number = trim($input['account_number'] ?? '');
$ifsc = trim($input['ifsc'] ?? '');
$type = trim($input['type'] ?? 'commission'); // default type commission
$transaction_id = uniqid("TXN");
$random = bin2hex(random_bytes(10));

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

// STEP 1: Calculate Total Commission (similar logic to ib_comession.php)
$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);

if (!$ib_users) {
    echo json_encode(["success" => false, "message" => "No IB users found for this email"]);
    exit;
}

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

// Calculate commission
$total_commission_all = 0;
$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);

foreach ($ib_users as $row) {
    $user_id = $row['id'];

    foreach ($all_live_accounts as $liveRow) {
        if ($liveRow['user_id'] != $user_id) continue;

        $trade_id = intval($liveRow['trade_id']);
        $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);

        // Commission based on account type
        $rebate = 0;
        $ac_group = $liveRow['account_type'];
        if (isset($accountTypes[$ac_group])) {
            $acctTypeRow = $accountTypes[$ac_group];
            for ($i = 1; $i <= 20; $i++) {
                $ib_field = "ib$i";
                if ($row[$ib_field] == $email) {
                    $rebate_rate = floatval($acctTypeRow["ib_commission$i"] ?? 0);
                    $rebate = $rebate_rate * $volume;
                    break;
                }
            }
        }

        $total_commission_all += $rebate;
    }
}
$mt5->Disconnect();

// STEP 2: Check if withdraw_amount <= total_commission
if ($withdraw_amount > $total_commission_all) {
    echo json_encode([
        "success" => false,
        "message" => "Insufficient commission balance. Available: $total_commission_all"
    ]);
    exit;
}

// STEP 3: Insert withdrawal request
$insert = $conn->prepare("INSERT INTO ib_withdraw 
    (email, withdraw_amount, withdraw_type, company_bank, client_bank, account_holder_name, 
    account_number, ifsc, type, transaction_id, random, Status) 
    VALUES (?,?,?,?,?,?,?,?,?,?,?,0)");

$insert->bind_param("sdsssssssss", $email, $withdraw_amount, $withdraw_type, $company_bank,
    $client_bank, $account_holder_name, $account_number, $ifsc, $type, $transaction_id, $random);

if ($insert->execute()) {
    echo json_encode([
        "success" => true,
        "message" => "Withdrawal request submitted successfully",
        "transaction_id" => $transaction_id,
        "requested_amount" => $withdraw_amount,
        "available_commission" => round($total_commission_all, 2)
    ]);
} else {
    echo json_encode([
        "success" => false,
        "message" => "Failed to submit withdrawal request",
        "error" => $insert->error
    ]);
}
?>
