<?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'];

// 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 student info for email
$student_stmt = $conn->prepare("SELECT email, full_name, phone FROM students WHERE id = ?");
$student_stmt->bind_param("i", $student_id);
$student_stmt->execute();
$student_result = $student_stmt->get_result();
$student = $student_result->fetch_assoc();

// Get bank account if exists
$bank_stmt = $conn->prepare("SELECT * FROM student_bank_accounts WHERE student_id = ?");
$bank_stmt->bind_param("i", $student_id);
$bank_stmt->execute();
$bank_result = $bank_stmt->get_result();
$bank_account = $bank_result->fetch_assoc();
?>

<div class="max-w-md mx-auto mt-4 p-6" style="margin-top:30px">
    <div class="text-center mb-6">
        <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-3">
            <svg class="w-8 h-8 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
        </div>
        <h2 class="text-1xl font-bold">Deposit Funds</h2>
        <p class="text-gray-500 mt-2">Add money to your wallet</p>
    </div>

    <form id="depositForm" class="space-y-4">
        <input type="hidden" name="student_id" value="<?= $student_id ?>">
        <input type="hidden" name="wallet_id" value="<?= $wallet['id'] ?>">
        <input type="hidden" name="wallet_id_display" value="<?= $wallet['wallet_id'] ?>">
        <input type="hidden" name="email" value="<?= $student['email'] ?>">
        <input type="hidden" name="fullname" value="<?= $student['full_name'] ?>">
        <input type="hidden" name="phone" value="<?= $student['phone'] ?>">
        
        <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" 
                       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">Minimum deposit: ₦100</p>
        </div>
        
        <div>
            <label class="block text-gray-700 mb-1">Payment Method</label>
            <div class="grid grid-cols-2 gap-3">
                <button type="button" onclick="selectPaymentMethod('paystack')" 
                        class="payment-method p-3 border rounded-lg flex flex-col items-center justify-center hover:border-primary-500">
                    <img src="assets/images/paystack.png" alt="Paystack" class="h-6 mb-1">
                    <span class="text-xs mt-1">Paystack</span>
                </button>
                <button type="button" onclick="selectPaymentMethod('bank_transfer')" 
                        class="payment-method p-3 border rounded-lg flex flex-col items-center justify-center hover:border-primary-500">
                    <svg class="w-6 h-6 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 14v3m4-3v3m4-3v3M3 21h18M3 10h18M3 7l9-4 9 4M4 10h16v11H4V10z"></path>
                    </svg>
                    <span class="text-xs mt-1">Bank Transfer</span>
                </button>
            </div>
            <input type="hidden" name="payment_method" id="paymentMethod" required>
        </div>
        
        <!-- Bank Transfer Details (hidden by default) -->
        <div id="bankTransferDetails" class="hidden space-y-4">
            <div class="p-4 bg-blue-50 border-l-4 border-blue-400 rounded">
                <p class="text-sm text-blue-700">
                    <i class="fas fa-info-circle mr-1"></i> Transfer funds to our bank account below.
                </p>
            </div>
            
            <div class="p-4 border rounded-lg bg-gray-50">
                <div class="mb-3">
                    <label class="block text-gray-500 text-sm mb-1">Bank Name</label>
                    <p class="font-medium">Zenith Bank</p>
                </div>
                <div class="mb-3">
                    <label class="block text-gray-500 text-sm mb-1">Account Name</label>
                    <p class="font-medium">EduFund Solutions</p>
                </div>
                <div class="mb-3">
                    <label class="block text-gray-500 text-sm mb-1">Account Number</label>
                    <p class="font-medium">1012345678</p>
                </div>
                <div>
                    <label class="block text-gray-500 text-sm mb-1">Reference/Note</label>
                    <p class="font-mono bg-gray-100 p-2 rounded">WAL<?= $wallet['wallet_id'] ?></p>
                </div>
            </div>
            
            <div class="p-4 bg-yellow-50 border-l-4 border-yellow-400 rounded">
                <p class="text-sm text-yellow-700">
                    <i class="fas fa-exclamation-triangle mr-1"></i> 
                    After making the transfer, please upload your payment proof below for verification.
                </p>
            </div>
            
            <div>
                <label class="block text-gray-700 mb-1">Upload Payment Proof</label>
                <input type="file" name="payment_proof" class="w-full p-2 border rounded-lg">
                <p class="text-xs text-gray-500 mt-1">Upload a screenshot or scan of your transfer receipt</p>
            </div>
        </div>
        
        <div class="pt-2">
            <button type="submit" id="depositSubmit" 
                    class="w-full bg-primary-500 text-white py-2 px-4 rounded-lg hover:bg-primary-600 transition">
                Proceed to Payment
            </button>
        </div>
    </form>
