<?php
// ---------------------------------------------------------
// 1. CONFIGURATION & INITIALIZATION
// ---------------------------------------------------------
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once('includes/init.php');
session_start();

// Redirect if not logged in
if (!isset($_SESSION['token'])) {
    header('location: login-required.php');
    exit();
}

$token = $_SESSION['token'];
$user_data = get_user_by_token($conn, $token);
$mobile = $user_data['mobile'];
$balance = 0;

$available = true;
$withdraw_success = false;
$method = "";

// Default values to prevent "Undefined Variable" errors if init.php is missing them
if (!isset($onetimepay)) $onetimepay = 0; 
if (!isset($payment)) $payment = true; 
if (!isset($recharge_user_auto_server)) $recharge_user_auto_server = 0;

$errors = array();

// ---------------------------------------------------------
// 2. GET USER BALANCE & STATUS
// ---------------------------------------------------------
$sql = "SELECT balance, pending FROM users WHERE mobile='$mobile'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) == 1) {
    while ($user = mysqli_fetch_assoc($result)) {
        $balance = $user["balance"];
        
        // If user has a pending payment, block new ones unless onetimepay is enabled
        if ($user["pending"] == 1) {
            if ($onetimepay == 0) {
                $available = true;
            } else {
                $available = false;
            }
        }
    }
} else {
    array_push($errors, "User not found");
}

// ---------------------------------------------------------
// 3. HANDLE WITHDRAWAL REQUEST
// ---------------------------------------------------------
if (isset($_POST['req'])) {
    
    // Sanitize Inputs
    if (isset($_POST['method'])) {
        $method = compactify($conn, $_POST['method']);
    }
    
    $point = compactify($conn, $_POST['point']);
    $point = (int) preg_replace('/\D/', '', $point); // Ensure point is integer
    $withdraw_mobile = compactify($conn, $_POST['withdraw_mobile']);

    // --- VALIDATION ---
    if (!$method || empty($method)) {
        array_push($errors, "Method is required");
    }
    if (empty($point)) {
        array_push($errors, "Point is required");
    }
    if (isset($_POST['point_minimum']) && $point < $_POST['point_minimum']) {
        array_push($errors, "Minimum point is " . $_POST['point_minimum']);
    }
    if (empty($withdraw_mobile)) {
        array_push($errors, "Account is required");
    }
    if ($point > $balance) {
        array_push($errors, "Not enough points");
    }
    if (!$available) {
        array_push($errors, "You already have a pending request.");
    }

    // --- PROCESS IF NO ERRORS ---
    if (count($errors) == 0) {
        
        $api_success = false;
        
        // --- AUTO SERVER API LOGIC ---
        // This block handles ALL methods (Recharge, Bkash, Nagad, etc.) in one go
        if ($recharge_user_auto_server == 1) {
            
            $url = "";
            $rid_uniq = rand(100000, 999999);
            
            // Logic for Prepaid/Topup URL
            if ($method == "Prepaid" || $method == "Recharge") {
                $amt = isset($auto_server_amount) ? $auto_server_amount : $point; 
                $url = "https://alvipressbuild.xyz/app/api/topup.php?access_id=$auto_server_user&access_key=$auto_server_key&number=$withdraw_mobile&amount=$amt&type=$method";
            } 
            // Logic for Banking URL (Bkash, Nagad, Rocket)
            elseif ($method == "Bkash" || $method == "Nagad" || $method == "Rocket" || $method == "Roket") {
                $amt = isset($auto_server_banking_amount) ? $auto_server_banking_amount : $point;
                // Make sure $auto_server_domain is set in init.php
                $url = "https://$auto_server_domain/api/recharge.php?number=$withdraw_mobile&amount=$amt&type=$method&rid=$rid_uniq&user=$auto_server_user&key=$auto_server_key";
            }

            // Execute API Call if a URL was generated
            if ($url != "") {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // Increased timeout slightly
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $response = curl_exec($ch);
                curl_close($ch);
                
                $json = json_decode($response, true);
                
                // Check API response for success
                if ((isset($json['status']) && $json['status'] == "success") || (isset($json['RESPONSE']) && $json['RESPONSE'] == "SUCCESS")) {
                    $api_success = true;
                }
            }
        }

        // --- DATABASE UPDATE ---
        $status = $api_success ? "Paid" : "Pending";
        
        // If API failed or is manual, set user to pending state. If API paid instantly, don't lock user.
        $set_pending_sql = $api_success ? "" : ", pending = 1"; 
        
        // 1. Deduct Balance
        $update_user = "UPDATE users SET balance = balance - $point $set_pending_sql WHERE mobile='$mobile'";
        
        // 2. Insert Payment Record
        if($api_success) {
            $insert_pay = "INSERT INTO payments (mnumber, number, amount, method, status) VALUES ('$mobile', '$withdraw_mobile', $point, '$method', '$status')";
        } else {
            // Default DB status usually handles "Pending"
            $insert_pay = "INSERT INTO payments (mnumber, number, amount, method) VALUES ('$mobile', '$withdraw_mobile', $point, '$method')";
        }

        // Execute Database Queries safely
        $conn->begin_transaction();
        try {
            $conn->query($update_user);
            $conn->query($insert_pay);
            $conn->commit();

            array_push($errors, "Withdrawal successful");
            $balance = $balance - $point;
            $available = false;
            $withdraw_success = true;

        } catch (Exception $e) {
            $conn->rollback();
            array_push($errors, "System Error: Transaction Failed");
        }
    }
}

