<?php
ob_start();
include 'include/header.php';
require_once '../config/conn.php';

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

$student_id = $_SESSION['user_id'];

// Check if user has set transaction PIN
$pin_stmt = $conn->prepare("SELECT * FROM wallet_pins WHERE student_id = ?");
$pin_stmt->bind_param("i", $student_id);
$pin_stmt->execute();
$has_pin = $pin_stmt->get_result()->num_rows > 0;

if (!$has_pin) {
    header("Location: pin.php");
    exit();
}

// Get wallet info
$wallet_stmt = $conn->prepare("SELECT id, wallet_id, balance FROM student_wallets WHERE student_id = ?");
$wallet_stmt->bind_param("i", $student_id);
$wallet_stmt->execute();
$wallet_result = $wallet_stmt->get_result();
$wallet = $wallet_result->fetch_assoc();

// Get linked bank accounts
$accounts_stmt = $conn->prepare("
    SELECT * FROM student_bank_accounts
    WHERE student_id = ?
    ORDER BY is_primary DESC, created_at DESC
");
$accounts_stmt->bind_param("i", $student_id);
$accounts_stmt->execute();
$accounts_result = $accounts_stmt->get_result();
$bank_accounts = $accounts_result->fetch_all(MYSQLI_ASSOC);
?>

<div class="max-w-md mx-auto " style="margin-top:20px; margin-bottom: 80px;">
    <div class="text-center mb-6">
        <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-3">
            <svg class="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"></path>
            </svg>
        </div>
        <h2 class="text-2xl font-bold">Withdraw Funds</h2>
        <p class="text-gray-500 mt-2">Transfer money to your bank account</p>
    </div>

    <form id="withdrawForm" class="space-y-4">
        <input type="hidden" name="student_id" value="<?= $student_id ?>">
        <input type="hidden" name="wallet_id" value="<?= $wallet['id'] ?>">
        
        <div>
            <label class="block text-gray-700 mb-1">Amount (₦)</label>
            <div class="relative">
                <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500">₦</span>
                <input type="number" name="amount" min="100" step="100" max="<?= $wallet['balance'] ?>" 
                       class="w-full pl-8 pr-3 py-2 border rounded-lg" 
                       placeholder="0.00" required>
            </div>
            <p class="text-xs text-gray-500 mt-1">
                Available: ₦<?= number_format($wallet['balance'], 2) ?> • Minimum: ₦100
            </p>
        </div>
        
        <div>
            <label class="block text-gray-700 mb-1">To Bank Account</label>
            <select name="bank_account_id" class="w-full px-3 py-2 border rounded-lg" required>
                <?php if (empty($bank_accounts)): ?>
                    <option value="">No bank accounts - please add one first</option>
                <?php else: ?>
                    <?php foreach ($bank_accounts as $account): ?>
                        <option value="<?= $account['id'] ?>" <?= $account['is_primary'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($account['bank_name']) ?> (****<?= substr($account['account_number'], -4) ?>)
                        </option>
                    <?php endforeach; ?>
                <?php endif; ?>
            </select>
            <?php if (empty($bank_accounts)): ?>
                <p class="text-sm text-red-500 mt-1">You need to add a bank account first</p>
            <?php endif; ?>
        </div>
        
        <div>
            <label class="block text-gray-700 mb-1">Transaction PIN</label>
            <input type="password" name="transaction_pin" maxlength="4" inputmode="numeric" pattern="\d{4}"
                   class="w-full px-3 py-2 border rounded-lg" placeholder="Enter 4-digit PIN" required>
        </div>
        
        <div class="pt-2">
            <button type="submit" id="withdrawSubmit" 
                    class="w-full bg-primary-500 text-white py-2 px-4 rounded-lg hover:bg-primary-600 transition"
                    <?= empty($bank_accounts) ? 'disabled' : '' ?>>
                Request Withdrawal
            </button>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const withdrawForm = document.getElementById('withdrawForm');
    
    withdrawForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const amount = parseFloat(this.amount.value);
        const balance = parseFloat(<?= $wallet['balance'] ?>);
        
        if (isNaN(amount)) {
            alert('Please enter a valid amount');
            return;
        }
        
        if (amount < 100) {
            alert('Minimum withdrawal amount is ₦100');
            return;
        }
        
        if (amount > balance) {
            alert('Insufficient balance');
            return;
        }
        
        if (this.transaction_pin.value.length !== 4 || !/^\d+$/.test(this.transaction_pin.value)) {
            alert('PIN must be exactly 4 digits');
            return;
        }
        
        // Submit via AJAX
        fetch('process_withdrawal.php', {
            method: 'POST',
            body: new FormData(withdrawForm)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Withdrawal request submitted successfully!');
                window.location.href = 'wallet.php';
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred');
        });
    });
});
</script>

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