@extends('front_end.layouts.home')

@section('title', 'Transfer Money')

@section('content')
@php $availableBalance = getUserWallet(auth()->id()); @endphp
<div class="bg-white shadow-sm border-0 rounded-3">
    <div class="card border-0 mb-4">
        <div class="card-body p-0">
            <div class="row g-0">
                <div class="col-12">
                    <div class="bg-primary text-white p-4 rounded-top-3">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <a href="{{ route('wallet.index') }}" class="text-white me-3">
                                    <i class="fas fa-arrow-left fa-lg"></i>
                                </a>
                                <div>
                                    <h4 class="mb-0 text-white">Transfer Money</h4>
                                    <p class="mb-0 text-white">Send money securely to other users</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-lg-12">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Transfer Form</h6>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <small class="text-muted">Available balance</small>
                            <span class="badge bg-light text-dark">$ {{ number_format($availableBalance, 2) }}</span>
                        </div>
                        <div id="formAlert" class="alert d-none" role="alert"></div>
                        <form id="transferForm" novalidate>
                            @csrf
                            <div class="row g-3">
                                <div class="col-12">
                                    <label for="to_userId" class="form-label">Recipient</label>
                                    <select class="form-control" id="to_userId" name="to_userId" style="width: 100%" required autofocus></select>
                                    <div class="invalid-feedback" id="error_to_userId"></div>
                                    <small class="text-muted">Search user by name or email</small>
                                </div>
                                <div class="col-12">
                                    <label for="transfer_amount" class="form-label">Amount ($)</label>
                                    <div class="input-group">
                                        <span class="input-group-text">$</span>
                                        <input type="number" class="form-control" id="transfer_amount" name="amount" step="0.01" min="0.01" max="{{ number_format($availableBalance, 2, '.', '') }}" required>
                                    </div>
                                    <div class="invalid-feedback" id="error_amount"></div>
                                    <small class="text-muted">Max: $ {{ number_format($availableBalance, 2) }}</small>
                                </div>
                                <div class="col-12">
                                    <label for="transfer_password" class="form-label">Password</label>
                                    <div class="input-group">
                                        <input type="password" class="form-control" id="transfer_password" name="password" required>
                                        <button class="btn btn-outline-secondary" type="button" id="togglePw" tabindex="-1"><i class="far fa-eye"></i></button>
                                    </div>
                                    <div class="invalid-feedback" id="error_password"></div>
                                </div>
                                <div class="col-12 d-flex justify-content-end mt-2">
                                    <a href="{{ route('wallet.index') }}" class="btn btn-light me-2">Cancel</a>
                                    <button type="button" id="submitBtn" class="btn btn-primary" onclick="submitTransfer()">
                                        <span class="btn-text">Send Money</span>
                                        <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Ensure jQuery and Select2 + theme are available
(function ensureDeps(){
    function loadScript(src){ return new Promise(r=>{ const s=document.createElement('script'); s.src=src; s.onload=r; document.body.appendChild(s); }); }
    function loadStyle(href){ const l=document.createElement('link'); l.rel='stylesheet'; l.href=href; document.head.appendChild(l); }

    if (!window.jQuery) {
        loadScript('https://code.jquery.com/jquery-3.6.0.min.js').then(loadSelect2);
    } else {
        loadSelect2();
    }

    function loadSelect2(){
        loadStyle('https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css');
        loadStyle('https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5.min.css');
        if (!$.fn.select2) {
            loadScript('https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js');
        }
    }
})();

document.addEventListener('DOMContentLoaded', function() {
    // Load jQuery if not present
    if (typeof jQuery === 'undefined') {
        var script = document.createElement('script');
        script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
        script.onload = loadSelect2;
        document.head.appendChild(script);
    } else {
        loadSelect2();
    }

    function loadSelect2() {
        if (typeof jQuery.fn.select2 === 'undefined') {
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css';
            document.head.appendChild(link);

            var script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js';
            script.onload = initSelect2;
            document.head.appendChild(script);
        } else {
            initSelect2();
        }
    }

    function initSelect2() {
        $('#to_userId').select2({
            placeholder: 'Search user by name or email',
            allowClear: true,
            ajax: {
                url: '{{ route('wallet.get_users') }}',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        q: params.term || '',
                        page: params.page || 1
                    };
                },
                processResults: function(data) {
                    return {
                        results: data.results.map(function(item) {
                            return {
                                id: item.id,
                                text: item.text,
                                email: item.text.match(/\((.*?)\)/)?.[1] || ''
                            };
                        })
                    };
                },
                cache: true
            },
            minimumInputLength: 1,
            templateResult: formatUser,
            templateSelection: formatUserSelection,
            escapeMarkup: function(markup) { return markup; }
        }).on('select2:open', function() {
            document.querySelector('.select2-search__field').focus();
        });
    }

    function formatUser(user) {
        if (!user.id) return user.text;
        var name = user.text.split('(')[0].trim();
        var email = user.email;
        
        return $('<div class="select2-result-user">' +
                '<div class="user-name">' + name + '</div>' +
                '<div class="user-email">' + email + '</div>' +
                '</div>');
    }

    function formatUserSelection(user) {
        if (!user.id) return user.text;
        return user.text.split('(')[0].trim();
    }

    // Clear errors on input
    ['transfer_amount','transfer_password'].forEach(id => {
        const el = document.getElementById(id);
        el.addEventListener('input', () => clearFieldError(id.replace('transfer_','')));
    });
    $('#to_userId').on('change', () => clearFieldError('to_userId'));

    // Toggle password visibility
    const toggle = document.getElementById('togglePw');
    if (toggle) {
        toggle.addEventListener('click', function(){
            const pw = document.getElementById('transfer_password');
            const icon = this.querySelector('i');
            if (pw.type === 'password') { pw.type = 'text'; icon.classList.remove('fa-eye'); icon.classList.add('fa-eye-slash'); }
            else { pw.type = 'password'; icon.classList.remove('fa-eye-slash'); icon.classList.add('fa-eye'); }
        });
    }
});