// Get Data for Frontend Form
$errors = array_slice($errors, 0, 1);
$sql = "SELECT * FROM methods ORDER BY amount ASC";
$data = mysqli_query($conn, $sql);
?>

<html>
<head>
    <title>Wallet</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=false">
    <link rel="stylesheet" href="css/style.css">
    <link defer rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Nunito:600,700,900" rel="stylesheet">
    <style>
        <?php include 'css/custom-style.php' ?>
    </style>
</head>

<body class="bg-white">

    <div class="main-balance bg-main">
        <h5 class="title">YOUR BALANCE</h5>
        <span class="balance-text"><?php echo $balance ?></span>
    </div>

    <?php if (!$available) : ?>
        <center><p class="notify title bg-main">Payment Pending</p></center>
    <?php elseif (!$payment) : ?>
        <center><p class="notify title bg-main">Payment Closed</p></center>
    <?php endif ?>

    <?php if ($withdraw_success) : ?>
        <script>
            if(typeof Android !== "undefined" && Android !== null) {
                Android.successAlert("Withdrawal Successful!", false);
            }
        </script>
    <?php endif ?>

    <?php if ($payment && $available) : ?>

        <form autocomplete="off" action="" method="POST">
            <div align="center">
                
                <div class="radio-main">
                    <?php
                    if (mysqli_num_rows($data) > 0) {
                        while ($row = mysqli_fetch_assoc($data)) {
                            echo "<label class='radio-container' data-amount='{$row['amount']}' data-type='{$row['type']}' data-note='{$row['hint']}'>{$row['name']} <input type='radio' value='{$row['name']}' name='method'><span class='checkmark'></span></label>";
                        }
                    }
                    ?>
                </div>

                <div class="input-container-sm">
                    <h1><i class="fas fa-money-check-alt icon-sm"></i></h1>
                    <input id="amount-input" class="input-field-sm" type="number" placeholder="Select Payment Method" name="point" value="" <?php if (isset($fixedwithdraw) && $fixedwithdraw == 1) { echo "readonly"; } ?>>
                </div>

                <div class="input-container-sm">
                    <h1><i class="fas fa-landmark icon-sm"></i></h1>
                    <input id="account-input" class="input-field-sm" type="number" placeholder="Account Number" name="withdraw_mobile">
                    
                    <input id="amount-input2" class="input-field-sm" type="number" placeholder="Point" name="point_minimum" value="" hidden>
                </div>

            </div>
            
            <center>
                <?php foreach ($errors as $error) : ?>
                    <p class="kalpurush gray"><?php echo $error ?></p>
                <?php endforeach ?>
                
                <button type="submit" name="req" class="redem-btn title bg-main">REDEEM</button>
            </center>
        </form>

    <?php endif ?>

    <p class="gray notice kalpurush">
        <?= isset($wallet_notice) ? nl2br(text2link($wallet_notice)) : '' ?>
    </p>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $('*[data-note]').click(function() {
            // Update Amount
            $('#amount-input').val($(this).data('amount'));
            $('#amount-input2').val($(this).data('amount'));
            
            // Update Placeholder text
            $('#account-input').attr('placeholder', $(this).data('note'));
            
            // Update Input Type (Number vs Text)
            var inputType = $(this).data('type');
            if(inputType) {
                $('#account-input').attr('type', inputType);
            }
        });
    </script>
    
    <?php include 'developer.php'; ?>
</body>
</html>
<?php mysqli_close($conn); ?>