<?php
session_start();
include 'db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
if (isset($_POST['withdraw'])) {
    $amount = floatval($_POST['amount']);

    $check = $conn->query("SELECT balance FROM users WHERE id=$user_id");
    $user = $check->fetch_assoc();

    if ($amount > 0 && $user['balance'] >= $amount) {
        $conn->query("UPDATE users SET balance = balance - $amount WHERE id = $user_id");
        $conn->query("INSERT INTO withdrawals (user_id, amount) VALUES ($user_id, $amount)");
        echo "Withdrawal request sent for admin approval.";
    } else {
        echo "Invalid amount or insufficient balance.";
    }
}
?>

<form method="POST">
    <input type="number" step="0.001" name="amount" required placeholder="Amount to withdraw"><br>
    <button type="submit" name="withdraw">Request Withdrawal</button>
</form>
