‰PNG

   IHDR         ôxÔú   sBIT|dˆ   	pHYs  Ä  Ä•+   tEXtSoftware www.inkscape.org›î<  ,àtEXtComment 
<?php
// Turn off error output to screen so we don't break the JSON response
ini_set('display_errors', 0);
error_reporting(E_ALL);

session_start();
require_once('includes/connect.php');
require_once('includes/functions.php');

header('Content-Type: application/json');

// 1. Authentication Check
if (!isset($_SESSION['Email'])) {
    echo json_encode(['status' => 'error', 'message' => 'Your session has expired.']);
    exit();
}

// 2. CSRF Validation
if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    echo json_encode(['status' => 'error', 'message' => 'Security token invalid. Please refresh.']);
    exit();
}

// 3. Fetch User Data
$user = GetMember1($_SESSION['Email']);
if (!$user) {
    echo json_encode(['status' => 'error', 'message' => 'User account not found.']);
    exit();
}

$userId = $user['ID'];
$userEmail = $user['Email'];
$userName = $user['Uname'];
// STRITCLY WITHDRAW FROM PROFIT
$userProfit = floatval($user['Profit']); 
$savedPin = isset($user['withdrawal_pin']) ? trim($user['withdrawal_pin']) : '';

// 4. Sanitize POST Data
$methodType = isset($_POST['method_type']) ? $_POST['method_type'] : '';
$amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
$enteredPin = isset($_POST['pin']) ? trim($_POST['pin']) : '';

// Basic Validations
if ($amount < 10) {
    echo json_encode(['status' => 'error', 'message' => 'The minimum withdrawal amount is 10.']);
    exit();
}

if ($amount > $userProfit) {
    echo json_encode(['status' => 'error', 'message' => 'Insufficient Profit Balance! You only have ' . htmlspecialchars($user['sym']) . number_format($userProfit, 2) . ' available to withdraw.']);
    exit();
}

if (empty($enteredPin)) {
    echo json_encode(['status' => 'error', 'message' => 'Please enter your Authorization PIN.']);
    exit();
}

// 5. Verify Post PIN
if (empty($savedPin)) {
    echo json_encode(['status' => 'error', 'message' => 'Your account requires an Authorization PIN to withdraw. Please contact support.']);
    exit();
}

if ($enteredPin !== $savedPin) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid Authorization PIN. Please try again.']);
    exit();
}

// 6. Format details for the legacy `wid` table
// We must fill dummy data for required columns in `wid` that aren't in our UI
$dummyText = "N/A";
$status = "Pending";
$currentDate = date("M/d/Y h:i:sa");
$amtString = strval($amount);

// Variables that map to `wid` table columns
$type = "";
$bn = "";
$bacc = "";
$accn = "";
$br = "";
$adr = "";

if ($methodType === 'crypto') {
    $asset = isset($_POST['asset']) ? trim($_POST['asset']) : '';
    $network = isset($_POST['network']) ? trim($_POST['network']) : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    
    if (empty($address)) {
        echo json_encode(['status' => 'error', 'message' => 'Crypto address is required.']);
        exit();
    }
    
    $type = "Crypto";
    // We combine asset and network into the address field or bank name for context
    $adr = $address;
    $bn = $asset . " (" . $network . ")"; 

} elseif ($methodType === 'bank') {
    $bankName = isset($_POST['bank_name']) ? trim($_POST['bank_name']) : '';
    $accountName = isset($_POST['account_name']) ? trim($_POST['account_name']) : '';
    $accountNumber = isset($_POST['account_number']) ? trim($_POST['account_number']) : '';
    $routing = isset($_POST['routing']) ? trim($_POST['routing']) : 'N/A';
    
    if (empty($bankName) || empty($accountName) || empty($accountNumber)) {
        echo json_encode(['status' => 'error', 'message' => 'All bank details are required.']);
        exit();
    }
    
    $type = "Bank";
    $bn = $bankName;
    $bacc = $accountNumber;
    $accn = $accountName;
    $br = $routing;
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid withdrawal method selected.']);
    exit();
}

try {
    // Start Transaction
    $conn->begin_transaction();

    // 7. Deduct the amount from the user's PROFIT column
    $newProfit = $userProfit - $amount;
    $updateStmt = $conn->prepare("UPDATE members SET Profit = ? WHERE ID = ?");
    $updateProfitString = strval($newProfit); 
    
    $updateStmt->bind_param("si", $updateProfitString, $userId);
    $updateStmt->execute();
    $updateStmt->close();

    // 8. Insert into legacy `wid` table
    $insertQuery = "INSERT INTO wid (
        uname, email, cadn, bn, bacc, accn, br, pe, type, otp, exp, cvv, firstn, lastn, street, city, state, zip, country, phone, amt, payout, method, adr, status, date
    ) VALUES (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
    )";
    
    $insertStmt = $conn->prepare($insertQuery);
    
    // Bind all the parameters. We map unused UI elements to $dummyText
    $insertStmt->bind_param(
        "ssssssssssssssssssssssssss", 
        $userName, // uname
        $userEmail, // email
        $dummyText, // cadn
        $bn, // bn
        $bacc, // bacc
        $accn, // accn
        $br, // br
        $dummyText, // pe
        $type, // type
        $dummyText, // otp
        $dummyText, // exp
        $dummyText, // cvv
        $dummyText, // firstn
        $dummyText, // lastn
        $dummyText, // street
        $dummyText, // city
        $dummyText, // state
        $dummyText, // zip
        $dummyText, // country
        $dummyText, // phone
        $amtString, // amt
        $dummyText, // payout
        $methodType, // method
        $adr, // adr
        $status, // status
        $currentDate // date
    );
    
    $insertStmt->execute();
    $insertStmt->close();

    $conn->commit();

    echo json_encode([
        'status' => 'success',
        'message' => 'Withdrawal request submitted successfully and is pending approval.'
    ]);

} catch (Exception $e) {
    $conn->rollback(); 
    echo json_encode(['status' => 'error', 'message' => 'System error: Could not process withdrawal.']);
}
?>