@extends('layouts.app')
@section('title', 'Create Invoice')
@php($prefix = auth()->user()->role === 'admin' ? 'admin.' : 'user.')
@section('content')
<!-- Create Invoice Modal -->
<div id="invoiceModal"
    class="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black bg-opacity-50">
    <div class="modal-content bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-2xl m-4">
        <!-- Modal Header -->
        <div class="flex justify-between items-center p-5 border-b border-gray-200 dark:border-gray-700">
            <h4 class="text-xl font-semibold text-gray-800 dark:text-gray-100">
                <i class="fa-solid fa-file-invoice-dollar text-Black mr-3"></i>Create Invoice
            </h4>
            <a href="{{ route($prefix . 'invoices.index') }}" id="closeInvoiceModalBtn"
                class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                <i class="fa-solid fa-times text-xl"></i>
            </a>
        </div>

        <!-- Form -->
        <form id="invoiceForm" action="{{ route($prefix . 'invoices.store') }}" method="POST"
            class="p-6 max-h-[70vh] overflow-y-auto">
            @csrf
            <input type="hidden" name="type" value="invoice">
            <input type="hidden" name="id" value=""> <!-- This can be used for editing -->

            <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mb-5">
                <div>
                    <label for="amount" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Amount
                        (BDT) *</label>
                    <input type="number" id="amount" name="amount" value="{{ old('amount') }}" step="0.01"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        required placeholder="e.g., 500.00">
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Please enter a numeric value only (e.g., 500 or 500.50).
                    </p>
                    <div class="error-message text-red-500 text-sm mt-1 hidden" id="amount_error"></div>
                    @error('amount')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="brand_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">User
                        Brand *</label>
                    <select id="brand_id" name="brand_id"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        required>
                        <option value="" disabled {{ old('brand_id') ? '' : 'selected' }}>Select Brand</option>
                        @foreach ($brands as $brand)
                        <option value="{{ $brand->id }}" {{ old('brand_id') == $brand->id ? 'selected' : '' }}>{{ $brand->name }}</option>
                        @endforeach
                    </select>
                    <div class="error-message text-red-500 text-sm mt-1 hidden" id="brand_id_error"></div>
                    @error('brand_id')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="due_date" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Due
                        Date *</label>
                    <input type="date" id="due_date" name="due_date"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        required value="{{ old('due_date') }}">
                    <div class="error-message text-red-500 text-sm mt-1 hidden" id="due_date_error"></div>
                    @error('due_date')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="status" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Status
                        *</label>
                    <select id="status" name="status"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        required>
                        <option value="1" {{ old('status', '1') == '1' ? 'selected' : '' }}>Active</option>
                        <option value="0" {{ old('status') == '0' ? 'selected' : '' }}>Deactivated</option>
                    </select>
                    @error('status')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="payment_status"
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Payment Status *</label>
                    <select id="payment_status" name="payment_status"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        required>
                        <option value="" disabled {{ old('payment_status') ? '' : 'selected' }}>Select one</option>
                        <option value="unpaid" {{ old('payment_status') == 'unpaid' ? 'selected' : '' }}>Unpaid</option>
                        <option value="pending" {{ old('payment_status') == 'pending' ? 'selected' : '' }}>Pending</option>
                        <option value="paid" {{ old('payment_status') == 'paid' ? 'selected' : '' }}>Paid</option>
                    </select>
                    <div class="error-message text-red-500 text-sm mt-1 hidden" id="payment_status_error"></div>
                    @error('payment_status')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <div class="space-y-4 mb-6">
                <div>
                    <label for="customer_name"
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Customer Name *</label>
                    <input type="text" id="customer_name" name="customer_name"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        required value="{{ old('customer_name') }}">
                    <div class="error-message text-red-500 text-sm mt-1 hidden" id="customer_name_error"></div>
                    @error('customer_name')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="customer_number"
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Customer Number</label>
                    <input type="text" id="customer_number" name="customer_number"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        value="{{ old('customer_number') }}">
                    @error('customer_number')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="customer_email"
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Customer Email</label>
                    <input type="email" id="customer_email" name="customer_email"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        value="{{ old('customer_email') }}">
                    <div class="error-message text-red-500 text-sm mt-1 hidden" id="customer_email_error"></div>
                    @error('customer_email')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="customer_address"
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Customer Address</label>
                    <textarea id="customer_address" name="customer_address" rows="2"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">{{ old('customer_address') }}</textarea>
                    @error('customer_address')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="description"
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Description</label>
                    <textarea id="description" name="description" rows="2"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">{{ old('description') }}</textarea>
                    @error('description')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <!-- Honeypot Field -->
            <div class="hidden">
                <label>Fill This Field</label>
                <input type="text" name="honeypot" value="">
            </div>

            <!-- Modal Footer -->
            <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                <a href="{{ route($prefix . 'invoices.index') }}"
                    class="bg-gray-200 hover:bg-gray-300 text-gray-800 dark:bg-gray-600 dark:text-gray-200 dark:hover:bg-gray-500 font-medium py-2 px-4 rounded-lg transition-colors">
                    Close
                </a>
                <button type="submit" id="saveInvoiceBtn"
                    class="bg-black text-white font-medium py-2 px-4 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fa-solid fa-save mr-2"></i>
                    <span id="saveInvoiceBtnText">Save Invoice</span>
                    <span id="saveInvoiceBtnLoading" class="hidden">
                        <i class="fa-solid fa-spinner fa-spin mr-2"></i>Saving...
                    </span>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Success Notification -->
