<?php
include 'include/header.php';

if (!isset($_SESSION['vendor_id']) || empty($_SESSION['vendor_id'])) {
    header("Location: vendor-login.php");
    exit();
}
$vendor_id = $_SESSION['vendor_id'];

// Get wallet balance
$wallet = ['balance' => 0, 'pending_balance' => 0];
$stmt = $conn->prepare("SELECT balance, pending_balance FROM vendor_wallets WHERE vendor_id = ?");
$stmt->bind_param("s", $vendor_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    $wallet = $result->fetch_assoc();
}

// Get verified bank accounts
$bank_accounts = [];
$stmt = $conn->prepare("SELECT * FROM vendor_bank_accounts WHERE vendor_id = ? AND is_verified = 1");
$stmt->bind_param("s", $vendor_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $bank_accounts[] = $row;
}

// Handle withdrawal request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bank_account_id = $_POST['bank_account'];
    $amount = floatval($_POST['amount']);
    $pin = $_POST['pin'];
    
    // Validate
    if ($amount < 10) {
        $error = "Minimum withdrawal amount is $10";
    } elseif ($amount > $wallet['balance']) {
        $error = "Insufficient balance";
    } else {
        // Verify PIN
        $stmt = $conn->prepare("SELECT withdrawal_pin FROM vendors WHERE id = ?");
        $stmt->bind_param("s", $vendor_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $vendor = $result->fetch_assoc();
        
        if (!password_verify($pin, $vendor['withdrawal_pin'])) {
            $error = "Invalid withdrawal PIN";
        } else {
            // Start transaction
            $conn->begin_transaction();
            
            try {
                // Create withdrawal request
                $reference = 'WDR' . strtoupper(uniqid());
                $stmt = $conn->prepare("INSERT INTO withdrawal_requests 
                                      (vendor_id, bank_account_id, amount, status, transaction_reference, withdrawal_pin_used) 
                                      VALUES (?, ?, ?, 'pending', ?, ?)");
                $stmt->bind_param("ssdss", $vendor_id, $bank_account_id, $amount, $reference, $pin);
                $stmt->execute();
                $request_id = $conn->insert_id;
                
                // Deduct from wallet
                $new_balance = $wallet['balance'] - $amount;
                $stmt = $conn->prepare("UPDATE vendor_wallets SET balance = ? WHERE vendor_id = ?");
                $stmt->bind_param("ds", $new_balance, $vendor_id);
                $stmt->execute();
                
                // Record transaction
                $stmt = $conn->prepare("INSERT INTO vendor_wallet_transactions 
                                      (vendor_id, amount, transaction_type, reference, status, balance_before, balance_after, notes) 
                                      VALUES (?, ?, 'debit', ?, 'pending', ?, ?, 'Withdrawal request')");
                $stmt->bind_param("sdssd", $vendor_id, $amount, $reference, $wallet['balance'], $new_balance);
                $stmt->execute();
                
                $conn->commit();
                $success = "Withdrawal request submitted successfully!";
            } catch (Exception $e) {
                $conn->rollback();
                $error = "Error processing withdrawal: " . $e->getMessage();
            }
        }
    }
}
?>

<div class="container mx-auto px-4 py-8 max-w-md">
    <h1 class="text-2xl font-bold mb-6">Withdraw Funds</h1>
    
    <?php if (isset($success)): ?>
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
            <?= $success ?>
        </div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            <?= $error ?>
        </div>
    <?php endif; ?>

    <?php if (empty($bank_accounts)): ?>
        <div class="bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded mb-4">
            You need at least one verified bank account to withdraw funds. 
            <a href="bank_accounts.php" class="font-bold underline">Add Bank Account</a>
        </div>
    <?php else: ?>
        <div class="bg-white rounded-lg shadow p-6">
            <form method="POST">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Bank Account</label>
                    <select name="bank_account" class="w-full px-3 py-2 border rounded-md" required>
                        <?php foreach ($bank_accounts as $account): ?>
                        <option value="<?= $account['id'] ?>">
                            <?= htmlspecialchars($account['bank_name']) ?> - ••••<?= substr($account['account_number'], -4) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Amount</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3">$</span>
                        <input type="number" name="amount" min="10" max="<?= $wallet['balance'] ?>" step="0.01" 
                               class="pl-8 w-full px-3 py-2 border rounded-md" required>
                    </div>
                    <p class="text-sm text-gray-500 mt-1">Available: $<?= number_format($wallet['balance'], 2) ?></p>
                </div>
                
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Withdrawal PIN</label>
                    <input type="password" name="pin" maxlength="6" pattern="\d{6}" 
                           class="w-full px-3 py-2 border rounded-md" required>
                    <p class="text-sm text-gray-500 mt-1">
                        <a href="wallet_pin.php" class="text-primary-500">Forgot PIN?</a>
                    </p>
                </div>
                
                <button type="submit" class="w-full bg-primary-500 text-white py-2 rounded-md">
                    Submit Withdrawal
                </button>
            </form>
        </div>
    <?php endif; ?>
</div>

<?php include 'include/footer.php'; ?>