

<?php $__env->startSection('content'); ?>
    <?php ($defaultType = old('type', request('type'))); ?>
    <?php ($menuType = request('menu_type')); ?>
    <?php ($baseMenuQuery = collect(request()->query())->except('menu_type')->all()); ?>

    <div class="tablet-order-screen flex min-h-[calc(100vh-4rem)] flex-col gap-4">
        <div class="flex flex-wrap items-center justify-between gap-4">
            <div>
                <h2 class="text-2xl font-semibold text-slate-900">Buat Order</h2>
                <p class="text-sm text-slate-500">Pesan untuk pelanggan</p>
            </div>
            <?php if (isset($component)) { $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.button','data' => ['href' => ''.e(route('orders.index')).'','variant' => 'secondary']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['href' => ''.e(route('orders.index')).'','variant' => 'secondary']); ?>Kembali <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $attributes = $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
<?php if (isset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $component = $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
        </div>

        <form method="post" action="<?php echo e(route('orders.store')); ?>" id="order-form" class="grid gap-4 lg:grid-cols-3">
            <?php echo csrf_field(); ?>
            <div id="client-error" class="hidden rounded-lg border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700 lg:col-span-3"></div>
            <?php if (isset($component)) { $__componentOriginal53747ceb358d30c0105769f8471417f6 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal53747ceb358d30c0105769f8471417f6 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.card','data' => ['class' => 'space-y-4 lg:col-span-1']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('card'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['class' => 'space-y-4 lg:col-span-1']); ?>
                <h3 class="text-lg font-semibold text-slate-900">Header Order</h3>
                <div>
                    <label class="mb-2 block text-sm font-semibold text-slate-700">Type</label>
                    <div id="type-display" class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700">
                        <?php echo e($defaultType === 'dine_in' ? 'Dine In' : 'Take Away'); ?>

                    </div>
                    <input type="hidden" name="type" id="type-select" value="<?php echo e($defaultType); ?>">
                </div>
                <?php if (isset($component)) { $__componentOriginaled2cde6083938c436304f332ba96bb7c = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginaled2cde6083938c436304f332ba96bb7c = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.select','data' => ['name' => 'id_meja','label' => 'Meja','id' => 'meja-select','onchange' => 'handleMejaSelectChange()']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('select'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['name' => 'id_meja','label' => 'Meja','id' => 'meja-select','onchange' => 'handleMejaSelectChange()']); ?>
                    <option value="">Pilih Meja</option>
                    <?php $__currentLoopData = $mejas; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $meja): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php if($meja->is_occupied ?? false) continue; ?>
                        <option
                            value="<?php echo e($meja->id); ?>"
                            data-order-url="<?php echo e($meja->open_order_id ? route('orders.show', $meja->open_order_id) : ''); ?>"
                            <?php echo e(old('id_meja') == $meja->id ? 'selected' : ''); ?>

                        >
                            <?php echo e($meja->no_meja); ?>

                        </option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginaled2cde6083938c436304f332ba96bb7c)): ?>
<?php $attributes = $__attributesOriginaled2cde6083938c436304f332ba96bb7c; ?>
<?php unset($__attributesOriginaled2cde6083938c436304f332ba96bb7c); ?>
<?php endif; ?>
<?php if (isset($__componentOriginaled2cde6083938c436304f332ba96bb7c)): ?>
<?php $component = $__componentOriginaled2cde6083938c436304f332ba96bb7c; ?>
<?php unset($__componentOriginaled2cde6083938c436304f332ba96bb7c); ?>
<?php endif; ?>
                <div id="meja-tambahan-wrap" class="hidden">
                    <label for="meja-tambahan-select" class="mb-2 block text-sm font-semibold text-slate-700">Meja Tambahan (Opsional)</label>
                    <select id="meja-tambahan-select" multiple
                            class="block w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 focus:border-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-100">
                        <?php $__currentLoopData = $mejas; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $meja): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php if($meja->is_occupied ?? false) continue; ?>
                            <option value="<?php echo e($meja->id); ?>"><?php echo e($meja->no_meja); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    <input type="hidden" name="meja_tambahan" id="meja-tambahan-value" value="<?php echo e(old('meja_tambahan')); ?>">
                    <p class="mt-1 text-xs text-slate-500">Bisa pilih lebih dari 1 meja. Meja utama tidak bisa dipilih ulang.</p>
                </div>
                <?php if (isset($component)) { $__componentOriginaled2cde6083938c436304f332ba96bb7c = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginaled2cde6083938c436304f332ba96bb7c = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.select','data' => ['name' => 'id_waiters','label' => 'Waiter','required' => true]] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('select'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['name' => 'id_waiters','label' => 'Waiter','required' => true]); ?>
                    <option value="">Pilih Waiter</option>
                    <?php $__currentLoopData = $waiters; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $waiter): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($waiter->id); ?>" <?php echo e(old('id_waiters') == $waiter->id ? 'selected' : ''); ?>><?php echo e($waiter->nama); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginaled2cde6083938c436304f332ba96bb7c)): ?>
