<x-shop-layout title="Checkout">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-8">Checkout</h1>

        @if($cartItems && count($cartItems) > 0)
            <!-- Display validation errors -->
            @if ($errors->any())
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                    <h3 class="font-bold">Please fix the following errors:</h3>
                    <ul class="mt-2 list-disc list-inside">
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <form id="checkout-form" action="{{ route('checkout.process') }}" method="POST">
                @csrf
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    <!-- Order Form -->
                    <div class="space-y-6">
                        <!-- Customer Information -->
                        <div class="bg-white p-6 rounded-lg shadow-md">
                            <h2 class="text-xl font-semibold text-gray-900 mb-4">Customer Information</h2>
                            
                            @guest
                                <!-- Guest Checkout -->
                                <div class="space-y-4">
                                    <div>
                                        <label for="name" class="block text-sm font-medium text-gray-700 mb-2">Full Name *</label>
                                        <input type="text" id="name" name="name" required 
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                               value="{{ old('name') }}">
                                        @error('name')
                                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                                        @enderror
                                    </div>
                                    
                                    <div>
                                        <label for="phone" class="block text-sm font-medium text-gray-700 mb-2">Phone Number *</label>
                                        <input type="tel" id="phone" name="phone" required 
                                               pattern="^01[3-9][0-9]{8}$"
                                               placeholder="01XXXXXXXXX"
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                               value="{{ old('phone') }}">
                                        @error('phone')
                                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                                        @enderror
                                        <p class="text-sm text-gray-500 mt-1">Enter a valid Bangladesh phone number</p>
                                    </div>
                                </div>
                                
                                <div class="mt-4 p-4 bg-blue-50 rounded-lg">
                                    <p class="text-sm text-blue-800">
                                        📱 <strong>Have an account?</strong> 
                                        <button onclick="openLoginModal()" class="text-blue-600 hover:text-blue-800 font-medium cursor-pointer">Sign in</button> 
                                        for faster checkout or 
                                        <button onclick="openRegisterModal()" class="text-blue-600 hover:text-blue-800 font-medium cursor-pointer">create an account</button> 
                                        to track your orders.
                                    </p>
                                </div>
                            @else
                                <!-- Logged in user -->
                                <div class="space-y-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Full Name</label>
                                        <input type="text" value="{{ auth()->user()->name }}" disabled 
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50">
                                        <input type="hidden" name="name" value="{{ auth()->user()->name }}">
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Phone Number</label>
                                        <input type="tel" value="{{ auth()->user()->phone }}" disabled 
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50">
                                        <input type="hidden" name="phone" value="{{ auth()->user()->phone }}">
                                    </div>
                                </div>
                            @endauth
                        </div>

                        <!-- Delivery Address -->
                        <div class="bg-white p-6 rounded-lg shadow-md">
                            <h2 class="text-xl font-semibold text-gray-900 mb-4">Delivery Address</h2>
                            
                            <div class="space-y-4">
                                <div>
                                    <label for="address" class="block text-sm font-medium text-gray-700 mb-2">Street Address *</label>
                                    <textarea id="address" name="address" rows="3" required 
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                              placeholder="House/Flat No, Street Name, Area">{{ old('address') }}</textarea>
                                    @error('address')
                                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                                    @enderror
                                </div>
                                
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    <div>
                                        <label for="shipping_area" class="block text-sm font-medium text-gray-700 mb-2">City *</label>
                                        <select id="shipping_area" name="shipping_area" required 
                                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                            <option value="">Select City</option>
                                            <option value="Dhaka" {{ old('shipping_area') == 'Dhaka' ? 'selected' : '' }}>Dhaka</option>
                                            <option value="Chittagong" {{ old('shipping_area') == 'Chittagong' ? 'selected' : '' }}>Chittagong</option>
                                            <option value="Sylhet" {{ old('shipping_area') == 'Sylhet' ? 'selected' : '' }}>Sylhet</option>
                                            <option value="Rajshahi" {{ old('shipping_area') == 'Rajshahi' ? 'selected' : '' }}>Rajshahi</option>
                                            <option value="Khulna" {{ old('shipping_area') == 'Khulna' ? 'selected' : '' }}>Khulna</option>
                                            <option value="Barisal" {{ old('shipping_area') == 'Barisal' ? 'selected' : '' }}>Barisal</option>
                                            <option value="Rangpur" {{ old('shipping_area') == 'Rangpur' ? 'selected' : '' }}>Rangpur</option>
                                            <option value="Mymensingh" {{ old('shipping_area') == 'Mymensingh' ? 'selected' : '' }}>Mymensingh</option>
                                        </select>
                                        @error('shipping_area')
                                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                                        @enderror
                                        <p id="delivery-info" class="text-sm text-gray-500 mt-1"></p>
                                    </div>
                                    
                                    <div>
                                        <label for="postal_code" class="block text-sm font-medium text-gray-700 mb-2">Postal Code</label>
                                        <input type="text" id="postal_code" name="postal_code" 
                                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                               value="{{ old('postal_code') }}">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Payment Method -->
                        <div class="bg-white p-6 rounded-lg shadow-md">
                            <h2 class="text-xl font-semibold text-gray-900 mb-4">Payment Method</h2>
                            
                            <div class="space-y-3 payment-methods">
                                <label class="flex items-center p-4 border border-gray-300 rounded-lg hover:bg-gray-50 cursor-pointer">
                                    <input type="radio" name="payment_method" value="cash_on_delivery" 
                                           class="mr-3 text-blue-600 focus:ring-blue-500" checked>
                                    <div class="flex items-center">
                                        <span class="text-2xl mr-3">💰</span>
                                        <div>
                                            <div class="font-medium">Cash on Delivery</div>
                                            <div class="text-sm text-gray-600">Pay when your order arrives</div>
                                        </div>
                                    </div>
                                </label>
                                
                                <label class="flex items-center p-4 border border-gray-300 rounded-lg hover:bg-gray-50 cursor-pointer opacity-50">
                                    <input type="radio" name="payment_method" value="bkash" 
                                           class="mr-3 text-blue-600 focus:ring-blue-500" disabled>
                                    <div class="flex items-center">
                                        <span class="text-2xl mr-3">📱</span>
                                        <div>
                                            <div class="font-medium">bKash</div>
                                            <div class="text-sm text-gray-600">Coming soon</div>
                                        </div>
                                    </div>
                                </label>
                                
                                <label class="flex items-center p-4 border border-gray-300 rounded-lg hover:bg-gray-50 cursor-pointer opacity-50">
                                    <input type="radio" name="payment_method" value="nagad" 
                                           class="mr-3 text-blue-600 focus:ring-blue-500" disabled>
                                    <div class="flex items-center">
                                        <span class="text-2xl mr-3">💳</span>
                                        <div>
                                            <div class="font-medium">Nagad</div>
                                            <div class="text-sm text-gray-600">Coming soon</div>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>

                        <!-- Special Instructions -->
                        <div class="bg-white p-6 rounded-lg shadow-md">
                            <h2 class="text-xl font-semibold text-gray-900 mb-4">Special Instructions</h2>
                            <textarea name="note" rows="3" 
                                      class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                      placeholder="Any special instructions for delivery (optional)">{{ old('note') }}</textarea>
                        </div>
                    </div>

                    <!-- Order Summary -->
                    <div class="lg:col-span-1">
                        <div class="bg-white p-6 rounded-lg shadow-md sticky top-8">
                            <h2 class="text-xl font-semibold text-gray-900 mb-4">Order Summary</h2>
                            
                            <!-- Order Items -->
                            <div class="space-y-3 mb-6">
                                @foreach($cartItems as $item)
                                    <div class="flex items-center space-x-3">
                                        <div class="flex-shrink-0">
                                            @if($item['product']->images && count($item['product']->images) > 0)
                                                <img src="{{ storage_url($item['product']->images[0]) }}" alt="{{ $item['product']->name }}" 
                                                     class="w-12 h-12 object-cover rounded">
                                            @else
                                                <div class="w-12 h-12 bg-gray-200 rounded flex items-center justify-center">
                                                    <span class="text-lg">🐟</span>
                                                </div>
                                            @endif
                                        </div>
                                        <div class="flex-grow">
                                            <h4 class="font-medium text-gray-900 text-sm">{{ $item['product']->name }}</h4>
                                            @if(!empty($item['variant']['label']))
                                                <p class="text-xs font-semibold text-gray-700">
                                                    <strong>পণ্যের ধরন:</strong> {{ $item['variant']['label'] }}
                                                    <br />ইউনিট রেট: ৳{{ number_format($item['variant']['base_unit_price'] ?? $item['price'] ?? $item['product']->price, 0) }}/{{ $item['variant']['unit'] ?? $item['product']->unit ?? 'kg' }}
                                                    <br />ফাইনাল সেলিং প্রাইস: ৳{{ number_format($item['price'] ?? $item['product']->price, 0) }}
                                                    <!-- @if(!empty($item['variant']['sale_price']))
                                                        <br />সেল: ৳{{ number_format($item['variant']['sale_price'], 0) }}
                                                    @endif -->
                                                </p>
                                            @endif
                                            <p class="text-xs text-gray-600">{{ $item['quantity'] }} × ৳{{ number_format($item['price'] ?? $item['product']->price, 0) }}/{{ $item['variant']['unit'] ?? $item['product']->unit ?? 'kg' }}</p>
                                            @if(!empty($item['services']) && count($item['services']) > 0)
                                                <div class="mt-1 space-y-0.5">
                                                    @foreach($item['services'] as $service)
                                                        <p class="text-xs text-blue-600">{{ $service['name'] ?? 'Service #' . $service['id'] }}: ৳{{ number_format($service['resolved_price'] * $item['quantity'], 0) }}</p>
                                                    @endforeach
                                                </div>
                                            @endif
                                        </div>
                                        <div class="text-sm font-medium">
                                            @php
                                                $itemTotal = ($item['price'] ?? $item['product']->price) * $item['quantity'];
                                                $itemServiceTotal = collect($item['services'] ?? [])->sum(fn($s) => $s['resolved_price'] * $item['quantity']);
                                            @endphp
                                            ৳{{ number_format($itemTotal + $itemServiceTotal, 0) }}
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                            
                            <!-- Pricing Breakdown -->
                            <div class="space-y-2 mb-4 border-t border-gray-200 pt-4">
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-600">Subtotal ({{ $cartCount }} items)</span>
                                    <span class="font-medium">৳{{ number_format($subtotal, 0) }}</span>
                                </div>
                                @if($servicesTotal > 0)
                                    <div class="flex justify-between text-sm">
                                        <span class="text-gray-600">Additional Services</span>
                                        <span class="font-medium">৳{{ number_format($servicesTotal, 0) }}</span>
                                    </div>
                                @endif
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-600">Delivery Fee</span>
                                    <span class="font-medium">
                                        @if(calculate_delivery_fee($subtotal) == 0)
                                            <span class="text-green-600">Free</span>
                                        @else
                                            ৳{{ number_format(calculate_delivery_fee($subtotal), 0) }}
                                        @endif
                                    </span>
                                </div>
                                @if(free_delivery_enabled() && $subtotal < free_delivery_minimum())
                                    <div class="text-xs text-orange-600 bg-orange-50 p-2 rounded">
                                        💡 Add ৳{{ number_format(free_delivery_minimum() - $subtotal, 0) }} more for free delivery!
                                    </div>
                                @endif
                            </div>
                            
                            <div class="border-t border-gray-200 pt-4 mb-6">
                                <div class="flex justify-between">
                                    <span class="text-lg font-semibold text-gray-900">Total</span>
                                    <span class="text-xl font-bold text-blue-600">
                                        ৳{{ number_format($subtotal + $servicesTotal + calculate_delivery_fee($subtotal), 0) }}
                                    </span>
                                </div>
                            </div>

                            <!-- Place Order Button -->
                            <button type="submit" id="place-order-btn"
                                    class="w-full bg-blue-600 text-white py-3 px-4 rounded-lg font-semibold hover:bg-blue-700 transition-colors">
                                Place Order
                            </button>

                            <!-- Security Info -->
                            <div class="mt-6 pt-6 border-t border-gray-200">
                                <div class="space-y-2 text-sm text-gray-600">
                                    <div class="flex items-center">
                                        <svg class="w-4 h-4 mr-2 text-green-500" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M2.166 4.999A11.954 11.954 0 0010 1.944 11.954 11.954 0 0017.834 5c.11.65.166 1.32.166 2.001 0 5.225-3.34 9.67-8 11.317C5.34 16.67 2 12.225 2 7c0-.682.057-1.35.166-2.001zm11.541 3.708a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                                        </svg>
                                        Your order is secure
                                    </div>
                                    <div class="flex items-center">
                                        <svg class="w-4 h-4 mr-2 text-blue-500" fill="currentColor" viewBox="0 0 20 20">
                                            <path d="M2.003 5.884L10 9.882l7.997-3.998A2 2 0 0016 4H4a2 2 0 00-1.997 1.884z"></path>
                                            <path d="M18 8.118l-8 4-8-4V14a2 2 0 002 2h12a2 2 0 002-2V8.118z"></path>
                                        </svg>
                                        SMS confirmation sent
                                    </div>
                                    <div class="flex items-center">
                                        <svg class="w-4 h-4 mr-2 text-green-500" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clip-rule="evenodd"></path>
                                        </svg>
                                        Easy returns
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        @else
            <!-- Empty Cart -->
            <div class="text-center py-16">
                <div class="text-8xl mb-6">🛒</div>
                <h2 class="text-2xl font-semibold text-gray-900 mb-4">Your cart is empty</h2>
                <p class="text-gray-600 mb-8">Add some fish to your cart before checkout.</p>
                <a href="{{ route('shop.products') }}" 
                   class="bg-blue-600 text-white px-8 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors">
                    Start Shopping
                </a>
            </div>
        @endif
    </div>

    <script>
        document.getElementById('checkout-form').addEventListener('submit', function(e) {
            console.log('Form submission started');
            
            // Basic form validation
            const requiredFields = ['name', 'phone', 'address', 'shipping_area'];
            let isValid = true;
            let errorMessage = '';
            let validationErrors = [];

            // Clear previous error messages
            document.querySelectorAll('.error-message').forEach(el => el.remove());

            // Check required fields
            requiredFields.forEach(fieldName => {
                const field = document.querySelector(`[name="${fieldName}"]`);
                const fieldValue = field ? field.value.trim() : '';
                console.log(`Checking field: ${fieldName}, element found: ${!!field}, value: "${fieldValue}"`);
                
                if (!field) {
                    console.error(`Field not found: ${fieldName}`);
                    validationErrors.push(`Field ${fieldName} not found in form`);
                    isValid = false;
                } else if (!fieldValue) {
                    isValid = false;
                    validationErrors.push(`${fieldName} is empty`);
                    errorMessage += `${fieldName.replace('_', ' ').toUpperCase()} is required.\n`;
                    
                    // Add visual error indicator
                    field.classList.add('border-red-500');
                    const errorDiv = document.createElement('p');
                    errorDiv.className = 'text-red-500 text-sm mt-1 error-message';
                    errorDiv.textContent = `${fieldName.replace('_', ' ').toUpperCase()} is required`;
                    field.parentNode.appendChild(errorDiv);
                } else {
                    // Remove error styling if field is valid
                    field.classList.remove('border-red-500');
                    console.log(`Field ${fieldName} is valid with value: "${fieldValue}"`);
                }
            });

            // Check phone number format for Bangladesh
            const phoneField = document.querySelector('[name="phone"]');
            if (phoneField && phoneField.value.trim()) {
                const phoneValue = phoneField.value.trim();
                const phonePattern = /^01[3-9][0-9]{8}$/;
                console.log(`Checking phone: "${phoneValue}", matches pattern: ${phonePattern.test(phoneValue)}`);
                
                if (!phonePattern.test(phoneValue)) {
                    isValid = false;
                    validationErrors.push(`Invalid phone format: ${phoneValue}`);
                    phoneField.classList.add('border-red-500');
                    const errorDiv = document.createElement('p');
                    errorDiv.className = 'text-red-500 text-sm mt-1 error-message';
                    errorDiv.textContent = 'Please enter a valid Bangladesh phone number (01XXXXXXXXX)';
                    phoneField.parentNode.appendChild(errorDiv);
                } else {
                    phoneField.classList.remove('border-red-500');
                }
            }

            // Check payment method selection
            const paymentMethod = document.querySelector('input[name="payment_method"]:checked');
            console.log('Payment method selected:', paymentMethod ? paymentMethod.value : 'none');
            console.log('Available payment methods:', document.querySelectorAll('input[name="payment_method"]').length);
            
            if (!paymentMethod) {
                isValid = false;
                validationErrors.push('No payment method selected');
                const paymentSection = document.querySelector('.space-y-4:last-of-type'); // Payment methods container
                if (paymentSection) {
                    const errorDiv = document.createElement('p');
                    errorDiv.className = 'text-red-500 text-sm mt-1 error-message';
                    errorDiv.textContent = 'Please select a payment method';
                    paymentSection.appendChild(errorDiv);
                }
            }

            console.log('Validation result:', isValid);
            console.log('Validation errors:', validationErrors);

            if (!isValid) {
                e.preventDefault();
                console.log('Form prevented due to validation errors:', validationErrors);
                
                if (validationErrors.length > 0) {
                    showToast('Please fix the errors: ' + validationErrors.join(', '), 'error');
                } else {
                    showToast('Please fix the errors above and try again.', 'error');
                }
                
                // Reset button state
                const btn = document.getElementById('place-order-btn');
                btn.disabled = false;
                btn.textContent = 'Place Order';
                btn.classList.remove('opacity-50');
                return false;
            }

            // If validation passes, update button state
            const btn = document.getElementById('place-order-btn');
            btn.disabled = true;
            btn.textContent = 'Processing Order...';
            btn.classList.add('opacity-50');

            console.log('Form validation passed, submitting...');
            // Let the form submit naturally
        });

        // City-based delivery estimation
        document.getElementById('shipping_area').addEventListener('change', function() {
            const city = this.value;
            const deliveryInfo = document.getElementById('delivery-info');
            
            if (city === 'Dhaka') {
                deliveryInfo.textContent = 'Same day delivery available (order before 2 PM)';
                deliveryInfo.className = 'text-sm text-green-600 mt-1';
            } else if (city) {
                deliveryInfo.textContent = 'Next day delivery';
                deliveryInfo.className = 'text-sm text-blue-600 mt-1';
            } else {
                deliveryInfo.textContent = '';
            }
        });
    </script>
</x-shop-layout>