<?php $__env->startSection('title', 'Checkout'); ?>

<?php $__env->startSection('content'); ?>
<!-- Sticky Header - Full Width -->
<div class="sticky top-0 bg-white dark:bg-gray-900 z-10 border-b border-gray-200 dark:border-gray-700 mb-4 sm:mb-6" style="margin-top: -1.5rem;">
    <div class="max-w-2xl mx-auto px-3 sm:px-4 py-3 flex items-center justify-between">
        <h1 class="text-xl sm:text-2xl font-bold">Checkout</h1>
        <a href="<?php echo e(route('orders.index')); ?>" class="text-sm sm:text-base text-blue-600 hover:text-blue-700 dark:text-blue-400 font-medium">
            ← Orders
        </a>
    </div>
</div>

<!-- Mobile-optimized checkout page -->
<div class="max-w-2xl mx-auto px-3 sm:px-4 pb-24" x-data="orderForm()">

    <form id="checkoutForm" method="POST" action="<?php echo e(route('checkout.store')); ?>" class="space-y-6">
        <?php echo csrf_field(); ?>

        <!-- Customer Information -->
        <div class="bg-white dark:bg-gray-800 shadow-sm rounded-lg p-5 border border-gray-200 dark:border-gray-700">
            <h2 class="text-lg font-bold mb-4 pb-3 border-b border-gray-100 dark:border-gray-700 text-gray-900 dark:text-white">Customer Information</h2>

            <div class="space-y-3">
                <!-- Phone Number - First for Auto-fill -->
                <div>
                    <input type="tel" id="billing_phone" name="billing_phone" required
                           inputmode="tel"
                           class="w-full rounded-lg border border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 placeholder:text-gray-400 transition-all"
                           value="<?php echo e(old('billing_phone')); ?>"
                           placeholder="Phone Number (e.g. 012-3456789)">
                    <p id="customer-autofill-status" class="text-xs mt-1.5 hidden font-medium"></p>
                    <?php $__errorArgs = ['billing_phone'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <p class="text-red-500 text-sm mt-1"><?php echo e($message); ?></p>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                <input type="text" id="billing_full_name" name="billing_full_name" required
                       class="w-full rounded-lg border border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 placeholder:text-gray-400 transition-all uppercase"
                       style="text-transform: uppercase;"
                       value="<?php echo e(old('billing_full_name')); ?>"
                       placeholder="Full Name">
                <?php $__errorArgs = ['billing_full_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                    <p class="text-red-500 text-sm mt-1"><?php echo e($message); ?></p>
                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>

                <input type="email" id="billing_email" name="billing_email"
                       inputmode="email"
                       class="w-full rounded-lg border border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 placeholder:text-gray-400 transition-all"
                       value="<?php echo e(old('billing_email')); ?>"
                       placeholder="Email (Optional)">
                <?php $__errorArgs = ['billing_email'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                    <p class="text-red-500 text-sm mt-1"><?php echo e($message); ?></p>
                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>

                <textarea id="billing_address_1" name="billing_address_1" required rows="3"
                       class="w-full rounded-lg border border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 leading-relaxed placeholder:text-gray-400 transition-all uppercase"
                       style="text-transform: uppercase;"
                       placeholder="Full Address"><?php echo e(old('billing_address_1')); ?></textarea>
                <?php $__errorArgs = ['billing_address_1'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                    <p class="text-red-500 text-sm mt-1"><?php echo e($message); ?></p>
                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>

                <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg border border-gray-200 dark:border-gray-600">
                    <div class="space-y-3">
                        <div>
                            <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Postcode</label>
                            <input type="text" name="billing_postcode" required
                                   inputmode="numeric"
                                   pattern="[0-9]{5}"
                                   maxlength="5"
                                   @input="lookupPostcode($event.target.value)"
                                   x-ref="postcodeInput"
                                   class="w-full rounded-lg border border-gray-300 dark:border-gray-500 dark:bg-gray-600 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-base py-3 px-4 font-medium placeholder:text-gray-400 transition-all"
                                   value="<?php echo e(old('billing_postcode')); ?>"
                                   placeholder="e.g. 50000">
                            <p id="postcode-status" class="text-xs mt-1.5 hidden font-medium"></p>
                            <p x-show="postcodeLoading" class="text-xs text-blue-500 mt-1.5 font-medium flex items-center gap-1">
                                <svg class="animate-spin h-3 w-3" fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                                Looking up...
                            </p>
                            <?php $__errorArgs = ['billing_postcode'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <p class="text-red-500 text-xs mt-1.5"><?php echo e($message); ?></p>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div>
                            <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">City</label>
                            <input type="text" name="billing_city" required
                                   x-ref="cityInput"
                                   class="w-full rounded-lg border border-gray-200 dark:border-gray-500 bg-gray-100 dark:bg-gray-600 text-base py-3 px-4 font-medium text-gray-700 dark:text-gray-300 placeholder:text-gray-400"
                                   value="<?php echo e(old('billing_city')); ?>"
                                   placeholder="Auto-filled">
                            <?php $__errorArgs = ['billing_city'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <p class="text-red-500 text-xs mt-1.5"><?php echo e($message); ?></p>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div>
                            <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">State</label>
                            <select name="billing_state" required
                                    x-ref="stateSelect"
                                    @change="updateShippingRate($event.target.value)"
                                    class="w-full rounded-lg border border-gray-200 dark:border-gray-500 bg-gray-100 dark:bg-gray-600 text-base py-3 px-4 font-medium text-gray-700 dark:text-gray-300">
                                <option value="">Auto-filled</option>
                                <option value="Johor" <?php echo e(old('billing_state') == 'Johor' ? 'selected' : ''); ?>>Johor</option>
                                <option value="Kedah" <?php echo e(old('billing_state') == 'Kedah' ? 'selected' : ''); ?>>Kedah</option>
                                <option value="Kelantan" <?php echo e(old('billing_state') == 'Kelantan' ? 'selected' : ''); ?>>Kelantan</option>
                                <option value="Melaka" <?php echo e(old('billing_state') == 'Melaka' ? 'selected' : ''); ?>>Melaka</option>
                                <option value="Negeri Sembilan" <?php echo e(old('billing_state') == 'Negeri Sembilan' ? 'selected' : ''); ?>>Negeri Sembilan</option>
                                <option value="Pahang" <?php echo e(old('billing_state') == 'Pahang' ? 'selected' : ''); ?>>Pahang</option>
                                <option value="Pulau Pinang" <?php echo e(old('billing_state') == 'Pulau Pinang' ? 'selected' : ''); ?>>Pulau Pinang</option>
                                <option value="Perak" <?php echo e(old('billing_state') == 'Perak' ? 'selected' : ''); ?>>Perak</option>
                                <option value="Perlis" <?php echo e(old('billing_state') == 'Perlis' ? 'selected' : ''); ?>>Perlis</option>
                                <option value="Sabah" <?php echo e(old('billing_state') == 'Sabah' ? 'selected' : ''); ?>>Sabah</option>
                                <option value="Sarawak" <?php echo e(old('billing_state') == 'Sarawak' ? 'selected' : ''); ?>>Sarawak</option>
                                <option value="Selangor" <?php echo e(old('billing_state') == 'Selangor' ? 'selected' : ''); ?>>Selangor</option>
                                <option value="Terengganu" <?php echo e(old('billing_state') == 'Terengganu' ? 'selected' : ''); ?>>Terengganu</option>
                                <option value="Wp Kuala Lumpur" <?php echo e(old('billing_state') == 'Wp Kuala Lumpur' ? 'selected' : ''); ?>>Kuala Lumpur</option>
                                <option value="Wp Labuan" <?php echo e(old('billing_state') == 'Wp Labuan' ? 'selected' : ''); ?>>Labuan</option>
                                <option value="Wp Putrajaya" <?php echo e(old('billing_state') == 'Wp Putrajaya' ? 'selected' : ''); ?>>Putrajaya</option>
                            </select>
                            <?php $__errorArgs = ['billing_state'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <p class="text-red-500 text-xs mt-1.5"><?php echo e($message); ?></p>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Products Selection - Checkbox List -->
        <div class="bg-white dark:bg-gray-800 shadow-sm rounded-lg p-4 sm:p-6">
            <h2 class="text-base sm:text-lg font-semibold mb-4 flex items-center gap-2 text-gray-900 dark:text-white">
                <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="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"/>
                </svg>
                Select Products
            </h2>

            <!-- Search box -->
            <div class="mb-4">
                <input type="text"
                       x-model="searchQuery"
                       placeholder="Search products..."
                       class="w-full h-12 px-4 text-base rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 shadow-sm focus:border-blue-500 focus:ring-blue-500">
            </div>

            <!-- Product List -->
            <div class="space-y-1 border border-gray-200 dark:border-gray-600 rounded-lg overflow-y-auto" style="max-height: 1000px;">
                <template x-for="product in filteredProducts" :key="product.id">
                    <div @click="toggleProduct(product.id)"
                         :class="selectedProducts[product.id] ? 'bg-blue-50 dark:bg-blue-900/20 border-blue-500' : 'bg-white dark:bg-gray-800 border-transparent hover:bg-gray-50 dark:hover:bg-gray-700'"
                         class="flex items-center gap-2 px-2 py-1 border-l-4 cursor-pointer transition-colors">
                        <!-- Checkbox -->
                        <input type="checkbox"
                               :checked="selectedProducts[product.id]"
                               @click.stop="toggleProduct(product.id)"
                               class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500 flex-shrink-0">

                        <!-- Product Info -->
                        <div class="flex-1 min-w-0">
                            <div class="text-sm font-medium text-gray-900 dark:text-white truncate" x-text="product.name"></div>
                            <div class="text-xs text-gray-500 dark:text-gray-400" x-text="'RM ' + parseFloat(product.price).toFixed(2)"></div>
                        </div>

                        <!-- Quantity Input - Compact -->
                        <div x-show="selectedProducts[product.id]" class="flex items-center gap-0.5 flex-shrink-0">
                            <button type="button"
                                    @click.stop="decrementQuantity(product.id)"
                                    class="w-6 h-6 flex items-center justify-center bg-gray-200 dark:bg-gray-600 rounded hover:bg-gray-300 dark:hover:bg-gray-500">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"/>
                                </svg>
                            </button>
                            <input type="number"
                                   :value="productQuantities[product.id] || 1"
                                   @input="updateQuantity(product.id, $event.target.value)"
                                   @click.stop
                                   min="1"
                                   class="w-10 h-6 text-xs text-center border-gray-300 dark:border-gray-600 dark:bg-gray-700 rounded font-semibold">
                            <button type="button"
                                    @click.stop="incrementQuantity(product.id)"
                                    class="w-6 h-6 flex items-center justify-center bg-gray-200 dark:bg-gray-600 rounded hover:bg-gray-300 dark:hover:bg-gray-500">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                </template>
            </div>

            <!-- Hidden inputs for selected products -->
            <template x-for="(selected, productId) in selectedProducts" :key="'input-' + productId">
                <template x-if="selected">
                    <div>
                        <input type="hidden" :name="'line_items[' + productId + '][name]'" :value="getProductById(productId).name">
                        <input type="hidden" :name="'line_items[' + productId + '][sku]'" :value="getProductById(productId).sku">
                        <input type="hidden" :name="'line_items[' + productId + '][quantity]'" :value="productQuantities[productId] || 1">
                        <input type="hidden" :name="'line_items[' + productId + '][price]'" :value="getProductById(productId).price">
                    </div>
                </template>
            </template>
        </div>

        <!-- Order Summary -->
        <div class="bg-white dark:bg-gray-800 shadow-sm rounded-lg p-4 sm:p-6" x-show="Object.values(selectedProducts).some(v => v)">
            <h2 class="text-base sm:text-lg font-semibold mb-4 flex items-center gap-2 text-gray-900 dark:text-white">
                <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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                </svg>
                Order Summary
            </h2>

            <div class="space-y-2">
                <template x-for="(selected, productId) in selectedProducts" :key="'summary-' + productId">
                    <div x-show="selected" class="flex justify-between items-center py-2 border-b border-gray-200 dark:border-gray-700">
                        <div class="flex-1">
                            <div class="font-medium text-gray-900 dark:text-white" x-text="getProductById(productId).name"></div>
                            <div class="text-sm text-gray-500 dark:text-gray-400">
                                <span x-text="productQuantities[productId] || 1"></span>
                                <span> × RM </span>
                                <span x-text="parseFloat(getProductById(productId).price).toFixed(2)"></span>
                            </div>
                        </div>
                        <div class="font-semibold text-gray-900 dark:text-white"
                             x-text="'RM ' + ((productQuantities[productId] || 1) * parseFloat(getProductById(productId).price)).toFixed(2)">
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- Payment & Shipping - Mobile Optimized -->
        <div class="bg-white dark:bg-gray-800 shadow-sm rounded-lg p-4 sm:p-6">
            <h2 class="text-base sm:text-lg font-semibold mb-4 flex items-center gap-2 text-gray-900 dark:text-white">
                <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="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z"/>
                </svg>
                Payment & Shipping
            </h2>

            <div class="space-y-4">
                <!-- Payment Method -->
                <div>
                    <label class="block text-base font-medium mb-2 text-gray-700 dark:text-gray-300">Payment Method <span class="text-red-500">*</span></label>
                    <select name="payment_method" required
                            @change="updateShippingByPayment($event.target.value)"
                            class="w-full h-12 px-4 text-base rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                        <option value="">Select Payment</option>
                        <option value="cod" <?php echo e(old('payment_method') == 'cod' ? 'selected' : ''); ?>>COD</option>
                        <option value="bayarcash-wc" <?php echo e(old('payment_method') == 'bayarcash-wc' ? 'selected' : ''); ?>>Online Banking</option>
                        <option value="duitnowqr-wc" <?php echo e(old('payment_method') == 'duitnowqr-wc' ? 'selected' : ''); ?>>DuitNow QR</option>
                        <option value="bank_transfer" <?php echo e(old('payment_method') == 'bank_transfer' ? 'selected' : ''); ?>>Bank Transfer</option>
                    </select>
                    <?php $__errorArgs = ['payment_method'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <p class="text-red-500 text-sm mt-1"><?php echo e($message); ?></p>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                <!-- Shipping and Discount - 2 Column -->
                <div class="grid grid-cols-2 gap-3">
                    <!-- Shipping Cost -->
                    <div>
                        <label class="block text-base font-medium mb-2 text-gray-700 dark:text-gray-300">Shipping (RM) <span class="text-red-500">*</span></label>
                        <input type="number" name="shipping_total" required min="0" step="0.01"
                               inputmode="decimal"
                               x-model="shipping"
                               @input="calculateTotals"
                               class="w-full h-12 px-4 text-base text-center font-semibold rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                               value="<?php echo e(old('shipping_total', '0.00')); ?>">
                        <?php $__errorArgs = ['shipping_total'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="text-red-500 text-sm mt-1"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- Discount -->
                    <div>
                        <label class="block text-base font-medium mb-2 text-gray-500 dark:text-gray-400">Discount (RM)</label>
                        <input type="number" name="discount_total" min="0" step="0.01"
                               inputmode="decimal"
                               x-model="discount"
                               @input="calculateTotals"
                               class="w-full h-12 px-4 text-base text-center font-semibold rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                               value="<?php echo e(old('discount_total', '0.00')); ?>">
                    </div>
                </div>

                <!-- Order Summary - Prominent -->
                <div class="mt-4 bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-gray-700 dark:to-gray-700 rounded-xl p-4 border-2 border-blue-200 dark:border-gray-600">
                    <div class="space-y-2">
                        <div class="flex justify-between text-base">
                            <span class="text-gray-600 dark:text-gray-400">Subtotal:</span>
                            <span class="font-semibold" x-text="'RM ' + subtotal.toFixed(2)"></span>
                        </div>
                        <div class="flex justify-between text-base">
                            <span class="text-gray-600 dark:text-gray-400">Shipping:</span>
                            <span class="font-semibold" x-text="'RM ' + parseFloat(shipping || 0).toFixed(2)"></span>
                        </div>
                        <div class="flex justify-between text-base" x-show="discount > 0">
                            <span class="text-gray-600 dark:text-gray-400">Discount:</span>
                            <span class="font-semibold text-red-600" x-text="'- RM ' + parseFloat(discount || 0).toFixed(2)"></span>
                        </div>
                        <div class="flex justify-between pt-3 border-t-2 border-blue-300 dark:border-gray-600">
                            <span class="text-lg font-bold text-gray-900 dark:text-white">TOTAL:</span>
                            <span class="text-2xl font-bold text-blue-600 dark:text-blue-400" x-text="'RM ' + total.toFixed(2)"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Notes - Collapsible on Mobile -->
        <div class="bg-white dark:bg-gray-800 shadow-sm rounded-lg p-4 sm:p-6">
            <h2 class="text-base sm:text-lg font-semibold mb-3 flex items-center gap-2 text-gray-500 dark:text-gray-400">
                <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="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"/>
                </svg>
                Notes (optional)
            </h2>
            <textarea name="notes" rows="2"
                      class="w-full px-4 py-3 text-base rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                      placeholder="Add notes..."><?php echo e(old('notes')); ?></textarea>
        </div>

        <!-- Submit Buttons Section -->
        <!-- Desktop/Tablet Button - Shows on larger screens -->
        <div class="hidden md:flex items-center justify-end gap-3 mt-6 mb-4">
            <a href="<?php echo e(route('orders.index')); ?>"
               class="px-6 py-3 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors font-medium">
                Cancel
            </a>
            <button type="submit"
                    class="px-8 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white rounded-lg shadow-lg hover:shadow-xl transition-all font-bold text-lg flex items-center gap-2">
                <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="M5 13l4 4L19 7"/>
                </svg>
                Create Order
                <span class="ml-2 px-3 py-1 bg-white/20 rounded-lg text-sm font-semibold" x-text="'RM ' + total.toFixed(2)"></span>
            </button>
        </div>
    </form>
</div><!-- End Alpine.js x-data wrapper -->

<!-- Sticky Bottom Submit Button - Mobile/Tablet Only -->
    <div class="fixed bottom-0 left-0 right-0 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 p-4 shadow-xl md:hidden z-50">
        <button type="submit" form="checkoutForm"
                class="w-full h-14 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white rounded-xl shadow-lg font-bold text-lg flex items-center justify-center gap-2">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
            </svg>
            Create Order
            <span class="ml-2 px-3 py-1 bg-white/20 rounded-lg text-sm font-semibold" x-text="'RM ' + total.toFixed(2)"></span>
        </button>
    </div>

<?php $__env->startPush('scripts'); ?>
<script>
function orderForm() {
    return {
        products: [],
        selectedProducts: {}, // { productId: true/false }
        productQuantities: {}, // { productId: quantity }
        searchQuery: '',
        shipping: 0.00,
        discount: 0.00,
        subtotal: 0,
        total: 0,
        postcodeLoading: false,
        postcodeTimer: null,
        customerLookupTimer: null,
        // COD rates from admin settings
        codRateEastMalaysia: <?php echo e(\App\Models\SystemSetting::get('cod_rate_east_malaysia', '20.00')); ?>,
        codRatePeninsular: <?php echo e(\App\Models\SystemSetting::get('cod_rate_peninsular', '10.00')); ?>,
        // Track current payment method and state
        currentPaymentMethod: '',
        currentState: '',

        async init() {
            // Load all active products on page load
            await this.loadProducts();
            this.$watch('selectedProducts', () => this.calculateTotals(), { deep: true });
            this.$watch('productQuantities', () => this.calculateTotals(), { deep: true });
            this.calculateTotals();

            // Setup customer auto-fill on phone number input
            const phoneInput = document.getElementById('billing_phone');
            if (phoneInput) {
                phoneInput.addEventListener('input', (e) => this.lookupCustomer(e.target.value));
            }
        },

        updateShippingByPayment(paymentMethod) {
            this.currentPaymentMethod = paymentMethod;

            if (paymentMethod === 'cod') {
                // For COD, use state-based shipping
                if (this.currentState) {
                    this.updateShippingRate(this.currentState);
                } else {
                    // Default to peninsular rate if no state selected yet
                    this.shipping = this.codRatePeninsular;
                }
            } else if (paymentMethod) {
                // For other payment methods (Online Banking, DuitNow QR, Bank Transfer), shipping is free
                this.shipping = 0.00;
            }

            this.calculateTotals();
        },

        updateShippingRate(state) {
            this.currentState = state;

            // Only apply shipping charges if payment method is COD
            if (this.currentPaymentMethod === 'cod') {
                // East Malaysia and Labuan states
                const eastMalaysiaStates = ['Sabah', 'Sarawak', 'Wp Labuan'];

                if (eastMalaysiaStates.includes(state)) {
                    this.shipping = this.codRateEastMalaysia;
                } else if (state) {
                    this.shipping = this.codRatePeninsular;
                }
            } else if (this.currentPaymentMethod) {
                // Non-COD payments have free shipping
                this.shipping = 0.00;
            }

            this.calculateTotals();
        },

        get filteredProducts() {
            if (!this.searchQuery) {
                return this.products;
            }
            const query = this.searchQuery.toLowerCase();
            return this.products.filter(p =>
                p.name.toLowerCase().includes(query) ||
                (p.sku && p.sku.toLowerCase().includes(query))
            );
        },

        toggleProduct(productId) {
            this.selectedProducts[productId] = !this.selectedProducts[productId];
            if (this.selectedProducts[productId] && !this.productQuantities[productId]) {
                this.productQuantities[productId] = 1;
            }
        },

        updateQuantity(productId, value) {
            const qty = parseInt(value) || 1;
            this.productQuantities[productId] = Math.max(1, qty);
        },

        incrementQuantity(productId) {
            this.productQuantities[productId] = (this.productQuantities[productId] || 1) + 1;
        },

        decrementQuantity(productId) {
            const current = this.productQuantities[productId] || 1;
            this.productQuantities[productId] = Math.max(1, current - 1);
        },

        getProductById(productId) {
            return this.products.find(p => p.id == productId) || {};
        },

        lookupPostcode(postcode) {
            // Clear previous timer
            if (this.postcodeTimer) {
                clearTimeout(this.postcodeTimer);
            }

            // Remove non-numeric characters
            postcode = postcode.replace(/[^0-9]/g, '');

            // Only lookup if we have 5 digits
            if (postcode.length === 5) {
                this.postcodeTimer = setTimeout(() => {
                    this.fetchPostcodeData(postcode);
                }, 500); // Debounce 500ms
            }
        },

        async fetchPostcodeData(postcode) {
            this.postcodeLoading = true;

            try {
                const response = await fetch(`<?php echo e(route('postcode.lookup')); ?>?postcode=${postcode}`);
                const result = await response.json();

                if (result.success) {
                    // Auto-fill city and state
                    this.$refs.cityInput.value = result.data.city;
                    this.$refs.stateSelect.value = result.data.state;

                    // Update shipping rate based on state
                    this.updateShippingRate(result.data.state);

                    // Visual feedback
                    this.$refs.cityInput.classList.add('border-green-500');
                    this.$refs.stateSelect.classList.add('border-green-500');

                    setTimeout(() => {
                        this.$refs.cityInput.classList.remove('border-green-500');
                        this.$refs.stateSelect.classList.remove('border-green-500');
                    }, 2000);
                } else {
                    // Postcode not found - no error shown, user can fill manually
                    console.log('Postcode not found in database');
                }
            } catch (error) {
                console.error('Error looking up postcode:', error);
            } finally {
                this.postcodeLoading = false;
            }
        },

        lookupCustomer(phone) {
            // Clear previous timer
            if (this.customerLookupTimer) {
                clearTimeout(this.customerLookupTimer);
            }

            // Remove non-numeric characters except +
            phone = phone.replace(/[^0-9+]/g, '');

            // Only lookup if we have at least 10 digits
            const digitCount = phone.replace(/[^0-9]/g, '').length;
            if (digitCount >= 10) {
                this.customerLookupTimer = setTimeout(() => {
                    this.fetchCustomerData(phone);
                }, 500); // Debounce 500ms
            }
        },

        async fetchCustomerData(phone) {
            const statusEl = document.getElementById('customer-autofill-status');

            try {
                statusEl.textContent = 'Looking up customer...';
                statusEl.className = 'text-xs mt-1.5 font-medium text-blue-500';
                statusEl.classList.remove('hidden');

                console.log('Looking up customer with phone:', phone);

                const csrfToken = document.querySelector('meta[name="csrf-token"]');
                if (!csrfToken) {
                    console.error('CSRF token not found!');
                    statusEl.textContent = 'Error: CSRF token missing';
                    statusEl.className = 'text-xs mt-1.5 font-medium text-red-600';
                    return;
                }

                const response = await fetch('<?php echo e(route('customer.lookup')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken.content
                    },
                    body: JSON.stringify({ phone: phone })
                });

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

                const result = await response.json();
                console.log('API result:', result);

                if (result.found && result.customer) {
                    console.log('Customer found, auto-filling...');
                    console.log('Customer data:', result.customer);

                    // Auto-fill customer data
                    const nameField = document.getElementById('billing_full_name');
                    const emailField = document.getElementById('billing_email');
                    const addressField = document.getElementById('billing_address_1');

                    console.log('Name field found:', !!nameField, 'Value to set:', result.customer.name);
                    console.log('Email field found:', !!emailField, 'Value to set:', result.customer.email);
                    console.log('Address field found:', !!addressField, 'Value to set:', result.customer.address);

                    if (nameField) {
                        nameField.value = (result.customer.name || '').toUpperCase();
                        console.log('Name field value after set:', nameField.value);
                    }
                    if (emailField) {
                        emailField.value = result.customer.email || '';
                        console.log('Email field value after set:', emailField.value);
                    }
                    if (addressField) {
                        addressField.value = (result.customer.address || '').toUpperCase();
                        console.log('Address field value after set:', addressField.value);
                    }

                    if (this.$refs.cityInput) {
                        this.$refs.cityInput.value = result.customer.city || '';
                        console.log('City set to:', this.$refs.cityInput.value);
                    }
                    if (this.$refs.stateSelect) {
                        this.$refs.stateSelect.value = result.customer.state || '';
                        console.log('State set to:', this.$refs.stateSelect.value);
                    }
                    if (this.$refs.postcodeInput) {
                        this.$refs.postcodeInput.value = result.customer.postcode || '';
                        console.log('Postcode set to:', this.$refs.postcodeInput.value);
                    }

                    // Update shipping rate based on state
                    if (result.customer.state) {
                        this.updateShippingRate(result.customer.state);
                    }

                    // Visual feedback
                    statusEl.textContent = '✓ Customer found! Information auto-filled';
                    statusEl.className = 'text-xs mt-1.5 font-medium text-green-600';

                    setTimeout(() => {
                        statusEl.classList.add('hidden');
                    }, 3000);
                } else {
                    console.log('Customer not found or not authorized');
                    // Customer not found - hide status
                    statusEl.classList.add('hidden');
                }
            } catch (error) {
                console.error('Error looking up customer:', error);
                statusEl.textContent = 'Error: ' + error.message;
                statusEl.className = 'text-xs mt-1.5 font-medium text-red-600';

                setTimeout(() => {
                    statusEl.classList.add('hidden');
                }, 3000);
            }
        },

        async loadProducts() {
            try {
                const response = await fetch(`<?php echo e(route('products.search.api')); ?>?q=`);
                let products = await response.json();

                // Sort: bundles first (A-Z), then singles (A-Z)
                this.products = products.sort((a, b) => {
                    // If types are different, bundles come first
                    if (a.product_type !== b.product_type) {
                        return a.product_type === 'bundle' ? -1 : 1;
                    }
                    // If types are same, sort alphabetically by name
                    return a.name.localeCompare(b.name);
                });
            } catch (error) {
                console.error('Error loading products:', error);
            }
        },

        calculateTotals() {
            this.subtotal = 0;

            // Calculate subtotal from selected products
            Object.keys(this.selectedProducts).forEach(productId => {
                if (this.selectedProducts[productId]) {
                    const product = this.getProductById(productId);
                    const quantity = this.productQuantities[productId] || 1;
                    this.subtotal += parseFloat(product.price) * quantity;
                }
            });

            this.total = this.subtotal + parseFloat(this.shipping || 0) - parseFloat(this.discount || 0);
        }
    }
}
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\multistore\resources\views/checkout/index.blade.php ENDPATH**/ ?>