<?php
session_start();
require_once "../include/db.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = $_SESSION['user_id'];
    $pin = $_POST['withdrawal_pin'];
    $auth = $_POST['admin_auth_code'];
    $amount = floatval($_POST['amount']);

    // Fetch user security data
    $userQuery = mysqli_query($conn, "SELECT balance, transaction_pin, withdrawal_auth FROM users WHERE id = $userId");
    $user = mysqli_fetch_assoc($userQuery);

    // Final Database Verification
    if ($pin !== $user['transaction_pin']) {
        $_SESSION['error'] = "Critical Security Failure: Incorrect PIN.";
        header("Location: ../withdrawals.php");
        exit;
    }

    if ($auth !== $user['withdrawal_auth']) {
        $_SESSION['error'] = "Authorization Rejected: Invalid Admin Code.";
        header("Location: ../withdrawals.php");
        exit;
    }

    if ($user['balance'] < $amount) {
        $_SESSION['error'] = "Insufficient Liquidity: Withdrawal denied.";
        header("Location: ../withdrawals.php");
        exit;
    }

    // Success - Execute Transaction
    mysqli_begin_transaction($conn);
    try {
        mysqli_query($conn, "UPDATE users SET balance = balance - $amount, withdrawal_auth = NULL WHERE id = $userId");
        
        $ref = "WIT-" . strtoupper(bin2hex(random_bytes(3)));
        mysqli_query($conn, "INSERT INTO transactions (user_id, type, amount, status, ref, created_at) VALUES ($userId, 'withdrawal', $amount, 'pending', '$ref', NOW())");
        
        mysqli_commit($conn);
        $_SESSION['success'] = "Payout #$ref has been queued for dispatch.";
        header("Location: ../withdrawals.php");
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $_SESSION['error'] = "Internal Server Error. Please contact Admin.";
        header("Location: ../withdrawals.php");
    }
}