function setFieldError(field, message){
    const inputMap = { to_userId: '#to_userId', amount: '#transfer_amount', password: '#transfer_password' };
    const el = document.querySelector(inputMap[field]);
    if (!el) return;
    
    // Add invalid class to the element
    el.classList.add('is-invalid');
    
    // For Select2, also add invalid class to container
    if (field === 'to_userId') {
        const select2Container = el.closest('.select2-container');
        if (select2Container) {
            select2Container.classList.add('is-invalid');
        }
    }
    
    // For amount field, also add invalid class to input group
    if (field === 'amount') {
        const inputGroup = el.closest('.input-group');
        if (inputGroup) {
            inputGroup.classList.add('has-validation');
            const inputGroupText = inputGroup.querySelector('.input-group-text');
            if (inputGroupText) {
                inputGroupText.style.borderColor = '#dc3545';
            }
        }
    }
    
    // Show error message
    const err = document.getElementById('error_' + field);
    if (err) {
        err.style.display = 'block';
        err.textContent = message;
    }
}
function clearFieldError(field){
    const inputMap = { to_userId: '#to_userId', amount: '#transfer_amount', password: '#transfer_password' };
    const el = document.querySelector(inputMap[field]);
    if (!el) return;
    
    // Remove invalid class from element
    el.classList.remove('is-invalid');
    
    // For Select2, remove invalid class from container
    if (field === 'to_userId') {
        const select2Container = el.closest('.select2-container');
        if (select2Container) {
            select2Container.classList.remove('is-invalid');
        }
    }
    
    // For amount field, clean up input group validation
    if (field === 'amount') {
        const inputGroup = el.closest('.input-group');
        if (inputGroup) {
            const inputGroupText = inputGroup.querySelector('.input-group-text');
            if (inputGroupText) {
                inputGroupText.style.borderColor = '#e4e6eb';
            }
        }
    }
    
    // Hide error message
    const err = document.getElementById('error_' + field);
    if (err) {
        err.style.display = 'none';
        err.textContent = '';
    }
}
function setFormAlert(type, message){
    const box = document.getElementById('formAlert');
    box.className = 'alert alert-' + type;
    box.textContent = message;
}
function clearFormAlert(){
    const box = document.getElementById('formAlert');
    box.className = 'alert d-none';
    box.textContent = '';
}

function validateTransferForm(){
    clearFormAlert();
    let valid = true;
    const userId = $('#to_userId').val();
    const amount = document.getElementById('transfer_amount').value;
    const password = document.getElementById('transfer_password').value.trim();
    const max = parseFloat(document.getElementById('transfer_amount').getAttribute('max')) || Infinity;

    // Recipient validation
    if (!userId) {
        setFieldError('to_userId', 'Please select a recipient from the list');
        valid = false;
    }

    // Amount validation
    if (!amount) {
        setFieldError('amount', 'Please enter the amount to transfer');
        valid = false;
    } else {
        const amountNum = parseFloat(amount);
        if (isNaN(amountNum) || amountNum <= 0) {
            setFieldError('amount', 'Please enter a valid amount greater than 0');
            valid = false;
        } else if (amountNum > max) {
            setFieldError('amount', `Amount exceeds your available balance ($${max.toFixed(2)})`);
            valid = false;
        } else if (amountNum < 0.01) {
            setFieldError('amount', 'Minimum transfer amount is $0.01');
            valid = false;
        }
    }

    // Password validation
    if (!password) {
        setFieldError('password', 'Please enter your password to confirm the transfer');
        valid = false;
    } else if (password.length < 6) {
        setFieldError('password', 'Password must be at least 6 characters');
        valid = false;
    }

    if (!valid) {
        setFormAlert('warning', 'Please correct the errors before proceeding');
    }

    return valid;
}

function setSubmitting(isSubmitting){
    const btn = document.getElementById('submitBtn');
    btn.disabled = isSubmitting;
    btn.querySelector('.btn-text').classList.toggle('d-none', isSubmitting);
    btn.querySelector('.spinner-border').classList.toggle('d-none', !isSubmitting);
}

