<?php
session_start();
require_once 'connection.php';

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    $_SESSION['withdraw_error'] = "Please login to continue.";
    header("Location: ../login.php");
    exit();
}

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

// Validate CSRF token
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token_withdraw']) {
    $_SESSION['withdraw_error'] = "Invalid security token. Please try again.";
    header("Location: ../withdraw.php");
    exit();
}

// Check if form was submitted
if (!isset($_POST['withdrawl_request']) || $_POST['withdrawl_request'] != 1) {
    $_SESSION['withdraw_error'] = "Invalid request.";
    header("Location: ../withdraw.php");
    exit();
}

// Get and validate amount
$amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;

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

if ($amount % 100 != 0) {
    $_SESSION['withdraw_error'] = "Withdrawal amount must be in multiples of ₹100.";
    header("Location: ../withdraw.php");
    exit();
}

// Start transaction
mysqli_begin_transaction($conn);

try {
    // Check user's current wallet balance
    $stmt = $conn->prepare("SELECT wallet, name FROM users WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();

    if (!$user) {
        throw new Exception("User not found.");
    }

    $wallet_balance = floatval($user['wallet']);

    // CRITICAL: Check if user has sufficient balance
    if ($wallet_balance < $amount) {
        throw new Exception("Insufficient balance. Your current wallet balance is ₹" . number_format($wallet_balance, 2));
    }

    // Check if user has complete profile (PAN, Aadhaar, Bank details)
    // Get PAN and Aadhaar
    $stmt = $conn->prepare("SELECT panno, aadharno FROM users WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user_docs = $result->fetch_assoc();
    $stmt->close();

    if (empty($user_docs['panno']) || empty($user_docs['aadharno'])) {
        throw new Exception("Please complete your KYC (PAN and Aadhaar) before withdrawing.");
    }

    // Check bank details
    $stmt = $conn->prepare("SELECT id FROM bank_details WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $bank = $result->fetch_assoc();
    $stmt->close();

    if (!$bank) {
        throw new Exception("Please add your bank details before withdrawing.");
    }

    // Check for existing pending withdrawal
    $stmt = $conn->prepare("SELECT id FROM witdrawl WHERE user_id = ? AND status = 0");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $pending = $result->fetch_assoc();
    $stmt->close();

    if ($pending) {
        throw new Exception("You already have a pending withdrawal request. Please wait for it to be processed.");
    }

    // Calculate deductions
    $tds_percentage = 5;
    $admin_percentage = 10;
    $tds_amount = $amount * $tds_percentage / 100;
    $admin_amount = $amount * $admin_percentage / 100;
    $net_amount = $amount - $tds_amount - $admin_amount;

    // Insert withdrawal request
    $request_date = date('Y-m-d');
    $status = 0; // Pending
    
    $stmt = $conn->prepare("INSERT INTO witdrawl (user_id, amt, status, request_date, left_count, right_count, net_amount) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $left_count = 0; // You might want to fetch these from user data
    $right_count = 0;
    $stmt->bind_param("idisidd", $user_id, $amount, $status, $request_date, $left_count, $right_count, $net_amount);
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to create withdrawal request: " . $stmt->error);
    }
    $withdrawal_id = $stmt->insert_id;
    $stmt->close();

    // Create income history entry (as debit)
    $description = "Withdrawal request of ₹" . number_format($amount, 2) . " (Net: ₹" . number_format($net_amount, 2) . ")";
    $transaction_id = 'WDR' . time() . rand(100, 999);
    $credit_debit = 0; // Debit
    $income_type = 'withdrawal';
    
    $stmt = $conn->prepare("INSERT INTO income_history (user_id, amount, description, credit_debit, income_type, transaction_id, created_at, from_user_id, to_user_id) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?)");
    $from_user_id = $user_id;
    $to_user_id = 0; // System
    $stmt->bind_param("idsissii", $user_id, $amount, $description, $credit_debit, $income_type, $transaction_id, $from_user_id, $to_user_id);
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to log income history: " . $stmt->error);
    }
    $stmt->close();

    // NOTE: We do NOT deduct the amount from wallet here
    // Amount will be deducted only when admin approves the withdrawal
    // This prevents double deduction if approval fails

    mysqli_commit($conn);
    
    $_SESSION['withdraw_success'] = "Withdrawal request of ₹" . number_format($amount, 2) . " submitted successfully! It will be processed within 24-48 hours.";
    header("Location: ../withdraw.php");
    exit();

} catch (Exception $e) {
    mysqli_rollback($conn);
    $_SESSION['withdraw_error'] = $e->getMessage();
    header("Location: ../withdraw.php");
    exit();
}
?>