@extends('layouts.app')

@section('title', 'Transfer Funds - ' . config('app.name'))

@section('content')
<div class="container mx-auto px-4 py-8">
    <div class="max-w-4xl mx-auto">
        <!-- Page Header -->
        <div class="mb-8">
            <div class="flex items-center mb-4">
                <a href="{{ route('wallet.index') }}" class="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 mr-3">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                </a>
                <h1 class="text-3xl font-bold text-gray-900 dark:text-white">Transfer Funds</h1>
            </div>
            <p class="text-gray-600 dark:text-gray-400">Send money to other users securely</p>
        </div>

        <!-- Current Balance -->
        <div class="bg-white dark:bg-gray-800 rounded-lg p-6 mb-8 shadow-sm border border-gray-200 dark:border-gray-700">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Available Balance</h2>
                    <div class="text-3xl font-bold text-blue-600 dark:text-blue-400">${{ number_format($balance, 2) }}</div>
                </div>
                <div class="bg-blue-100 dark:bg-blue-900 rounded-full p-3">
                    <svg class="w-8 h-8 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
                    </svg>
                </div>
            </div>
        </div>

        @if($user->level == 1)
            <!-- Upgrade Required Warning -->
            <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-8">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <svg class="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-yellow-800 dark:text-yellow-200">Upgrade Required</h3>
                        <div class="mt-2 text-sm text-yellow-700 dark:text-yellow-300">
                            <p>You need to upgrade your account to Premium to transfer funds to other users.</p>
                            <a href="#" class="text-yellow-800 dark:text-yellow-200 underline hover:no-underline">Upgrade Now</a>
                        </div>
                    </div>
                </div>
            </div>
        @else
            <!-- Transfer Form -->
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
                <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Transfer Details</h3>
                </div>
                
                <form action="{{ route('processTransfer') }}" method="POST" class="p-6">
                    @csrf
                    
                    <!-- Recipient Selection -->
                    <div class="mb-6">
                        <label for="recipient_search" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Recipient</label>
                        <div class="relative">
                            <input type="text" id="recipient_search" 
                                   class="block w-full px-3 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white" 
                                   placeholder="Search by name, email, or username..." autocomplete="off">
                            <div id="search_results" class="absolute z-10 w-full mt-1 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg shadow-lg hidden max-h-60 overflow-y-auto"></div>
                        </div>
                        <input type="hidden" id="to_user_id" name="to_user_id" required>
                        <div id="selected_recipient" class="mt-2 hidden">
                            <div class="flex items-center p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                                <img id="recipient_avatar" src="" alt="" class="w-8 h-8 rounded-full mr-3">
                                <div>
                                    <p id="recipient_name" class="font-medium text-gray-900 dark:text-white"></p>
                                    <p id="recipient_email" class="text-sm text-gray-600 dark:text-gray-400"></p>
                                </div>
                                <button type="button" id="remove_recipient" class="ml-auto text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                        @error('to_user_id')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Amount Input -->
                    <div class="mb-6">
                        <label for="amount" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Transfer Amount</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <span class="text-gray-500 dark:text-gray-400 sm:text-sm">$</span>
                            </div>
                            <input type="number" id="amount" name="amount" min="0.01" max="{{ $balance }}" step="0.01" 
                                   class="block w-full pl-7 pr-12 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white" 
                                   placeholder="0.00" required>
                            <div class="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
                                <span class="text-gray-500 dark:text-gray-400 sm:text-sm">USD</span>
                            </div>
                        </div>
                        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
                            Max: ${{ number_format($balance, 2) }}
                        </p>
                        @error('amount')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Password Confirmation -->
                    <div class="mb-6">
                        <label for="password" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Confirm Password</label>
                        <input type="password" id="password" name="password" 
                               class="block w-full px-3 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white" 
                               placeholder="Enter your password" required>
                        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">Enter your password to confirm the transfer</p>
                        @error('password')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Submit Button -->
                    <div class="flex items-center justify-between">
                        <a href="{{ route('wallet.index') }}" class="text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200">
                            Cancel
                        </a>
                        <button type="submit" id="transfer-btn"
                                class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-6 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
                            Transfer Funds
                        </button>
                    </div>
                </form>
            </div>

            <!-- Transfer Information -->
            <div class="mt-8 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <svg class="h-5 w-5 text-blue-400" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-blue-800 dark:text-blue-200">Transfer Information</h3>
                        <div class="mt-2 text-sm text-blue-700 dark:text-blue-300">
                            <ul class="list-disc list-inside space-y-1">
                                <li>Transfers are instant and cannot be reversed</li>
                                <li>No fees are charged for transfers</li>
                                <li>Recipient will receive the full amount</li>
                                <li>You will receive a confirmation email</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        @endif

        <!-- Recent Transfers -->
        <div class="mt-8">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Recent Transfers</h3>
                <a href="{{ route('wallet.index') }}" class="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 text-sm font-medium">View All</a>
            </div>
            
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
                <div class="p-6 text-center text-gray-500 dark:text-gray-400">
                    <svg class="w-12 h-12 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
                    </svg>
                    <p>No transfer history yet</p>
                    <p class="text-sm mt-1">Your transfers will appear here</p>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('recipient_search');
    const searchResults = document.getElementById('search_results');
    const selectedRecipient = document.getElementById('selected_recipient');
    const toUserIdInput = document.getElementById('to_user_id');
    const recipientAvatar = document.getElementById('recipient_avatar');
    const recipientName = document.getElementById('recipient_name');
    const recipientEmail = document.getElementById('recipient_email');
    const removeRecipientBtn = document.getElementById('remove_recipient');
    const transferBtn = document.getElementById('transfer-btn');

    let searchTimeout;

    // Search for users
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        const query = this.value.trim();
        
        if (query.length < 2) {
            searchResults.classList.add('hidden');
            return;
        }

        searchTimeout = setTimeout(() => {
            fetch(`/wallet/get_users?search=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success' && data.data.length > 0) {
                        displaySearchResults(data.data);
                    } else {
                        searchResults.innerHTML = '<div class="p-3 text-gray-500 dark:text-gray-400">No users found</div>';
                        searchResults.classList.remove('hidden');
                    }
                })
                .catch(error => {
                    console.error('Error searching users:', error);
                });
        }, 300);
    });

    // Display search results
    function displaySearchResults(users) {
        searchResults.innerHTML = users.map(user => `
            <div class="user-result p-3 hover:bg-gray-50 dark:hover:bg-gray-600 cursor-pointer border-b border-gray-200 dark:border-gray-600 last:border-b-0" 
                 data-user-id="${user.id}" 
                 data-user-name="${user.name}" 
                 data-user-email="${user.email}" 
                 data-user-avatar="${user.profile_picture || '/images/default-avatar.png'}">
                <div class="flex items-center">
                    <img src="${user.profile_picture || '/images/default-avatar.png'}" alt="${user.name}" class="w-8 h-8 rounded-full mr-3">
                    <div>
                        <p class="font-medium text-gray-900 dark:text-white">${user.name}</p>
                        <p class="text-sm text-gray-600 dark:text-gray-400">${user.email}</p>
                    </div>
                </div>
            </div>
        `).join('');
        
        searchResults.classList.remove('hidden');
    }

    // Select recipient
    searchResults.addEventListener('click', function(e) {
        if (e.target.closest('.user-result')) {
            const userResult = e.target.closest('.user-result');
            const userId = userResult.dataset.userId;
            const userName = userResult.dataset.userName;
            const userEmail = userResult.dataset.userEmail;
            const userAvatar = userResult.dataset.userAvatar;

            // Set hidden input
            toUserIdInput.value = userId;

            // Display selected recipient
            recipientAvatar.src = userAvatar;
            recipientName.textContent = userName;
            recipientEmail.textContent = userEmail;
            selectedRecipient.classList.remove('hidden');

            // Hide search results and clear search input
            searchResults.classList.add('hidden');
            searchInput.value = userName;

            // Enable transfer button
            transferBtn.disabled = false;
        }
    });

    // Remove selected recipient
    removeRecipientBtn.addEventListener('click', function() {
        toUserIdInput.value = '';
        selectedRecipient.classList.add('hidden');
        searchInput.value = '';
        transferBtn.disabled = true;
    });

    // Hide search results when clicking outside
    document.addEventListener('click', function(e) {
        if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) {
            searchResults.classList.add('hidden');
        }
    });

    // Amount validation
    const amountInput = document.getElementById('amount');
    amountInput.addEventListener('input', function() {
        const amount = parseFloat(this.value);
        const maxAmount = {{ $balance }};
        
        if (amount > maxAmount) {
            this.setCustomValidity('Amount cannot exceed your available balance');
        } else if (amount <= 0) {
            this.setCustomValidity('Amount must be greater than 0');
        } else {
            this.setCustomValidity('');
        }
    });

    // Initially disable transfer button
    transferBtn.disabled = true;
});
</script>
@endpush
@endsection