</div>

<!-- Processing Payment Modal -->
<div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden" id="processingModal">
    <div class="bg-white p-6 rounded-lg w-full max-w-md text-center">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-500 mx-auto mb-4"></div>
        <h3 class="text-xl font-bold mb-2">Processing Payment</h3>
        <p class="text-gray-600">Please wait while we process your transaction...</p>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const depositForm = document.getElementById('depositForm');
    let paymentData = null;
    
    window.selectPaymentMethod = function(method) {
        document.getElementById('paymentMethod').value = method;
        // Highlight selected method
        document.querySelectorAll('.payment-method').forEach(btn => {
            btn.classList.remove('border-primary-500', 'bg-primary-50');
        });
        event.currentTarget.classList.add('border-primary-500', 'bg-primary-50');
        
        // Show/hide Bank Transfer details
        if (method === 'bank_transfer') {
            document.getElementById('bankTransferDetails').classList.remove('hidden');
        } else {
            document.getElementById('bankTransferDetails').classList.add('hidden');
        }
    };
    
    depositForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const amount = parseFloat(this.amount.value);
        const paymentMethod = this.payment_method.value;
        
        if (isNaN(amount)) {
            alert('Please enter a valid amount');
            return;
        }
        
        if (amount < 100) {
            alert('Minimum deposit amount is ₦100');
            return;
        }
        
        if (!paymentMethod) {
            alert('Please select a payment method');
            return;
        }
        
        // Show processing modal
        document.getElementById('processingModal').classList.remove('hidden');
        
        // Prepare payment data
        paymentData = {
            amount: amount * 100, // Convert to kobo
            email: this.email.value,
            fullname: this.fullname.value,
            phone: this.phone.value,
            wallet_id: this.wallet_id_display.value,
            student_id: this.student_id.value,
            wallet_db_id: this.wallet_id.value,
            purpose: 'wallet_funding'
        };
        
        // Initiate payment based on selected method
        if (paymentMethod === 'paystack') {
            initiatePaystackPayment(paymentData);
        } else if (paymentMethod === 'bank_transfer') {
            handleBankTransfer(paymentData);
        }
    });
    
    // Handle Bank Transfer submission
    function handleBankTransfer(paymentData) {
        const paymentProof = document.querySelector('input[name="payment_proof"]').files[0];
        
        if (!paymentProof) {
            document.getElementById('processingModal').classList.add('hidden');
            alert('Please upload your payment proof');
            return;
        }
        
        // In a real implementation, you would upload the file and save the transaction
        // For now, we'll simulate a successful submission
        
        setTimeout(() => {
            document.getElementById('processingModal').classList.add('hidden');
            alert('Bank transfer details submitted successfully. Your wallet will be credited once we verify your payment.');
            window.location.href = 'wallet.php';
        }, 2000);
    }
    
    // Paystack payment integration
    function initiatePaystackPayment(paymentData) {
        const handler = PaystackPop.setup({
            key: 'pk_test_b47847d06c11275c802c304d0e9568b02a8c7391', // CHANGE TO YOUR PUBLIC KEY
            email: paymentData.email,
            amount: paymentData.amount,
            currency: 'NGN',
            ref: 'WAL' + Math.floor(Math.random() * 1000000000 + 1),
            metadata: {
                student_id: paymentData.student_id,
                wallet_id: paymentData.wallet_db_id,
                purpose: paymentData.purpose
            },
            callback: function(response) {
                document.getElementById('processingModal').classList.remove('hidden');
                verifyPayment(response.reference, 'paystack');
            },
            onClose: function() {
                document.getElementById('processingModal').classList.add('hidden');
                alert('Transaction was not completed');
            }
        });
        handler.openIframe();
    }
    
    // Verify payment after completion
    function verifyPayment(reference, gateway) {
        fetch('verify_payment.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                reference: reference,
                gateway: gateway
            })
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('processingModal').classList.add('hidden');
            
            if (data.success) {
                alert('Payment successful! Your wallet has been credited with ₦' + (data.amount / 100).toFixed(2));
                window.location.href = 'wallet.php';
            } else {
                alert('Payment verification failed: ' + data.message);
            }
        })
        .catch(error => {
            document.getElementById('processingModal').classList.add('hidden');
            console.error('Error:', error);
            alert('An error occurred while verifying payment');
        });
    }
});
</script>

<!-- Include Paystack script -->
<script src="https://js.paystack.co/v1/inline.js"></script>

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