<?php
ob_start();
session_start();
date_default_timezone_set('Asia/Kolkata');

$con = mysqli_connect("localhost", "root", "", "hopex");
if (mysqli_connect_errno()) {
    echo json_encode(['success' => false, 'message' => 'DB connection failed']);
    exit;
}

header('Content-Type: application/json');

if ($_POST) {
    $ids = $_POST['ids'] ?? '';
    $member_ids = $_POST['member_ids'] ?? '';
    $amounts = $_POST['amounts'] ?? '';

    if (empty($ids)) {
        echo json_encode(['success' => false, 'message' => 'No withdrawals selected']);
        exit;
    }

    $idsArray = explode(',', $ids);
    $memberIdsArray = explode(',', $member_ids);
    $amountsArray = explode(',', $amounts);

    $successCount = 0;
    $errorCount = 0;
    $errors = [];

    mysqli_begin_transaction($con);

    try {
        foreach ($idsArray as $index => $id) {
            $withdrawId = mysqli_real_escape_string($con, trim($id));
            $memberId = mysqli_real_escape_string($con, trim($memberIdsArray[$index]));


            $selectQuery = "SELECT * FROM meddolic_user_wallet_withdrawal_crypto WHERE id = '$withdrawId'";
            $result = mysqli_query($con, $selectQuery);
            $row = mysqli_fetch_assoc($result);

            if (!$row) {
                $errorCount++;
                $errors[] = "ID $withdrawId not found.";
                continue;
            }

            $distributedFund = $row['distributedFund'];
            $orderId = $row['orderid'];
            $netAmount = $row['netAmount'];


            $queryConfig = mysqli_query($con, "SELECT withdrawCharge FROM meddolic_config_misc_setting");
            $valConfig = mysqli_fetch_assoc($queryConfig);
            $withdrawCharge = $valConfig['withdrawCharge'];

            $Charge = $netAmount * $withdrawCharge / 100;
            $netAmount -= $Charge;


            $queryAddress = mysqli_query($con, "SELECT walletAddress FROM meddolic_user_details WHERE member_id='$memberId'");
            $valAddress = mysqli_fetch_assoc($queryAddress);
            $WalletAddress = $valAddress['walletAddress'] ?? '';

            if (empty($WalletAddress) || strlen($WalletAddress) < 10) {
                $errorCount++;
                $errors[] = "Invalid Wallet ($WalletAddress) for ID: $withdrawId";
                continue;
            }

            $curl = curl_init();
            $payload = json_encode([
                "withdrawals" => [
                    [
                        "address" => $WalletAddress,
                        "currency" => "USDTBSC",
                        "amount" => (float) $netAmount,
                        "ipnCallbackUrl" => "https://hopexglobal.com/withdrowalReturnFaradpayApi"
                    ]
                ]
            ]);

            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://gateway.faradpay.com/api/payout',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $payload,
                CURLOPT_HTTPHEADER => array(
                    'x-api-key: 98A7DE9D-1B5B-4244-B307-094FCF018B20',
                    'Content-Type: application/json'
                ),
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);
            curl_close($curl);

            if ($err) {
                $errorCount++;
                $errors[] = "cURL Error ID $withdrawId: $err";
                continue;
            }

            $data = json_decode($response, true);


            if (isset($data['status']) && $data['status'] === 'error') {
                $errorCount++;
                $msg = $data['message'] ?? 'Unknown API Error';
                $errors[] = "API Fail ID $withdrawId: $msg";

                mysqli_query($con, "UPDATE meddolic_user_wallet_withdrawal_crypto SET `status`='FAILED' WHERE id='$withdrawId'");
                continue;
            }

            $withdrawal = $data['data']['withdrawals'][0] ?? null;

            if ($withdrawal) {
                $Trnxid = $withdrawal['id'];
                $status = $withdrawal['status'];

                mysqli_query($con, "UPDATE meddolic_user_wallet_withdrawal_crypto SET trnxId='$Trnxid', status='$status' WHERE id='$withdrawId'");

                $updateQuery = "UPDATE meddolic_user_wallet_withdrawal_crypto 
                                SET released = 3, payment_date = NOW(), remarks = 'Online Release'
                                WHERE id = '$withdrawId'";

                $updateResult = mysqli_query($con, $updateQuery);

                if ($updateResult) {
                    $successCount++;

                    // $updateBalance = "UPDATE meddolic_user_details 
                    //                   SET tradeWallet = tradeWallet + $distributedFund,
                    //                       splitWallet = splitWallet + $distributedFund,
                    //                       retopup_wallet = retopup_wallet + $distributedFund
                    //                   WHERE member_id = '$memberId'";
                    // mysqli_query($con, $updateBalance);
                } else {
                    $errorCount++;
                    $errors[] = "DB Update Failed ID: $withdrawId";
                }
            } else {
                $errorCount++;
                $errors[] = "No data returned from API for ID: $withdrawId";
            }
        }

        mysqli_commit($con);
        ob_clean();

        $isSuccess = ($successCount > 0);

        echo json_encode([
            'success' => $isSuccess,
            'message' => "$successCount released. $errorCount failed.",
            'details' => $errors
        ]);

    } catch (Exception $e) {
        mysqli_rollback($con);
        ob_clean();
        echo json_encode(['success' => false, 'message' => 'Exception: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}
?>