@extends('front_end.layouts.home')

@section('title', 'Withdraw Funds')

@push('styles')
<style>
    .is-invalid {
        border-color: #dc3545 !important;
    }
    .is-valid {
        border-color: #198754 !important;
    }
    .invalid-feedback {
        display: block;
        color: #dc3545;
        font-size: 0.875em;
        margin-top: 0.25rem;
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
@endpush

@section('content')
<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">Withdraw Funds</h4>
                                    <p class="mb-0 text-white">Create a withdrawal request</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">Withdrawal Form</h6>
                    </div>
                    <div class="card-body">
                        <form id="withdrawForm">
                            @csrf
                            <div class="mb-3">
                                <label for="withdraw_type" class="form-label">Withdrawal Method</label>
                                <select class="form-select" id="withdraw_type" name="type" required onchange="togglePaymentFields()">
                                    <option value="">Select Method</option>
                                    @if(setting('bank_withdraw')==1)
                                        <option value="Paypal">PayPal</option>
                                    @endif
                                    @if(setting('paypal_withdraw')==1)
                                        <option value="Bank">Bank Transfer</option>
                                    @endif
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="withdraw_amount" class="form-label">Amount ($)</label>
                                <input type="number" class="form-control" id="withdraw_amount" name="amount" step="0.01" min="10" required 
                                    data-wallet-balance="{{ getUserWallet(auth()->id()) }}">
                                <small class="text-muted">Minimum: ${{ setting('m_withdrawal') }} | Available Balance: ${{ number_format(getUserWallet(auth()->id()), 2) }}</small>
                            </div>

                            <!-- PayPal Fields -->
                            <div id="paypal_fields" class="d-none">
                                <div class="mb-3">
                                    <label for="paypal_email" class="form-label">PayPal Email</label>
                                    <input type="email" class="form-control" id="paypal_email" name="paypal_email">
                                </div>
                            </div>

                            <!-- Bank Fields -->
                            <div id="bank_fields" class="d-none">
                                <div class="mb-3">
                                    <label for="full_name" class="form-label">Account Holder Name</label>
                                    <input type="text" class="form-control" id="full_name" name="full_name">
                                </div>
                                <div class="mb-3">
                                    <label for="bank_name" class="form-label">Bank Name</label>
                                    <input type="text" class="form-control" id="bank_name" name="bank_name">
                                </div>
                                <div class="mb-3">
                                    <label for="bank_account_no" class="form-label">Account Number</label>
                                    <input type="text" class="form-control" id="bank_account_no" name="bank_account_no">
                                </div>
                                <div class="mb-3">
                                    <label for="iban" class="form-label">IBAN</label>
                                    <input type="text" class="form-control" id="iban" name="iban">
                                </div>
                                <div class="mb-3">
                                    <label for="swift_code" class="form-label">SWIFT Code</label>
                                    <input type="text" class="form-control" id="swift_code" name="swift_code">
                                </div>
                                <div class="mb-3">
                                    <label for="country" class="form-label">Country</label>
                                    <input type="text" class="form-control" id="country" name="country">
                                </div>
                            </div>

                            <div class="d-flex justify-content-end">
                                <a href="{{ route('wallet.index') }}" class="btn btn-light me-2">Cancel</a>
                                <button type="button" class="btn btn-primary" onclick="submitWithdraw()">Request Withdrawal</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Initialize validation state
let validationErrors = {};

// Validation rules
const validationRules = {
    type: {
        required: true,
        message: 'Please select a withdrawal method'
    },
    amount: {
        required: true,
        min: {{ setting('m_withdrawal') }},
        message: 'Amount must be at least ${{ setting('m_withdrawal') }}',
        validateBalance: true
    },
    paypal_email: {
        required: true,
        email: true,
        message: 'Please enter a valid PayPal email'
    },
    full_name: {
        required: true,
        minLength: 3,
        message: 'Please enter the account holder name (min 3 characters)'
    },
    bank_name: {
        required: true,
        message: 'Please enter the bank name'
    },
    bank_account_no: {
        required: true,
        message: 'Please enter the bank account number'
    },
    iban: {
        required: true,
        message: 'Please enter the IBAN'
    },
    swift_code: {
        required: true,
        message: 'Please enter the SWIFT code'
    },
    country: {
        required: true,
        message: 'Please enter the country'
    }
};

// Validate a single field
function validateField(field) {
    const value = field.value.trim();
    const name = field.name;
    const rules = validationRules[name];
    
    // Remove existing error message
    const existingError = field.parentElement.querySelector('.invalid-feedback');
    if (existingError) existingError.remove();
    field.classList.remove('is-invalid', 'is-valid');
    
    // Skip validation if field is not required for current payment type
    const type = document.getElementById('withdraw_type').value;
    if ((type === 'Paypal' && !name.includes('paypal')) || 
        (type === 'Bank' && name === 'paypal_email')) {
        delete validationErrors[name];
        return true;
    }
    
    if (!rules) return true;
    
    let isValid = true;
    let errorMessage = '';
    
    // Required validation
    if (rules.required && !value) {
        isValid = false;
        errorMessage = rules.message;
    }
    
    // Email validation
    if (rules.email && value && !value.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
        isValid = false;
        errorMessage = rules.message;
    }
    
    // Min length validation
    if (rules.minLength && value.length < rules.minLength) {
        isValid = false;
        errorMessage = rules.message;
    }
    
    // Min value validation
    if (rules.min && Number(value) < rules.min) {
        isValid = false;
        errorMessage = rules.message;
    }
    
    // Wallet balance validation
    if (rules.validateBalance && name === 'amount') {
        const walletBalance = parseFloat(field.dataset.walletBalance);
        const amount = parseFloat(value);
        if (amount > walletBalance) {
            isValid = false;
            errorMessage = `Amount cannot exceed your wallet balance ($${walletBalance.toFixed(2)})`;
        }
    }
    
    // Show validation state
    if (!isValid) {
        field.classList.add('is-invalid');
        const feedback = document.createElement('div');
        feedback.className = 'invalid-feedback';
        feedback.textContent = errorMessage;
        field.parentElement.appendChild(feedback);
        validationErrors[name] = errorMessage;
    } else {
        field.classList.add('is-valid');
        delete validationErrors[name];
    }
    
    return isValid;
}

// Validate all fields
function validateForm() {
    const form = document.getElementById('withdrawForm');
    const fields = form.querySelectorAll('input, select');
    fields.forEach(validateField);
    return Object.keys(validationErrors).length === 0;
}

// Handle form submission
function submitWithdraw() {
    if (!validateForm()) {
        return;
    }
    
    const form = document.getElementById('withdrawForm');
    const submitBtn = form.querySelector('button[type="button"]');
    const originalBtnText = submitBtn.innerHTML;
    
    // Disable form during submission
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...';
    
    const formData = new FormData(form);
    
    fetch('{{ route("wallet.create.withdraw.request") }}', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 200) {
            // Show success message
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Withdrawal request submitted successfully',
                showConfirmButton: false,
                timer: 2000
            }).then(() => {
                window.location.href = '{{ route('wallet.index') }}';
            });
        } else {
            // Show error message
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: data.message || 'Failed to submit withdrawal request'
            });
        }
    })
    .catch(error => {
        // Show network error
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Network error occurred. Please try again.'
        });
    })
    .finally(() => {
        // Re-enable form
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalBtnText;
    });
}

function togglePaymentFields() {
    const type = document.getElementById('withdraw_type').value;
    const paypalFields = document.getElementById('paypal_fields');
    const bankFields = document.getElementById('bank_fields');
    
    // Reset validation state when switching payment type
    validationErrors = {};
    document.querySelectorAll('.is-invalid, .is-valid').forEach(field => {
        field.classList.remove('is-invalid', 'is-valid');
    });
    document.querySelectorAll('.invalid-feedback').forEach(feedback => {
        feedback.remove();
    });
    
    paypalFields.classList.add('d-none');
    bankFields.classList.add('d-none');
    
    if (type === 'Paypal') {
        paypalFields.classList.remove('d-none');
        // Clear bank fields
        bankFields.querySelectorAll('input').forEach(input => input.value = '');
    }
    if (type === 'Bank') {
        bankFields.classList.remove('d-none');
        // Clear PayPal fields
        paypalFields.querySelectorAll('input').forEach(input => input.value = '');
    }
}

// Add event listeners for real-time validation
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('withdrawForm');
    const fields = form.querySelectorAll('input, select');
    
    fields.forEach(field => {
        field.addEventListener('blur', () => validateField(field));
        field.addEventListener('input', () => validateField(field));
    });
});
</script>

@endsection