<div id="successNotification" class="fixed top-4 right-4 z-50 hidden">
    <div class="bg-green-500 text-white px-6 py-4 rounded-lg shadow-lg">
        <div class="flex items-center">
            <i class="fa-solid fa-check-circle mr-3"></i>
            <span id="successMessage">Invoice created successfully!</span>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const invoiceForm = document.getElementById('invoiceForm');
    const saveInvoiceBtn = document.getElementById('saveInvoiceBtn');
    const saveInvoiceBtnText = document.getElementById('saveInvoiceBtnText');
    const saveInvoiceBtnLoading = document.getElementById('saveInvoiceBtnLoading');

    // Show error message
    function showError(fieldId, message) {
        const errorElement = document.getElementById(fieldId + '_error');
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.classList.remove('hidden');
            
            // Add red border to input
            const inputElement = document.getElementById(fieldId);
            if (inputElement) {
                inputElement.classList.add('border-red-500');
            }
        }
    }

    // Hide error message
    function hideError(fieldId) {
        const errorElement = document.getElementById(fieldId + '_error');
        if (errorElement) {
            errorElement.classList.add('hidden');
            
            // Remove red border from input
            const inputElement = document.getElementById(fieldId);
            if (inputElement) {
                inputElement.classList.remove('border-red-500');
            }
        }
    }

    // Show success message
    function showSuccess(message) {
        const successNotification = document.getElementById('successNotification');
        const successMessage = document.getElementById('successMessage');
        
        if (successNotification && successMessage) {
            successMessage.textContent = message;
            successNotification.classList.remove('hidden');
            
            setTimeout(() => {
                successNotification.classList.add('hidden');
            }, 3000);
        }
    }

    // Validate individual field
    function validateField(field) {
        const value = field.value.trim();
        const fieldName = field.name;

        hideError(fieldName);

        // Required field validation
        if (field.hasAttribute('required') && !value) {
            showError(fieldName, 'This field is required');
            return false;
        }

        // Specific field validations
        switch(fieldName) {
            case 'amount':
                if (value && (isNaN(value) || parseFloat(value) < 0)) {
                    showError(fieldName, 'Amount must be a positive number');
                    return false;
                }
                break;
                
            case 'customer_email':
                if (value && !isValidEmail(value)) {
                    showError(fieldName, 'Please enter a valid email address');
                    return false;
                }
                break;
                
            case 'due_date':
                if (value) {
                    const selectedDate = new Date(value);
                    const today = new Date();
                    today.setHours(0, 0, 0, 0);
                    
                    if (selectedDate <= today) {
                        showError(fieldName, 'Due date must be a future date');
                        return false;
                    }
                }
                break;
        }

        return true;
    }

    // Email validation
    function isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    // Validate entire form
    function validateForm() {
        let isValid = true;
        
        const requiredFields = invoiceForm.querySelectorAll('[required]');
        requiredFields.forEach(field => {
            if (!validateField(field)) {
                isValid = false;
            }
        });

        return isValid;
    }

    // Real-time validation on blur
    document.querySelectorAll('#invoiceForm input, #invoiceForm select, #invoiceForm textarea').forEach(element => {
        element.addEventListener('blur', function() {
            validateField(this);
        });

        // Real-time validation while typing for some fields
        if (element.name === 'customer_email' || element.name === 'amount') {
            element.addEventListener('input', function() {
                hideError(this.name);
            });
        }
    });

    // Form submission
    if (invoiceForm) {
        invoiceForm.addEventListener('submit', async function(event) {
            event.preventDefault();
            event.stopPropagation();

            console.log('Form submission started...');

            // Validate form
            if (!validateForm()) {
                console.log('Form validation failed');
                return;
            }

            console.log('Form validation passed');

            // Disable submit button and show loading
            saveInvoiceBtn.disabled = true;
            saveInvoiceBtnText.classList.add('hidden');
            saveInvoiceBtnLoading.classList.remove('hidden');

            const formData = new FormData(invoiceForm);

            // Log form data for debugging
            for (let [key, value] of formData.entries()) {
                console.log(key + ': ' + value);
            }

            try {
                const response = await fetch(this.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    }
                });

                console.log('Response status:', response.status);

                const data = await response.json();
                console.log('Response data:', data);

                if (response.ok && data.success) {
                    showSuccess(data.message || 'Invoice created successfully!');
                    
                    // Reset form
                    invoiceForm.reset();
                    
                    // Redirect after 2 seconds
                    setTimeout(() => {
                        window.location.href = "{{ route($prefix . 'invoices.index') }}";
                    }, 2000);
                    
                } else {
                    // Handle validation errors
                    if (data.errors) {
                        Object.keys(data.errors).forEach(field => {
                            showError(field, data.errors[field][0]);
                        });
                    } else {
                        showError('form', data.message || 'An error occurred while creating the invoice');
                    }
                }
            } catch (error) {
                console.error('Error:', error);
                showError('form', 'Network error occurred. Please try again.');
            } finally {
                // Re-enable submit button
                saveInvoiceBtn.disabled = false;
                saveInvoiceBtnText.classList.remove('hidden');
                saveInvoiceBtnLoading.classList.add('hidden');
            }
        });
    }

    // Close modal functionality
    const closeBtn = document.getElementById('closeInvoiceModalBtn');
    if (closeBtn) {
        closeBtn.addEventListener('click', function(e) {
            e.preventDefault();
            window.location.href = "{{ route($prefix . 'invoices.index') }}";
        });
    }

    // Escape key to close modal
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            window.location.href = "{{ route($prefix . 'invoices.index') }}";
        }
    });
});
</script>

<style>
.error-message {
    transition: all 0.3s ease;
}

input:invalid,
select:invalid {
    border-color: #f87171;
}

input:valid,
select:valid {
    border-color: #10b981;
}
</style>
@endpush