<?php $attributes = $__attributesOriginaled2cde6083938c436304f332ba96bb7c; ?>
<?php unset($__attributesOriginaled2cde6083938c436304f332ba96bb7c); ?>
<?php endif; ?>
<?php if (isset($__componentOriginaled2cde6083938c436304f332ba96bb7c)): ?>
<?php $component = $__componentOriginaled2cde6083938c436304f332ba96bb7c; ?>
<?php unset($__componentOriginaled2cde6083938c436304f332ba96bb7c); ?>
<?php endif; ?>
                <?php if (isset($component)) { $__componentOriginalc2fcfa88dc54fee60e0757a7e0572df1 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc2fcfa88dc54fee60e0757a7e0572df1 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.input','data' => ['name' => 'nama_pelanggan','label' => 'Nama Pelanggan','value' => old('nama_pelanggan')]] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('input'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['name' => 'nama_pelanggan','label' => 'Nama Pelanggan','value' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute(old('nama_pelanggan'))]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc2fcfa88dc54fee60e0757a7e0572df1)): ?>
<?php $attributes = $__attributesOriginalc2fcfa88dc54fee60e0757a7e0572df1; ?>
<?php unset($__attributesOriginalc2fcfa88dc54fee60e0757a7e0572df1); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc2fcfa88dc54fee60e0757a7e0572df1)): ?>
<?php $component = $__componentOriginalc2fcfa88dc54fee60e0757a7e0572df1; ?>
<?php unset($__componentOriginalc2fcfa88dc54fee60e0757a7e0572df1); ?>
<?php endif; ?>

                <div id="meja-cards" class="space-y-2">
                    <p class="text-sm font-semibold text-slate-700">Pilih Meja (Dine In)</p>
                    <div class="grid grid-cols-3 gap-2">
                        <?php $__currentLoopData = $mejas; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $meja): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php if($meja->is_occupied ?? false) continue; ?>
                            <?php ($cardClass = $meja->is_active
                                ? (($meja->is_occupied ?? false)
                                    ? 'bg-rose-100 text-rose-700 border-rose-200'
                                    : 'bg-emerald-100 text-emerald-700 border-emerald-200')
                                : 'bg-slate-100 text-slate-400 border-slate-200'); ?>
                            <button
                                type="button"
                                class="rounded-lg border px-3 py-2 text-sm font-semibold <?php echo e($cardClass); ?>"
                                data-id="<?php echo e($meja->id); ?>"
                                data-active="<?php echo e($meja->is_active ? '1' : '0'); ?>"
                                data-order-url="<?php echo e($meja->open_order_id ? route('orders.show', $meja->open_order_id) : ''); ?>"
                            >
                                <span><?php echo e($meja->no_meja); ?></span>
                                <span data-role-badge class="hidden rounded-full px-2 py-0.5 text-[10px] font-bold uppercase"></span>
                            </button>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                    <div class="flex gap-3 text-xs text-slate-500">
                        <span>Hijau: kosong</span>
                        <span>Biru: meja induk</span>
                        <span>Kuning: meja tambahan</span>
                        <span>Abu: nonaktif</span>
                    </div>
                    <p class="text-xs text-slate-500">Klik pertama jadi meja induk, klik meja lain untuk tambah/hapus meja tambahan.</p>
                </div>
             <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $attributes = $__attributesOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__attributesOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $component = $__componentOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__componentOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>

            <?php if (isset($component)) { $__componentOriginal53747ceb358d30c0105769f8471417f6 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal53747ceb358d30c0105769f8471417f6 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.card','data' => ['class' => 'flex min-h-0 flex-col gap-4 lg:col-span-2']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('card'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['class' => 'flex min-h-0 flex-col gap-4 lg:col-span-2']); ?>
                <h3 class="text-lg font-semibold text-slate-900">Item Pesanan</h3>

                <div class="flex flex-wrap items-center gap-3">
                    <div class="relative w-full max-w-xs">
                        <input id="menu-search" type="text" class="w-full rounded-lg border border-slate-200 px-3 py-2 pr-10 text-sm" placeholder="Cari menu..." value="<?php echo e($search ?? ''); ?>" autocomplete="off">
                        <button type="button" id="menu-search-clear" class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 <?php echo e(($search ?? '') ? '' : 'hidden'); ?>">&times;</button>
                    </div>
                    <div id="menu-filters" class="flex flex-wrap items-center gap-2 text-xs">
                        <a href="<?php echo e(route('orders.create', $baseMenuQuery)); ?>"
                           class="rounded-full border px-3 py-1 font-semibold <?php echo e($menuType ? 'border-slate-200 text-slate-500 hover:bg-slate-100' : 'border-slate-900 bg-slate-900 text-white'); ?>">
                            Semua
                        </a>
                        <?php $__currentLoopData = ['makanan' => 'Makanan', 'minuman' => 'Minuman', 'snack' => 'Snack']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <a href="<?php echo e(route('orders.create', array_merge($baseMenuQuery, ['menu_type' => $key, 'page' => 1]))); ?>"
                               class="rounded-full border px-3 py-1 font-semibold <?php echo e($menuType === $key ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-200 text-slate-500 hover:bg-slate-100'); ?>">
                                <?php echo e($label); ?>

                            </a>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                </div>

                <div id="menu-grid" class="tablet-order-menu grid flex-1 gap-3 overflow-y-auto pr-1 sm:grid-cols-2 xl:grid-cols-3 max-h-[45vh] lg:max-h-[36vh]">
                    <?php $__currentLoopData = $menus; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $menu): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <button
                            type="button"
                            class="flex gap-3 rounded-xl border border-slate-200 bg-white p-3 text-left transition hover:border-slate-300 hover:shadow-sm"
                            data-id="<?php echo e($menu->id); ?>"
                            data-name="<?php echo e($menu->nama); ?>"
                            data-price="<?php echo e($menu->harga_jual); ?>"
                            data-type="<?php echo e($menu->type_menu); ?>"
                            data-stand="<?php echo e($menu->stand?->nama ?? 'General'); ?>"
                            data-is-package="<?php echo e($menu->is_package ? '1' : '0'); ?>"
                        >
                            <div class="h-16 w-16 flex-shrink-0 overflow-hidden rounded-lg bg-slate-100">
                                <?php if($menu->image): ?>
                                    <img src="<?php echo e(asset('storage/' . $menu->image)); ?>" alt="<?php echo e($menu->nama); ?>" class="h-full w-full object-cover">
                                <?php else: ?>
                                    <div class="flex h-full w-full items-center justify-center text-xs text-slate-400">No Image</div>
                                <?php endif; ?>
                            </div>
                            <div class="flex-1">
                                <p class="text-sm font-semibold text-slate-900">
                                    <?php echo e($menu->nama); ?>

                                    <?php if($menu->is_package): ?>
                                        <span class="ml-1 inline-flex items-center rounded-full bg-sky-100 px-2 py-0.5 text-[10px] font-bold uppercase text-sky-700">Paket</span>
                                    <?php endif; ?>
                                </p>
                                <p class="text-xs text-slate-500"><?php echo e(ucfirst($menu->type_menu)); ?> | <?php echo e($menu->stand?->nama ?? 'General'); ?></p>
                                <p class="mt-2 text-sm font-semibold text-slate-700"><?php echo e(format_rupiah($menu->harga_jual)); ?></p>
                            </div>
                        </button>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
                <div class="flex items-center justify-center">
                    <?php echo e($menus->links()); ?>

                </div>

                <div class="flex min-h-0 flex-col gap-3 rounded-lg border border-slate-200 bg-slate-50 p-3">
                    <div class="flex items-center justify-between">
                        <h4 class="text-sm font-semibold text-slate-700">Cart</h4>
                        <span class="text-xs text-slate-500">Item: <span id="cart-count">0</span></span>
                    </div>
                    <div class="overflow-visible">
                        <?php if (isset($component)) { $__componentOriginal163c8ba6efb795223894d5ffef5034f5 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal163c8ba6efb795223894d5ffef5034f5 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.table','data' => []] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('table'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
                    <thead class="bg-slate-50 text-xs uppercase text-slate-500">
                        <tr>
                            <th class="px-4 py-3">Menu</th>
                            <th class="px-4 py-3 text-right">Qty</th>
                            <th class="px-4 py-3 text-right">Harga</th>
                            <th class="px-4 py-3 text-right">Subtotal</th>
                            <th class="px-4 py-3">Note</th>
                            <th class="px-4 py-3 text-right"></th>
                        </tr>
                    </thead>
                    <tbody id="cart-body">
                        <tr>
                            <td class="px-4 py-6 text-center text-slate-500" colspan="6">Belum ada item.</td>
                        </tr>
                    </tbody>
                         <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal163c8ba6efb795223894d5ffef5034f5)): ?>