function submitTransfer() {
    // Clear previous errors
    ['to_userId','amount','password'].forEach(clearFieldError);
    clearFormAlert();

    // Validate form
    if (!validateTransferForm()) return;

    // Show confirmation dialog
    const amount = document.getElementById('transfer_amount').value;
    const recipientName = $('#to_userId').select2('data')[0]?.text.split('(')[0].trim() || 'selected user';
    
    if (!confirm(`Are you sure you want to transfer $${parseFloat(amount).toFixed(2)} to ${recipientName}?`)) {
        return;
    }

    // Submit form
    const form = document.getElementById('transferForm');
    const formData = new FormData(form);
    setSubmitting(true);
    
    fetch('{{ route("wallet.transfer.amount") }}', {
        method: 'POST',
        body: formData,
        headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
    })
    .then(async r => {
        let data;
        try { 
            data = await r.json();
        } catch(_) {
            throw new Error('Unexpected response from server');
        }

        if (data.status === 200) {
            setFormAlert('success', 'Transfer completed successfully! Redirecting...');
            // Clear form
            form.reset();
            $('#to_userId').val(null).trigger('change');
            // Redirect after showing success message
            setTimeout(() => { window.location.href = '{{ route('wallet.index') }}'; }, 1500);
        } else {
            // Handle specific error cases
            if (data.message.toLowerCase().includes('insufficient')) {
                setFieldError('amount', data.message);
                setFormAlert('danger', 'Insufficient balance for this transfer');
            } else if (data.message.toLowerCase().includes('password')) {
                setFieldError('password', 'Incorrect password');
                setFormAlert('danger', 'Please check your password and try again');
            } else {
                setFormAlert('danger', data.message || 'Transfer failed. Please try again.');
            }
        }
    })
    .catch(error => {
        console.error('Transfer error:', error);
        setFormAlert('danger', 'Network error. Please check your connection and try again.');
    })
    .finally(() => {
        setSubmitting(false);
        // Scroll to top if there's an error
        if (document.querySelector('.alert.alert-danger')) {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    });
}
</script>

<style>
/* Select2 Customization */
.select2-container {
    width: 100% !important;
}

.select2-container--default .select2-selection--single {
    height: 45px !important;
    border: 1px solid #e4e6eb !important;
    border-radius: 8px !important;
    background-color: #fff !important;
    display: flex !important;
    align-items: center !important;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: normal !important;
    padding-left: 15px !important;
    padding-right: 40px !important;
    color: #333 !important;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 100% !important;
    width: 30px !important;
    right: 5px !important;
}

.select2-container--default .select2-selection--single .select2-selection__clear {
    margin-right: 10px !important;
    color: #999 !important;
    font-size: 18px !important;
    margin-top: -2px !important;
}

.select2-dropdown {
    border: 1px solid #e4e6eb !important;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
    border-radius: 8px !important;
    margin-top: 4px !important;
}

.select2-search--dropdown {
    padding: 10px !important;
}

.select2-search--dropdown .select2-search__field {
    height: 40px !important;
    border: 1px solid #e4e6eb !important;
    border-radius: 6px !important;
    padding: 8px 12px !important;
    font-size: 14px !important;
}

.select2-search--dropdown .select2-search__field:focus {
    border-color: #e4e6eb !important;
    outline: none !important;
    box-shadow: none !important;
}

.select2-results__option {
    padding: 10px 15px !important;
    font-size: 14px !important;
    line-height: 1.4 !important;
}

.select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: #f0f2f5 !important;
    color: #333 !important;
}

.select2-result-user {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.select2-result-user .user-name {
    font-weight: 500;
    color: #333;
}

.select2-result-user .user-email {
    font-size: 12px;
    color: #65676b;
}

.select2-container--default.select2-container--focus .select2-selection--single {
    border-color: #e4e6eb !important;
    box-shadow: none !important;
}

.select2-container--default.select2-container--open .select2-selection--single {
    border-color: #e4e6eb !important;
    box-shadow: none !important;
}

/* Placeholder styling */
.select2-container--default .select2-selection--single .select2_selection__placeholder {
    color: #65676b !important;
}

/* Form validation styling */
.invalid-feedback {
    display: block;
    width: 100%;
    margin-top: 0.25rem;
    font-size: 0.875em;
    color: #dc3545;
}

.form-control.is-invalid,
.input-group .form-control.is-invalid {
    border-color: #dc3545;
    padding-right: calc(1.5em + 0.75rem);
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right calc(0.375em + 0.1875rem) center;
    background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.input-group.has-validation > .form-control.is-invalid {
    border-color: #dc3545;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.input-group.has-validation > .input-group-text {
    border-right: 0;
}

.input-group.has-validation > .form-control.is-invalid + .input-group-text {
    border-color: #dc3545;
    border-left: 0;
}

.input-group.has-validation > .invalid-feedback {
    margin-top: 0.25rem;
}

/* Select2 validation */
.select2-container--default.is-invalid .select2-selection--single {
    border-color: #dc3545 !important;
}
</style>
</style>

@endsection


