<?php
ob_start();

session_start();
date_default_timezone_set('Asia/Kolkata');

$con = mysqli_connect("localhost", "root", "", "hopex");
if (mysqli_connect_errno()) {
    error_log("MySQL Connection Error: " . mysqli_connect_error());
    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]));
            $amount = mysqli_real_escape_string($con, trim($amountsArray[$index]));

            $updateQuery = "UPDATE meddolic_user_wallet_withdrawal_crypto 
                            SET released = 2, payment_date = NOW(), remarks = 'Rejected via Admin'
                            WHERE id = '$withdrawId' AND member_id = '$memberId' AND released = 0";

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

            if ($updateResult && mysqli_affected_rows($con) > 0) {
                $successCount++;

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

                $updateBalance = "UPDATE meddolic_user_details 
                                  SET wallet = wallet + $amount
                                  WHERE member_id = '$memberId'";

                mysqli_query($con, $updateBalance);

            } else {
                $errorCount++;
                $errors[] = "Failed to release withdrawal ID: $withdrawId";
            }
        }

        mysqli_commit($con);

        ob_clean();

        echo json_encode([
            'success' => true,
            'message' => "$successCount withdrawal(s) rejefcted" . ($errorCount ? ", $errorCount failed" : ""),
            'details' => [
                'success' => $successCount,
                'errors' => $errorCount,
                'error_messages' => $errors
            ]
        ]);

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

} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}
?>