<?php $attributes = $__attributesOriginal163c8ba6efb795223894d5ffef5034f5; ?>
<?php unset($__attributesOriginal163c8ba6efb795223894d5ffef5034f5); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal163c8ba6efb795223894d5ffef5034f5)): ?>
<?php $component = $__componentOriginal163c8ba6efb795223894d5ffef5034f5; ?>
<?php unset($__componentOriginal163c8ba6efb795223894d5ffef5034f5); ?>
<?php endif; ?>
                    </div>
                </div>

                <div class="flex items-center justify-between rounded-lg bg-slate-900 px-4 py-3 text-white">
                    <span class="text-sm">Grand Total</span>
                    <span id="grand-total" class="text-lg font-semibold">Rp 0</span>
                </div>

                <div id="items-inputs"></div>
                <input type="hidden" name="print_option" id="print-option" value="">

                <?php if (isset($component)) { $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.button','data' => ['type' => 'button','id' => 'open-submit-modal','class' => 'w-full py-3 text-base']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['type' => 'button','id' => 'open-submit-modal','class' => 'w-full py-3 text-base']); ?>Simpan Order <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $attributes = $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
<?php if (isset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $component = $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
             <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $attributes = $__attributesOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__attributesOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $component = $__componentOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__componentOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
        </form>
    </div>

    <div id="print-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-slate-900/60 p-4">
        <div class="w-full max-w-2xl rounded-2xl bg-white p-8 shadow-xl">
            <div class="flex items-center justify-between">
                <h3 class="text-lg font-semibold text-slate-900">Pilih Metode Print</h3>
                <button type="button" id="close-print-modal" class="text-slate-400 hover:text-slate-600">&times;</button>
            </div>
            <p class="mt-2 text-sm text-slate-500">Cetak berurutan: Nota lalu Stand.</p>
            <div class="mt-6 space-y-4">
                <div class="rounded-xl border border-slate-200 bg-slate-50 p-4">
                    <div id="print-step-label" class="mb-3 flex items-center gap-2 text-sm font-semibold text-slate-700">
                        <span id="print-step-badge" class="inline-flex h-6 w-6 items-center justify-center rounded-full bg-slate-900 text-xs text-white">1</span>
                        <span id="print-step-title">Print Nota Customer</span>
                    </div>
                    <button type="button" id="print-main-button" class="print-choice flex h-28 w-full flex-col items-center justify-center gap-2 rounded-xl border border-slate-200 bg-white text-sm font-semibold text-slate-700 shadow-sm transition hover:bg-slate-50">
                        <span class="text-base" id="print-main-title">Mulai Print Nota Customer'</span>
                        <span class="text-xs text-slate-500" id="print-main-desc">Cetak via perangkat tablet</span>
                    </button>
                </div>
            </div>
            <div class="mt-6 flex justify-between gap-3">
                <button type="button" id="prev-print-step" class="rounded-lg border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-50 hidden">Previous</button>
                <div class="flex items-center gap-3">
                    <button type="button" id="back-print" class="rounded-lg border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-50">Kembali</button>
                    <button type="button" id="confirm-print" class="rounded-lg bg-slate-300 px-4 py-2 text-sm font-semibold text-white" disabled>OK</button>
                </div>
            </div>
        </div>
    </div>

    <div id="note-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-slate-900/60 p-4">
        <div class="w-full max-w-lg rounded-xl bg-white p-6 shadow-lg">
            <div class="flex items-center justify-between">
                <h3 class="text-lg font-semibold text-slate-900">Catatan Item</h3>
                <button type="button" id="close-note" class="text-slate-400 hover:text-slate-600">&times;</button>
            </div>
            <textarea id="note-textarea" rows="5" class="mt-4 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700" placeholder="Tulis catatan untuk item..."></textarea>
            <div class="mt-4 flex justify-end gap-3">
                <?php if (isset($component)) { $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.button','data' => ['type' => 'button','variant' => 'secondary','id' => 'close-note-secondary']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['type' => 'button','variant' => 'secondary','id' => 'close-note-secondary']); ?>Batal <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $attributes = $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
<?php if (isset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $component = $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
                <?php if (isset($component)) { $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.button','data' => ['type' => 'button','id' => 'save-note']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['type' => 'button','id' => 'save-note']); ?>Simpan <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $attributes = $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
<?php if (isset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $component = $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        const menuSearch = document.getElementById('menu-search');
        const menuGrid = document.getElementById('menu-grid');
        const paginationWrap = menuGrid?.nextElementSibling;
        const cartBody = document.getElementById('cart-body');
        const grandTotalEl = document.getElementById('grand-total');
        const itemsInputs = document.getElementById('items-inputs');
        const printModal = document.getElementById('print-modal');
        const openSubmitModal = document.getElementById('open-submit-modal');
        const closePrintModal = document.getElementById('close-print-modal');
        const printOptionInput = document.getElementById('print-option');
        const orderForm = document.getElementById('order-form');
        const typeSelect = document.getElementById('type-select');
        const typeDisplay = document.getElementById('type-display');
        const mejaSelect = document.getElementById('meja-select');
        const mejaCards = document.getElementById('meja-cards');
        const mejaTambahanWrap = document.getElementById('meja-tambahan-wrap');
        const mejaTambahanSelect = document.getElementById('meja-tambahan-select');
        const mejaTambahanValue = document.getElementById('meja-tambahan-value');

        const storageKey = 'order_cart_items';
        const appName = <?php echo json_encode(app_setting('app_name', 'Foodcourt'), 512) ?>;
        const appLogoPath = <?php echo json_encode(app_setting('app_logo'), 15, 512) ?>;
        const appLogoUrl = appLogoPath ? "<?php echo e(asset('storage')); ?>/" + appLogoPath : '';
        const openOrderMap = <?php echo json_encode($mejas->mapWithKeys(fn ($m) => [$m->id => $m->open_order_id])->all(), 15, 512) ?>;
        const orderShowBaseUrl = <?php echo json_encode(url('/orders'), 15, 512) ?>;
        const items = [];
        const headerStorageKey = 'order_header_inputs';

        function formatRupiah(value) {
            return new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR',
                minimumFractionDigits: 0,
            }).format(value);
        }

        function appendHiddenInput(name, value) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = name;
            input.value = value;
            itemsInputs.appendChild(input);
        }

        function persistCart() {
            try {
                localStorage.setItem(storageKey, JSON.stringify(items));
            } catch (error) {
                // ignore storage errors
            }
        }

        function loadCart() {
            try {
                const raw = localStorage.getItem(storageKey);
                if (!raw) {
                    return;
                }
                const saved = JSON.parse(raw);
                if (Array.isArray(saved)) {
                    saved.forEach((item) => {
                                if (item && item.id && item.nama) {
                                    items.push({
                                        id: item.id,
                                        nama: item.nama,
                                        harga: parseFloat(item.harga || 0),
                                        qty: parseInt(item.qty || 1, 10),
                                        note: item.note || '',
                                        type_menu: item.type_menu || null,
                                        stand: item.stand || 'General',
                                        is_package: item.is_package === true || item.is_package === 1 || item.is_package === '1',
                                    });
                                }
                            });
                        }
            } catch (error) {
                // ignore parse errors
            }
        }

        function persistHeader() {
            const waiterSelect = document.querySelector('select[name="id_waiters"]');
            let previous = {};
            try {
                const raw = localStorage.getItem(headerStorageKey);
                previous = raw ? JSON.parse(raw) : {};
            } catch (error) {
                previous = {};
            }

            const currentWaiter = waiterSelect?.value || '';
            const headerState = {
                type: typeSelect.value || previous.type || '',
                id_meja: mejaSelect.value || previous.id_meja || '',
                meja_tambahan_ids: Array.from(mejaTambahanSelect?.selectedOptions ?? []).map((option) => option.value),
                id_waiters: currentWaiter || previous.id_waiters || '',
                nama_pelanggan: document.querySelector('input[name="nama_pelanggan"]')?.value || previous.nama_pelanggan || '',
            };
            try {
                localStorage.setItem(headerStorageKey, JSON.stringify(headerState));
            } catch (error) {
                // ignore storage errors
            }
        }

        function applyMejaSelection() {
            const primaryId = String(mejaSelect?.value || '');
            const tambahanIds = new Set(
                Array.from(mejaTambahanSelect?.selectedOptions ?? []).map((option) => String(option.value))
            );

            document.querySelectorAll('#meja-cards button').forEach((el) => {
                const cardId = String(el.dataset.id || '');
                const isPrimary = cardId === primaryId;
                const isTambahan = !isPrimary && tambahanIds.has(cardId);

                el.classList.remove('ring-2', 'ring-slate-900', 'ring-amber-400');
                if (isPrimary) {
                    el.classList.add('ring-2', 'ring-slate-900');
                } else if (isTambahan) {
                    el.classList.add('ring-2', 'ring-amber-400');
                }

                const badge = el.querySelector('[data-role-badge]');
                if (!badge) {
                    return;
                }
                badge.className = 'hidden rounded-full px-2 py-0.5 text-[10px] font-bold uppercase';
                badge.textContent = '';

                if (isPrimary) {
                    badge.textContent = 'Induk';
                    badge.classList.remove('hidden');
                    badge.classList.add('bg-slate-900', 'text-white');
                } else if (isTambahan) {
                    badge.textContent = 'Tambahan';
                    badge.classList.remove('hidden');
                    badge.classList.add('bg-amber-100', 'text-amber-700');
                }
            });
        }

        function syncSelect2(selectEl) {
            if (window.$ && $.fn.select2) {
                $(selectEl).trigger('change');
            } else {
                selectEl.dispatchEvent(new Event('change'));
            }
        }

        function updateMejaTambahanValue() {
            if (!mejaTambahanSelect || !mejaTambahanValue) {
                return;
            }
            const labels = Array.from(mejaTambahanSelect.selectedOptions)
                .map((option) => option.textContent.trim())
                .filter(Boolean);
            mejaTambahanValue.value = labels.join(', ');
        }

        function syncMejaTambahanOptions() {
            if (!mejaTambahanSelect) {
                return;
            }
            const primaryMejaId = String(mejaSelect?.value || '');
            Array.from(mejaTambahanSelect.options).forEach((option) => {
                const isPrimary = String(option.value) === primaryMejaId;
                option.disabled = isPrimary;
                if (isPrimary) {
                    option.selected = false;
                }
            });
            updateMejaTambahanValue();
        }

        function loadHeader() {
            try {
                const raw = localStorage.getItem(headerStorageKey);
                if (!raw) {
                    return;
                }
                const saved = JSON.parse(raw);
                if (!saved || typeof saved !== 'object') {
                    return;
                }
                const urlType = new URLSearchParams(window.location.search).get('type');
                if (urlType) {
                    typeSelect.value = urlType;
                } else if (saved.type) {
                    typeSelect.value = saved.type;
                }
                if (saved.id_meja) {
                    mejaSelect.value = saved.id_meja;
                    syncSelect2(mejaSelect);
                }
                if (Array.isArray(saved.meja_tambahan_ids) && mejaTambahanSelect) {
                    const selectedIds = new Set(saved.meja_tambahan_ids.map((id) => String(id)));
                    Array.from(mejaTambahanSelect.options).forEach((option) => {
                        option.selected = selectedIds.has(String(option.value));
                    });
                }
                const waiterSelect = document.querySelector('select[name="id_waiters"]');
                if (waiterSelect && saved.id_waiters) {
                    waiterSelect.value = saved.id_waiters;
                    syncSelect2(waiterSelect);
                }
                const namaInput = document.querySelector('input[name="nama_pelanggan"]');
                if (namaInput && saved.nama_pelanggan) {
                    namaInput.value = saved.nama_pelanggan;
                }
                if (urlType) {
                    persistHeader();
                }
            } catch (error) {
                // ignore parse errors
            }
        }

        function renderCart() {
            cartBody.innerHTML = '';
            itemsInputs.innerHTML = '';

            if (items.length === 0) {
                cartBody.innerHTML = `<tr><td class="px-4 py-6 text-center text-slate-500" colspan="6">Belum ada item.</td></tr>`;
                grandTotalEl.textContent = formatRupiah(0);
                document.getElementById('cart-count').textContent = '0';
                syncMenuHighlights();
                persistCart();
                return;
            }

            let total = 0;
            items.forEach((item, index) => {
                const subtotal = item.qty * item.harga;
                total += subtotal;
                const row = document.createElement('tr');
                row.className = 'border-b border-slate-100';
                const packageBadge = item.is_package
                    ? '<span class="ml-1 inline-flex items-center rounded-full bg-sky-100 px-2 py-0.5 text-[10px] font-bold uppercase text-sky-700">Paket</span>'
                    : '';
                row.innerHTML = `
                    <td class="px-4 py-3 font-medium text-slate-800">${item.nama}${packageBadge}</td>
                    <td class="px-4 py-3 text-right">
                        <div class="inline-flex items-center rounded-lg border border-slate-200">
                            <button type="button" data-index="${index}" data-action="decrease" class="px-3 py-1 text-slate-600 hover:bg-slate-100">-</button>
                            <input type="number" min="1" value="${item.qty}" data-index="${index}" class="qty-input w-14 border-x border-slate-200 px-2 py-1 text-center text-sm">
                            <button type="button" data-index="${index}" data-action="increase" class="px-3 py-1 text-slate-600 hover:bg-slate-100">+</button>
                        </div>
                    </td>
                    <td class="px-4 py-3 text-right">${formatRupiah(item.harga)}</td>
                    <td class="px-4 py-3 text-right">${formatRupiah(subtotal)}</td>
                    <td class="px-4 py-3">
                        <button type="button" data-index="${index}" class="note-btn inline-flex w-full items-center justify-between rounded-lg border border-slate-200 bg-white px-2 py-1 text-left text-sm text-slate-600 hover:bg-slate-50">
                            <span class="truncate">${item.note ? item.note : 'Tambah catatan'}</span>
                           
                        </button>
                    </td>
                    <td class="px-4 py-3 text-right">
                        <button type="button" data-index="${index}" data-action="remove" class="text-rose-600 hover:text-rose-700">Hapus</button>
                    </td>
                `;
                cartBody.appendChild(row);

                appendHiddenInput(`items[${index}][id_menu]`, item.id);
                appendHiddenInput(`items[${index}][qty]`, item.qty);
                appendHiddenInput(`items[${index}][note]`, item.note);
            });

            grandTotalEl.textContent = formatRupiah(total);
            document.getElementById('cart-count').textContent = String(items.length);
            syncMenuHighlights();
            persistCart();
        }

        function handleMenuClick(event) {
            const button = event.target.closest('button[data-id]');
            if (!button) return;

            const id = button.dataset.id;
            const existing = items.find((item) => item.id === id);
            if (existing) {
                existing.qty += 1;
                renderCart();
                return;
            }

            const item = {
                id,
                nama: button.dataset.name,
                harga: parseFloat(button.dataset.price || 0),
                qty: 1,
                note: '',
                type_menu: button.dataset.type || null,
                stand: button.dataset.stand || 'General',
                is_package: button.dataset.isPackage === '1',
            };
            items.push(item);
            renderCart();
        }

        function rebindMenuEvents() {
            menuGrid?.removeEventListener('click', handleMenuClick);
            menuGrid?.addEventListener('click', handleMenuClick);
            syncMenuHighlights();
        }

        function syncMenuHighlights() {
            const idsInCart = new Set(items.map((item) => String(item.id)));
            document.querySelectorAll('#menu-grid button[data-id]').forEach((button) => {
                const isSelected = idsInCart.has(String(button.dataset.id));
                button.classList.toggle('ring-2', isSelected);
                button.classList.toggle('ring-emerald-500', isSelected);
                button.classList.toggle('bg-emerald-50', isSelected);
                button.classList.toggle('border-emerald-300', isSelected);
            });
        }

        cartBody.addEventListener('click', (event) => {
            const button = event.target.closest('button');
            if (!button) {
                return;
            }
            const index = button.dataset.index;
            if (button.dataset.action === 'increase') {
                items[index].qty += 1;
                renderCart();
                return;
            }
            if (button.dataset.action === 'decrease') {
                items[index].qty = Math.max(1, items[index].qty - 1);
                renderCart();
                return;
            }
            if (button.dataset.action === 'remove') {
                items.splice(index, 1);
                renderCart();
            }
        });

        cartBody.addEventListener('input', (event) => {
            if (event.target.classList.contains('qty-input')) {
                const index = event.target.dataset.index;
                const qty = parseInt(event.target.value, 10) || 1;
                items[index].qty = qty;
                renderCart();
            }
        });

        const noteModal = document.getElementById('note-modal');
        const noteTextarea = document.getElementById('note-textarea');
        const saveNoteBtn = document.getElementById('save-note');
        const closeNoteBtn = document.getElementById('close-note');
        const closeNoteSecondary = document.getElementById('close-note-secondary');
        let currentNoteIndex = null;

        cartBody.addEventListener('click', (event) => {
            const noteButton = event.target.closest('.note-btn');
            if (!noteButton) {
                return;
            }
            currentNoteIndex = noteButton.dataset.index;
            noteTextarea.value = items[currentNoteIndex]?.note ?? '';
            noteModal.classList.remove('hidden');
            noteModal.classList.add('flex');
            setTimeout(() => noteTextarea.focus(), 50);
        });

        saveNoteBtn.addEventListener('click', () => {
            if (currentNoteIndex === null) {
                return;
            }
            items[currentNoteIndex].note = noteTextarea.value.trim();
            renderCart();
            noteModal.classList.add('hidden');
            noteModal.classList.remove('flex');
            currentNoteIndex = null;
        });

        function closeNoteModal() {
            noteModal.classList.add('hidden');
            noteModal.classList.remove('flex');
            currentNoteIndex = null;
        }

        closeNoteBtn.addEventListener('click', closeNoteModal);
        closeNoteSecondary.addEventListener('click', closeNoteModal);

        noteModal.addEventListener('click', (event) => {
            if (event.target === noteModal) {
                closeNoteModal();
            }
        });

        const searchClear = document.getElementById('menu-search-clear');
        let searchTimer;
        const SEARCH_DEBOUNCE = 800;
        let isFetchingMenus = false;

        function updateSearchQuery(value) {
            const url = new URL(window.location.href);
            if (value) {
                url.searchParams.set('q', value);
                url.searchParams.set('page', '1');
            } else {
                url.searchParams.delete('q');
                url.searchParams.set('page', '1');
            }
            fetchMenuPage(url.toString());
        }

        async function fetchMenuPage(url) {
            if (isFetchingMenus) return;
            isFetchingMenus = true;
            menuGrid?.classList.add('opacity-60');
            try {
                const response = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
                if (!response.ok) throw new Error('Gagal memuat menu.');
                const html = await response.text();
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const newGrid = doc.querySelector('#menu-grid');
                const newPagination = newGrid?.nextElementSibling;
                if (newGrid && menuGrid) {
                    menuGrid.innerHTML = newGrid.innerHTML;
                }
                if (paginationWrap && newPagination) {
                    paginationWrap.innerHTML = newPagination.innerHTML;
                }
                const newFilters = doc.querySelector('#menu-filters');
                const currentFilters = document.getElementById('menu-filters');
                if (newFilters && currentFilters) {
                    currentFilters.innerHTML = newFilters.innerHTML;
                }
                rebindMenuEvents();
                rebindPaginationLinks();
                rebindFilterLinks();
                window.history.replaceState({}, '', url);
            } catch (error) {
                showClientError(error.message || 'Gagal memuat menu.');
            } finally {
                menuGrid?.classList.remove('opacity-60');
                isFetchingMenus = false;
            }
        }

        function debounceSearch(value) {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(() => {
                updateSearchQuery(value);
            }, SEARCH_DEBOUNCE);
        }

        menuSearch.addEventListener('input', () => {
            const value = menuSearch.value.trim();
            if (searchClear) {
                searchClear.classList.toggle('hidden', value.length === 0);
            }
            if (value.length === 0) {
                debounceSearch('');
                return;
            }
            if (value.length < 2) {
                clearTimeout(searchTimer);
                return;
            }
            debounceSearch(value);
        });

        menuSearch.addEventListener('keydown', (event) => {
            if (event.key === 'Enter') {
                event.preventDefault();
                updateSearchQuery(menuSearch.value.trim());
            }
        });

        searchClear?.addEventListener('click', () => {
            menuSearch.value = '';
            searchClear.classList.add('hidden');
            updateSearchQuery('');
        });

        function toggleMeja() {
            const isDineIn = typeSelect.value === 'dine_in';
            if (typeDisplay) {
                typeDisplay.textContent = isDineIn ? 'Dine In' : 'Take Away';
            }
            mejaSelect.closest('div').style.display = isDineIn ? 'block' : 'none';
            mejaCards.style.display = isDineIn ? 'block' : 'none';
            if (mejaTambahanWrap) {
                mejaTambahanWrap.style.display = isDineIn ? 'block' : 'none';
            }
            if (!isDineIn) {
                mejaSelect.value = '';
                if (mejaTambahanSelect) {
                    Array.from(mejaTambahanSelect.options).forEach((option) => {
                        option.selected = false;
                    });
                }
                if (mejaTambahanValue) {
                    mejaTambahanValue.value = '';
                }
            }
            syncMejaTambahanOptions();
            applyMejaSelection();
            persistHeader();
        }

        window.addEventListener('load', () => {
            loadHeader();
            toggleMeja();
            // re-apply after select2 init (prevent reset)
            setTimeout(loadHeader, 300);
        });
        typeSelect.addEventListener('change', toggleMeja);
        if (window.$ && $.fn.select2) {
            $(typeSelect).on('change', toggleMeja);
        }
        function handleMejaSelectChange() {
            const selected = mejaSelect?.selectedOptions?.[0];
            const orderUrl = selected?.dataset?.orderUrl;
            const selectedId = mejaSelect?.value;
            const openOrderId = selectedId ? openOrderMap?.[selectedId] : null;
            if (orderUrl) {
                window.location.href = orderUrl;
                return;
            }
            if (openOrderId) {
                window.location.href = `${orderShowBaseUrl}/${openOrderId}`;
                return;
            }
            syncMejaTambahanOptions();
            applyMejaSelection();
            persistHeader();
        }
        window.handleMejaSelectChange = handleMejaSelectChange;

        mejaSelect.addEventListener('change', handleMejaSelectChange);
        document.addEventListener('change', (event) => {
            if (event.target && event.target.id === 'meja-select') {
                handleMejaSelectChange();
            }
        });
        if (window.$ && $.fn.select2) {
            $(document).on('select2:select', '#meja-select', handleMejaSelectChange);
        }
        const waiterSelect = document.querySelector('select[name="id_waiters"]');
        waiterSelect?.addEventListener('change', persistHeader);
        mejaTambahanSelect?.addEventListener('change', () => {
            updateMejaTambahanValue();
            persistHeader();
        });
        mejaTambahanSelect?.addEventListener('mousedown', (event) => {
            const option = event.target;
            if (!(option instanceof HTMLOptionElement)) {
                return;
            }
            if (option.disabled) {
                event.preventDefault();
                return;
            }
            // Allow multi-pick with normal click (without Ctrl/Cmd).
            event.preventDefault();
            option.selected = !option.selected;
            updateMejaTambahanValue();
            persistHeader();
        });
        document.querySelector('input[name="nama_pelanggan"]')?.addEventListener('input', persistHeader);

        document.querySelectorAll('#meja-cards button').forEach((button) => {
            button.addEventListener('click', () => {
                if (button.dataset.active !== '1') {
                    return;
                }
                if (button.dataset.orderUrl) {
                    window.location.href = button.dataset.orderUrl;
                    return;
                }

                const selectedId = String(button.dataset.id || '');
                const primaryId = String(mejaSelect?.value || '');

                if (!primaryId) {
                    mejaSelect.value = selectedId;
                    syncSelect2(mejaSelect);
                    syncMejaTambahanOptions();
                    applyMejaSelection();
                    persistHeader();
                    return;
                }

                if (selectedId === primaryId) {
                    applyMejaSelection();
                    persistHeader();
                    return;
                }

                if (mejaTambahanSelect) {
                    const option = Array.from(mejaTambahanSelect.options).find((item) => String(item.value) === selectedId);
                    if (option && !option.disabled) {
                        option.selected = !option.selected;
                    }
                    updateMejaTambahanValue();
                }

                applyMejaSelection();
                persistHeader();
            });
        });

        function showClientError(message) {
            const box = document.getElementById('client-error');
            box.textContent = message;
            box.classList.remove('hidden');
            box.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }

        function clearClientError() {
            const box = document.getElementById('client-error');
            box.classList.add('hidden');
            box.textContent = '';
        }

        openSubmitModal.addEventListener('click', () => {
            clearClientError();
            if (!typeSelect.value) {
                showClientError('Type order wajib dipilih.');
                return;
            }
            if (typeSelect.value === 'dine_in' && !mejaSelect.value) {
                showClientError('Meja wajib dipilih untuk Dine In.');
                return;
            }
            if (typeSelect.value === 'take_away') {
                const namaInput = document.querySelector('input[name="nama_pelanggan"]');
                if (!namaInput?.value?.trim()) {
                    showClientError('Nama pelanggan wajib diisi untuk Take Away.');
                    return;
                }
            }
            const waiterSelect = document.querySelector('select[name="id_waiters"]');
            if (!waiterSelect?.value) {
                showClientError('Waiter wajib dipilih, isi dengan jujur.');
                return;
            }
            if (items.length === 0) {
                showClientError('Item pesanan belum ada. Tambahkan minimal 1 item.');
                return;
            }
            printModal.classList.remove('hidden');
            printModal.classList.add('flex');
        });

        closePrintModal.addEventListener('click', () => {
            printModal.classList.add('hidden');
            printModal.classList.remove('flex');
        });

        printModal.addEventListener('click', (event) => {
            if (event.target === printModal) {
                printModal.classList.add('hidden');
                printModal.classList.remove('flex');
            }
        });

        const donePrints = new Set();
        const confirmPrintButton = document.getElementById('confirm-print');
        const backPrintButton = document.getElementById('back-print');
        const printMainButton = document.getElementById('print-main-button');
        const printStepBadge = document.getElementById('print-step-badge');
        const printStepTitle = document.getElementById('print-step-title');
        let printMainTitle = document.getElementById('print-main-title');
        let printMainDesc = document.getElementById('print-main-desc');
        const prevPrintStep = document.getElementById('prev-print-step');
        let printStep = 1;
        let isSubmittingOrder = false;

        function setConfirmState() {
            const ready = donePrints.size === 2;
            confirmPrintButton.disabled = !ready;
            confirmPrintButton.classList.toggle('bg-slate-300', !ready);
            confirmPrintButton.classList.toggle('bg-slate-900', ready);
            confirmPrintButton.classList.toggle('hover:bg-slate-800', ready);
        }

        function setLoading(button, loading) {
            if (loading) {
                button.disabled = true;
                button.classList.add('opacity-70');
                button.innerHTML = `
                    <svg class="h-5 w-5 animate-spin text-slate-500" viewBox="0 0 24 24" fill="none">
                        <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 0 1 8-8v4a4 4 0 0 0-4 4H4Z"></path>
                    </svg>
                    <span class="text-xs text-slate-500">Memproses...</span>
                `;
                return;
            }
            button.disabled = false;
            button.classList.remove('opacity-70');
            button.innerHTML = `
                <span class="text-base" id="print-main-title">Mulai Print Bluetooth</span>
                <span class="text-xs text-slate-500" id="print-main-desc">Cetak via perangkat tablet</span>
            `;
            printMainTitle = document.getElementById('print-main-title');
            printMainDesc = document.getElementById('print-main-desc');
            updatePrintStepUI();
        }

        function updatePrintStepUI() {
            if (printStep === 1) {
                printStepBadge.textContent = '1';
                printStepBadge.className = 'inline-flex h-6 w-6 items-center justify-center rounded-full bg-slate-900 text-xs text-white';
                printStepTitle.textContent = 'Print Bluetooth';
                printMainTitle.textContent = 'Mulai Print Bluetooth';
                printMainDesc.textContent = 'Cetak via perangkat tablet';
                prevPrintStep.classList.add('hidden');
            } else {
                printStepBadge.textContent = '2';
                printStepBadge.className = 'inline-flex h-6 w-6 items-center justify-center rounded-full bg-emerald-600 text-xs text-white';
                printStepTitle.textContent = 'Print Stand';
                printMainTitle.textContent = 'Mulai Print Stand';
                printMainDesc.textContent = 'Kirim ke printer stand';
                prevPrintStep.classList.remove('hidden');
            }
        }

        updatePrintStepUI();

        function openPrintPreview() {
            const now = new Date();
            const typeLabel = typeSelect.value === 'dine_in' ? 'Dine In' : 'Take Away';
            const isDineIn = typeSelect.value === 'dine_in';
            const mejaText = isDineIn
                ? (mejaSelect.selectedOptions[0]?.textContent || '-')
                : '';
            const pelanggan = document.querySelector('input[name="nama_pelanggan"]')?.value || '';
            const waiterName = document.querySelector('select[name="id_waiters"]')?.selectedOptions[0]?.textContent || '-';
            const itemRows = items.map((item) => `
                <div class="item">
                    <div class="item-row">
                        <span class="item-name">${item.nama}</span>
                        <span class="item-qty">x${item.qty}</span>
                    </div>
                    ${item.note ? `<div class="item-note">Catatan: ${item.note}</div>` : ''}
                </div>
            `).join('');

            const html = `
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Print Preview</title>
    <style>
  /* Kunci: benar-benar nol semua */
  * { margin: 0; padding: 0; box-sizing: border-box; }

  /* Paksa ukuran kertas 80mm, tanpa margin */
  @page { size: 80mm auto; margin: 0; }

  html, body {
    width: 80mm;
    height: fit-content;
    font-family: Arial, sans-serif;
    color: #111;
    overflow: hidden;          /* cegah ruang ekstra */
  }

  /* Ini penting: paksa konten hanya setinggi isi */
  .receipt {
    width: 80mm;
    display: inline-block;     /* jangan block full page */
    height: fit-content;
    padding: 0;
    margin: 0;
  }

  .meta { font-size: 14px; margin: 0 0 6px 6px; }
  .meta-row { display: grid; grid-template-columns: 18mm 2mm 1fr; }

  .items { display: flex; flex-direction: column; gap: 6px; font-size: 12px; }
  .item { padding-bottom: 4px; }
  .item-row { display: flex; justify-content: space-between; gap: 8px; }
  .item-name { font-weight: 600; font-size: 14px; }
  .item-qty { text-align: right; min-width: 24px; }
  .item-note { margin-top: 2px; font-size: 11px; color: #555; }

  /* cegah engine print bikin page break aneh */
  .items, .item, .meta { page-break-inside: avoid; break-inside: avoid; }
</style>
</head>
<body>
    <div class="receipt">
        <div class="meta">
${typeLabel ? `<div class="meta-row">${typeLabel}</div>` : ''}
            ${isDineIn
                ? `<div class="meta-row"><span>Meja</span><span>:</span><span>${mejaText || '-'}</span></div>`
                : `<div class="meta-row"><span>Pelanggan</span><span>:</span><span>${pelanggan || '-'}</span></div>`
            }
            <div class="meta-row"><span>Waiter</span><span>:</span><span>${waiterName}</span></div>
        </div>
        <div class="items">
            ${itemRows}
        </div>
    </div>
</body>
</html>`;

            const win = window.open('', '_blank');
            if (win) {
                win.document.write(html);
                win.document.close();
                win.onload = () => {
                    win.print();
                };
                win.focus();
            }
        }

        function buildDraftPayload() {
            const waiterSelect = document.querySelector('select[name="id_waiters"]');
            const mejaText = typeSelect.value === 'dine_in'
                ? (mejaSelect.selectedOptions[0]?.textContent || null)
                : null;
            const waiterName = waiterSelect?.selectedOptions[0]?.textContent || null;
            const pelanggan = document.querySelector('input[name="nama_pelanggan"]')?.value || null;
            const grandTotal = items.reduce((sum, item) => sum + (item.qty * item.harga), 0);

            return {
                header: {
                    type: typeSelect.value || null,
                    meja: mejaText,
                    waiter: waiterName,
                    nama_pelanggan: pelanggan,
                    grand_total: grandTotal,
                },
                items: items.map((item) => ({
                    id_menu: item.id,
                    nama: item.nama,
                    qty: item.qty,
                    harga: item.harga,
                    note: item.note,
                    type_menu: item.type_menu || null,
                    stand: item.stand || 'General',
                    is_package: item.is_package ? 1 : 0,
                })),
            };
        }

        async function triggerPrintStandDraft() {
            const response = await fetch('/api/print/order/draft', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify(buildDraftPayload()),
            });

            if (response.ok) {
                return response.json();
            }

            let message = 'Gagal mengirim print stand.';
            try {
                const errorData = await response.json();
                if (errorData?.message) {
                    message = errorData.message;
                }
            } catch (error) {
                // ignore parse errors
            }
            throw new Error(message);
        }

        printMainButton.addEventListener('click', async () => {
            const value = printStep === 1 ? 'bluetooth' : 'stand';
            setLoading(printMainButton, true);

            if (value === 'bluetooth') {
                setTimeout(() => {
                    setLoading(printMainButton, false);
                    donePrints.add(value);
                    printMainButton.classList.add('ring-2', 'ring-emerald-500');
                    openPrintPreview();
                    printStep = 2;
                    printMainButton.classList.remove('ring-2', 'ring-emerald-500');
                    updatePrintStepUI();
                    printMainButton.classList.add('animate-pulse');
                    setTimeout(() => printMainButton.classList.remove('animate-pulse'), 600);
                    setConfirmState();
                }, 800);
                return;
            }

            try {
                await triggerPrintStandDraft();
                donePrints.add(value);
                printOptionInput.value = 'stand';
                printMainButton.classList.add('ring-2', 'ring-emerald-500');
                setConfirmState();
            } catch (error) {
                showClientError(error.message);
            } finally {
                setLoading(printMainButton, false);
            }
        });

        prevPrintStep.addEventListener('click', () => {
            printStep = 1;
            updatePrintStepUI();
        });

        confirmPrintButton.addEventListener('click', () => {
            if (donePrints.size !== 2 || isSubmittingOrder) {
                return;
            }
            isSubmittingOrder = true;
            confirmPrintButton.disabled = true;
            confirmPrintButton.classList.add('opacity-70');
            confirmPrintButton.textContent = 'Menyimpan...';
            openSubmitModal?.setAttribute('disabled', 'disabled');
            try {
                localStorage.removeItem(storageKey);
                localStorage.removeItem(headerStorageKey);
            } catch (error) {
                // ignore storage errors
            }
            orderForm.submit();
        });

        backPrintButton.addEventListener('click', () => {
            printModal.classList.add('hidden');
            printModal.classList.remove('flex');
        });

        function rebindPaginationLinks() {
            paginationWrap?.querySelectorAll('a').forEach((link) => {
                link.addEventListener('click', (event) => {
                    event.preventDefault();
                    fetchMenuPage(link.href);
                });
            });
        }

        function rebindFilterLinks() {
            document.querySelectorAll('#menu-filters a').forEach((link) => {
                link.addEventListener('click', (event) => {
                    event.preventDefault();
                    fetchMenuPage(link.href);
                });
            });
        }

        rebindMenuEvents();
        rebindPaginationLinks();
        rebindFilterLinks();

        loadCart();
        renderCart();
        syncMejaTambahanOptions();
    </script>
<?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\foodcourt\resources\views/orders/create.blade.php ENDPATH**/ ?>