<?php
// Secure withdrawal processor
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_secure', 1); // Enable if HTTPS
session_start();
session_regenerate_id(true);

// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");

require_once 'connection.php';

// CSRF protection
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== ($_SESSION['csrf_token_withdraw'] ?? '')) {
    $_SESSION['withdraw_error'] = "Security validation failed.";
    header("Location: ../withdraw.php");
    exit();
}

// Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../../login.php");
    exit();
}

$user_id = intval($_SESSION['user_id']);

// Rate limiting: allow max 3 withdrawal requests per hour
$ip = $_SERVER['REMOTE_ADDR'];
$rate_key = "rate_withdraw_" . $ip;
$current_time = time();
if (isset($_SESSION[$rate_key]) && ($current_time - $_SESSION[$rate_key]['time']) < 3600) {
    if ($_SESSION[$rate_key]['count'] >= 3) {
        $_SESSION['withdraw_error'] = "Too many withdrawal attempts. Please try again later.";
        header("Location: ../withdraw.php");
        exit();
    }
    $_SESSION[$rate_key]['count']++;
} else {
    $_SESSION[$rate_key] = ['count' => 1, 'time' => $current_time];
}

// Validate required fields
if (!isset($_POST['withdrawl_request'], $_POST['amount']) || $_POST['withdrawl_request'] != '1') {
    $_SESSION['withdraw_error'] = "Invalid request.";
    header("Location: ../withdraw.php");
    exit();
}

$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
if ($amount === false || $amount <= 0) {
    $_SESSION['withdraw_error'] = "Invalid amount.";
    header("Location: ../withdraw.php");
    exit();
}

// Minimum withdrawal check
if ($amount < 100) {
    $_SESSION['withdraw_error'] = "Minimum withdrawal amount is ₹100.";
    header("Location: ../withdraw.php");
    exit();
}

// Fetch user data with prepared statement
$stmt = $conn->prepare("SELECT c1_achieved_at, wallet FROM users WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$user) {
    $_SESSION['withdraw_error'] = "User not found.";
    header("Location: ../withdraw.php");
    exit();
}

// Check Level 1 eligibility
if (empty($user['c1_achieved_at'])) {
    $_SESSION['withdraw_error'] = "You need to achieve Level 1 (have 4 direct referrals) before you can withdraw.";
    header("Location: ../withdraw.php");
    exit();
}

// Check balance (even though we don't deduct yet)
if ($amount > $user['wallet']) {
    $_SESSION['withdraw_error'] = "Insufficient balance.";
    header("Location: ../withdraw.php");
    exit();
}

// Begin transaction
mysqli_begin_transaction($conn);
try {
    // Get next ID
    $result = $conn->query("SELECT MAX(id) as max_id FROM witdrawl");
    $row = $result->fetch_assoc();
    $new_id = intval($row['max_id']) + 1;

    // Insert withdrawal request
    $stmt = $conn->prepare("INSERT INTO witdrawl (id, user_id, amt, request_date, status) VALUES (?, ?, ?, NOW(), 0)");
    $stmt->bind_param("iid", $new_id, $user_id, $amount);
    if (!$stmt->execute()) {
        throw new Exception("Database error: " . $stmt->error);
    }
    $stmt->close();

    

    mysqli_commit($conn);

    // Audit log
    error_log("Withdrawal request: User $user_id, Amount $amount, IP $ip");

    $_SESSION['withdraw_success'] = "Withdrawal request of ₹$amount submitted successfully!";
} catch (Exception $e) {
    mysqli_rollback($conn);
    error_log("Withdrawal error for user $user_id: " . $e->getMessage());
    $_SESSION['withdraw_error'] = "An error occurred. Please try again later.";
}

header("Location: ../withdraw.php");
exit();
?>