<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" @if (str_replace('_', '-' , app()->getLocale()) === 'ar' ||
@$_COOKIE['is_rtl'] === 'true') dir="rtl" @endif>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <title>{{ trans('lang.Pub&Go_merchant_title') }}</title>

    <link rel="icon" id="favicon" type="image/x-icon"
        href="{{ str_replace('images/', 'images%2F', @$_COOKIE['favicon']) }}">

    
    <link rel='stylesheet' href='https://cdn-uicons.flaticon.com/3.0.0/uicons-solid-rounded/css/uicons-solid-rounded.css'>

    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    
    {{-- Ikony Font Awesome --}}
    <link href="{{ asset('css/icons/font-awesome/css/font-awesome.css') }}" rel="stylesheet">

   
    {{-- DataTables --}}
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.dataTables.min.css">

    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script>

    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        // Konfiguracja Tailwind CSS dla CDN
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                    },
                    fontFamily: {
                        sans: ['Poppins', 'sans-serif'],
                    }
                }
            }
        }
        
        // Ukryj ostrzeżenie o CDN w produkcji
        if (typeof tailwind !== 'undefined') {
            const originalWarn = console.warn;
            console.warn = function(message) {
                if (typeof message === 'string' && message.includes('cdn.tailwindcss.com should not be used in production')) {
                    return; // Ignoruj to ostrzeżenie
                }
                originalWarn.apply(console, arguments);
            };
        }
    </script>

    @auth
    @php
    $id = Auth::user()->getvendorId();
    @endphp

    {{-- Globalne przekazanie vendorId do JS --}}
    <script type="text/javascript">
        var cuser_id = '{{ $id }}';
    </script>
    @endauth

    {{-- Font Awesome z kit --}}
    <script src="https://kit.fontawesome.com/4b4effb0ed.js" crossorigin="anonymous"></script>

    <link rel="stylesheet" href="https://cdn-uicons.flaticon.com/uicons-regular-rounded/css/uicons-regular-rounded.css">

    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

    {{-- Dodajemy CSS i JS dla Flowbite --}}
    <link href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/datepicker.min.js"></script>

    <script defer src="https://cdn.jsdelivr.net/npm/flatpickr"></script>


    {{-- Google Maps API - Wymaga klucza API z włączonym "Places API" --}}
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD3P1NrvMwgDsJfrSY9HOqiuZ3Vq4y6tV4&loading=async" defer></script>

    <style>
        [x-cloak] {
            display: none !important;
        }
    </style>

</head>

<body class="min-h-screen bg-gradient-to-br from-blue-50 to-white" x-data>
    <div id="app" class="overflow-x-hidden">
        @auth
        <header class="fixed top-0 left-0 right-0 z-30">
            @include('layouts.header')
        </header>

        <aside
            class="fixed top-[85px] left-0 w-[120px] h-[calc(100vh-85px)] z-20 bg-gradient-to-b from-slate-800 via-slate-900 to-slate-950 overflow-y-auto pt-[40px]">
            @include('layouts.menu')
        </aside>
        @endauth

        <main @auth class="ml-[120px] mt-[85px]" @endauth>
            @yield('content')
        </main>
        
        {{-- Modal: nowe zamówienie --}}
        <div id="notification_add_order" tabindex="-1" aria-hidden="true"
            class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-[1010] justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
            <div class="relative p-4 w-full max-w-md max-h-full">
                <!-- Modal content -->
                <div class="relative bg-white rounded-lg shadow flex flex-col overflow-hidden">
                    <!-- Modal header -->
                    <div class="bg-gray-50 px-6 py-4 flex items-center justify-between border-b border-gray-200">
                        <h3 class="text-lg font-bold text-slate-700 order_placed_subject"></h3>
                        <button type="button" data-modal-hide="notification_add_order"
                            class="text-slate-400 hover:text-slate-600 transition-colors focus:outline-none">
                            <span class="sr-only">{{ trans('lang.close') }}</span>
                            <i class="fa-solid fa-times text-xl"></i>
                        </button>
                    </div>
                    <!-- Modal body -->
                    <div class="p-6 text-center">
                        <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-blue-100">
                            <i class="fa-solid fa-bell text-3xl text-blue-600"></i>
                        </div>
                        <p class="mt-4 text-base text-gray-600 order_placed_msg"></p>
                    </div>
                    <!-- Modal footer -->
                    <div class="bg-gray-50 px-4 py-4 border-t border-gray-200">
                        <a href="{{ url('live-orders') }}" id="notification_add_order_a"
                            class="w-full h-12 flex items-center justify-center bg-blue-500 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-blue-600 focus:outline-none focus:ring-0 active:outline-none active:ring-0 no-underline hover:no-underline"
                            style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);">
                            {{ trans('lang.check_order') }}
                        </a>
                    </div>
                </div>
            </div>
        </div>

        
        
        {{-- Modal: QR Code dla restauracji --}}
        <div id="qr-code-modal" tabindex="-1" aria-hidden="true"
            class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-[1010] justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
            <div class="relative p-4 w-full max-w-md max-h-full">
                <!-- Modal content -->
                <div class="relative bg-white rounded-lg shadow flex flex-col overflow-hidden">
                    <!-- Modal header -->
                    <div class="bg-gray-50 px-6 py-4 flex items-center justify-between border-b border-gray-200">
                        <h3 class="text-lg font-bold text-slate-700">{{ trans('lang.your_restaurant') }}</h3>
                        <button type="button" data-modal-hide="qr-code-modal"
                            class="text-slate-400 hover:text-slate-600 transition-colors focus:outline-none">
                            <span class="sr-only">{{ trans('lang.close') }}</span>
                            <i class="fa-solid fa-times text-xl"></i>
                        </button>
                    </div>
                    <!-- Modal body -->
                    <div class="p-6 text-center">
                        
                        <div class="w-56 h-56 mx-auto my-4" id="qrcode-container"></div>
                        <p class="mt-2 text-sm text-gray-600">{{ trans('lang.scan_qr_to_see_restaurant') }}</p>
                    </div>
                    <!-- Modal footer -->
                    <div class="bg-gray-50 px-4 py-4 border-t border-gray-200">
                        <button type="button"
                            class="w-full h-12 flex items-center justify-center bg-blue-500 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-blue-600 focus:outline-none focus:ring-0 active:outline-none active:ring-0"
                            style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);" data-modal-hide="qr-code-modal">
                            {{ trans('lang.close') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Overlay dla ekranu ostrzegawczego --}}
    <div id="overlay" class="fixed inset-0 z-[9999] flex-col items-center justify-center bg-blue-500 p-8 text-center text-white" style="display: none;">
        <div class="mb-6">
            <img src="{{ asset('assets/images/logo-PnG-vertical.svg') }}" alt="Logo" class="mx-auto h-40 w-auto">
        </div>
        <h2 class="mb-3 text-3xl font-bold">{!! trans('lang.warning_screen_title') !!}</h2>
        <p class="max-w-2xl text-lg text-slate-300">{!! trans('lang.warning_screen_desc') !!}</p>
    </div>

    <script src="{{ asset('assets/plugins/jquery/jquery.min.js') }}"></script>
    
    
    <script src="{{ asset('js/waves.js') }}"></script>
    <script src="{{ asset('assets/plugins/sticky-kit-master/dist/sticky-kit.min.js') }}"></script>
    <script src="{{ asset('assets/plugins/sparkline/jquery.sparkline.min.js') }}"></script>
    <script src="{{ asset('js/jquery.resizeImg.js') }}"></script>

    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>

    
    

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment.min.js"></script>
    <script src="https://cdn.datatables.net/plug-ins/2.0.8/sorting/datetime-moment.js"></script>
    <script src="https://cdn.datatables.net/plug-ins/1.10.11/sorting/date-eu.js"></script>
    <script src="https://cdn.datatables.net/plug-ins/2.0.8/sorting/date-euro.js"></script>

    <script src="{{ asset('js/crypto-js.js') }}"></script>
    <script src="{{ asset('js/jquery.cookie.js') }}"></script>
    <script src="{{ asset('js/jquery.validate.js') }}"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.2.1/compressor.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/davidshimjs-qrcodejs@0/qrcode.min.js"></script>

    @yield('scripts')
    <script type="text/javascript">
        var route1 = '{{ route("orders.edit", ":id") }}';
        var booktable = '{{ route("booktable.edit", ":id") }}';
        var pageloadded = 0;
        var vendorId = '';

        var version = database.collection('settings').doc("Version");
        var globalSettings = database.collection('settings').doc("globalSettings");

        var orderPlacedSubject = '';
        var orderPlacedMsg = '';
        var dineInPlacedSubject = '';
        var dineInPlacedMsg = '';
        var driverAcceptedSubject = '';
        var driverAcceptedMsg = '';
        var scheduleOrderPlacedSubject = '';
        var scheduleOrderPlacedMsg = '';

        let newOrderCount = 0;
        let isInitialLoad = true;
        let attachNotification = false;
        let latestOrderTimestamp = getLatestOrderTimestamp();
        
        const isLivePage = window.location.pathname.includes('live-orders');
        const isStatusScreen = window.location.pathname.includes('status-screen');

        let qrCodeModalInstance = null;
        let newOrderModalInstance = null;
        let qrCodeGenerator = null;

        document.addEventListener('DOMContentLoaded', function () {
            const qrModalEl = document.getElementById('qr-code-modal');

            const newOrderModalEl = document.getElementById('notification_add_order');
            if (newOrderModalEl) {
                const modalOptions = {
                    backdropClasses: 'bg-black/80 fixed inset-0 z-[1000]'
                };
                newOrderModalInstance = new Modal(newOrderModalEl, modalOptions);
            }

            if (qrModalEl) {
                // Opcje dla modala, w tym niestandardowe tło
                const modalOptions = {
                    backdropClasses: 'bg-black/80 fixed inset-0 z-[1000]'
                };
                // Inicjalizacja modala z Flowbite z nowymi opcjami
                qrCodeModalInstance = new Modal(qrModalEl, modalOptions);
            }

            const qrContainer = document.getElementById('qrcode-container');
            if (qrContainer) {
                // Inicjalizacja generatora QR kodu
                qrCodeGenerator = new QRCode(qrContainer, { text: "", width: 224, height: 224, colorDark: "#000000", colorLight: "#ffffff", correctLevel: QRCode.CorrectLevel.H });
            }
        });

        $(document).ready(function () {
            handleScreenResize();
            changeHeaderTitle();
            findVendorAndSetupListener();
            loadDynamicNotifications();
        });

        function handleScreenResize() {
            const MIN_WIDTH = 999;
            const overlay = document.getElementById('overlay');
            const appContainer = document.getElementById('app');
            let resizeTimeout;

            function checkViewportWidth() {
                const isTooSmall = window.innerWidth < MIN_WIDTH;
                overlay.style.display = isTooSmall ? 'flex' : 'none';
                appContainer.style.display = isTooSmall ? 'none' : '';
            }

            const debouncedCheck = () => {
                clearTimeout(resizeTimeout);
                resizeTimeout = setTimeout(checkViewportWidth, 150);
            };

            checkViewportWidth();
            window.addEventListener('resize', debouncedCheck);
        }

        function findVendorAndSetupListener() {
            database.collection('users').doc(cuser_id).get()
                .then(function (usersnapshots) {
                    var userData = usersnapshots.data();
                    if (!userData) return;

                    var username = userData.firstName + ' ' + userData.lastName;
                    Alpine.store('user').name = username;
                    if (userData.profilePictureURL) {
                        Alpine.store('user').avatar = userData.profilePictureURL;
                    }

                    vendorId = userData.vendorID;
                    database.collection('vendors').where('id', '==', vendorId).get().then(function (snapshots) {
                        if (!snapshots.empty) {
                            snapshots.forEach(function (doc) {
                                var data = doc.data();
                                setOnlineSwitch(data.reststatus);
                                fixCreatedAtTimestamp(data, doc);
                            });
                        }
                    });
                    setupOrderListener(vendorId);
                })
                .catch(function (error) {
                    console.error("Error fetching vendor data:", error);
                });
        }
        
        function setOnlineSwitch(reststatus) {
            Alpine.store('restaurant').isOnline = reststatus;
            Alpine.store('restaurant').statusText = reststatus ? 'Online' : 'Offline';
        }

        function fixCreatedAtTimestamp(data, docRef) {
            if (data.createdAt instanceof firebase.firestore.Timestamp) {
                return; 
            }
            if (typeof data.createdAt === 'object' && !Array.isArray(data.createdAt)) {
                const combinedValue = (data.createdAt._seconds) * 1000 + (data.createdAt._nanoseconds / 1000000);
                const regularTimestamp = new Date(combinedValue);
                docRef.ref.update({ "createdAt": regularTimestamp });
            }
        }
        
        function setupOrderListener(vendorID) {
            if (!vendorID) return;
            database.collection('restaurant_orders')
                .where('vendorID', "==", vendorID)
                .onSnapshot(function (snapshot) {
                    let changes = snapshot.docChanges();
                    let newLatestOrderTimestamp = latestOrderTimestamp;
                    if (isStatusScreen) return;
                    changes.forEach(function (change) {
                        const val = change.doc.data();
                        const orderTimestamp = val.createdAt ? val.createdAt.toDate : null;
                        if (isInitialLoad) {
                            if (orderTimestamp && (!newLatestOrderTimestamp || orderTimestamp > newLatestOrderTimestamp)) {
                                newLatestOrderTimestamp = orderTimestamp;
                            }
                        } else {
                            if (orderTimestamp && (!latestOrderTimestamp || orderTimestamp > latestOrderTimestamp)) {
                                if (val.status === "Order Placed") {
                                    if (!isLivePage) {
                                        updateModal(val);
                                    } else {
                                        insertTile(val);
                                    }
                                }
                                if (orderTimestamp > newLatestOrderTimestamp) {
                                    newLatestOrderTimestamp = orderTimestamp;
                                }
                            }
                        }
                    });
                    if (isInitialLoad) {
                        isInitialLoad = false;
                    }
                    latestOrderTimestamp = newLatestOrderTimestamp;
                    saveLatestOrderTimestamp(latestOrderTimestamp);
                },
                    function (error) {
                        console.error('Error listening to restaurant orders:', error);
                    }
                );
        }
        
        function updateModal(val) {
            newOrderCount++;
            document.querySelector('#notification_add_order .order_placed_subject').textContent = '{{ trans('lang.new_order_placed') }}';
            document.querySelector('#notification_add_order .order_placed_msg').textContent = '{{ trans('lang.you_have') }} ' + newOrderCount + ' {{ trans('lang.new_orders') }}.';

            const link = document.getElementById('notification_add_order_a');
            link.setAttribute("href", "{{ url('live-orders') }}");
            
            if (newOrderModalInstance) {
                newOrderModalInstance.show();
            }
        }

        function getLatestOrderTimestamp() {
            const timestampStr = localStorage.getItem('latestOrderTimestamp');
            return timestampStr ? new Date(timestampStr) : null;
        }
        function saveLatestOrderTimestamp(timestamp) {
            if (timestamp) {
                localStorage.setItem('latestOrderTimestamp', timestamp.toISOString());
            }
        }

        var pageloadded_book = 0;
        database.collection('booked_table').where('vendorID', "==", cuser_id).onSnapshot(function (doc) {
            if (pageloadded_book) {
                doc.docChanges().forEach(function (change) {
                    var val = change.doc.data();
                    if (change.type === "added") {
                        if (val.status === "Order Placed") {
                            if (val.author && val.author.firstName) {}
                            if (route1) { $("#notification_book_table_add_order_a").attr("href", booktable.replace(':id', val.id)); }
                            $('.dinein_order_placed_subject').text(dineInPlacedSubject);
                            $('.dinein_order_placed_msg').text(dineInPlacedMsg);
                        }
                    }
                });
            } else {
                pageloadded_book = 1;
            }
        });
        
        function loadDynamicNotifications() {
            database.collection('dynamic_notification').get().then(function (snapshot) {
                if (!snapshot.empty) {
                    snapshot.docs.forEach(function (listval) {
                        let val = listval.data();
                        if (val.type === "dinein_placed") { dineInPlacedSubject = val.subject; dineInPlacedMsg = val.message; } 
                        else if (val.type === "order_placed") { orderPlacedSubject = val.subject; orderPlacedMsg = val.message; }
                        else if (val.type === "driver_accepted") { driverAcceptedSubject = val.subject; driverAcceptedMsg = val.message; }
                        else if (val.type === "schedule_order") { scheduleOrderPlacedSubject = val.subject; scheduleOrderPlacedMsg = val.message; }
                    });
                }
            });
        }
        
        var langcount = 0;
        var languages_list_main = [];
        var languages_list = database.collection('settings').doc('languages');
        languages_list.get().then(async function (snapshotslang) {
            var data = snapshotslang.data();
            if (!data) return;
            var snapList = data.list || [];
            snapList.forEach((lang) => {
                if (lang.isActive) {
                    langcount++;
                    $('#language_dropdown').append($("<option></option>").attr("value", lang.slug).text(lang.title));
                }
            });
            if (langcount > 1) { $("#language_dropdown_box").css('visibility', 'visible'); }
            @if (session() -> get('locale'))
                $("#language_dropdown").val("{{ session()->get('locale') }}");
            @endif
            languages_list_main = snapList;
        });
        
        var url = "{{ route('changeLang') }}";
        $(".changeLang").change(function () {
            var slug = $(this).val();
            languages_list_main.forEach((data) => {
                if (slug === data.slug) {
                    if (data.is_rtl === undefined) { setCookie('is_rtl', 'false', 365); }
                    else { setCookie('is_rtl', data.is_rtl.toString(), 365); }
                    window.location.href = url + "?lang=" + slug;
                }
            });
        });

        function setCookie(name, value, days) {
            var expires = "";
            if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); }
            document.cookie = name + "=" + (value || "") + expires + "; path=/";
        }
        function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i].trim(); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
        
        document.addEventListener('alpine:init', () => {
            Alpine.store('user', {
                name: '...',
                avatar: '{{ asset('images/icons/account_icon.svg') }}'
            });

            Alpine.store('restaurant', {
                isOnline: false,
                statusText: 'Offline'
            });

            Alpine.store('header', {
                title: ''
            });

            Alpine.store('app', {
                showStatusModal: false,
                statusModalTitle: '',
                statusModalText: '',
                checkboxElement: null,

                openStatusModal(el) {
                    this.checkboxElement = el;
                    const isCurrentlyChecked = el.checked;

                    if (!isCurrentlyChecked) {
                        this.statusModalTitle = "{!! trans('lang.modal_status_offline_title') !!}";
                        this.statusModalText = "{!! trans('lang.modal_status_offline_desc') !!}";
                    } else {
                        this.statusModalTitle = "{!! trans('lang.modal_status_online_title') !!}";
                        this.statusModalText = "{!! trans('lang.modal_status_online_desc') !!}";
                    }
                    this.showStatusModal = true;
                },

                confirmStatusChange() {
                    if (this.checkboxElement) {
                        // 1. Zmień stan w magazynie Alpine
                        const newStatus = !Alpine.store('restaurant').isOnline;
                        Alpine.store('restaurant').isOnline = newStatus;

                        // 2. Wywołaj funkcję aktualizującą Firebase
                        switchRestStatus();
                    }
                    this.hideModal();
                },

                hideModal() {
                    this.showStatusModal = false;
                    this.checkboxElement = null;
                }
            });
        });

        function switchRestStatus() {
            const isOnline = Alpine.store('restaurant').isOnline;
            database.collection('vendors').where('author', '==', cuser_id).get().then(function(snapshots) {
                if (snapshots.docs.length > 0) {
                    var doc = snapshots.docs[0];
                    var data = doc.data();
                    database.collection('users').doc(cuser_id).get().then(function(userSnapshots) {
                        var user = userSnapshots.data();
                        if ('restaurant_id' in user && user.restaurant_id != doc.id) {
                            alert("You are not authorised to change status of this restaurant.");
                            setOnlineSwitch(data.reststatus);
                            return false;
                        }
                        if ('approvalWaiting' in data && data.approvalWaiting === true) {
                            alert("Unable to publish restaurant. Account approval is in progress.");
                            setOnlineSwitch(false);
                            return false;
                        }
                        var docRef = database.collection('vendors').doc(doc.id);
                        docRef.update({ reststatus: isOnline });
                        Alpine.store('restaurant').statusText = isOnline ? 'Online' : 'Offline';
                    });
                }
            });
        }

        // =========================================================================
        // ZMIANA: Zaktualizowana funkcja do dynamicznej zmiany tytułu w nagłówku
        // =========================================================================
        function changeHeaderTitle() {
            const currentUrl = window.location.href;
            const baseUrl = "{{ env('APP_URL') }}";
            
            const urlMappings = {
                [`${baseUrl}/users/restaurant`]: "{!! trans('lang.restaurant_settings') !!}", 
                [`${baseUrl}/orders/edit/`]: "{!! trans('lang.order_edit') !!}",
                [`${baseUrl}/orders/create`]: "{!! trans('lang.create_order') !!}",
                [`${baseUrl}/orders`]: "{!! trans('lang.orders') !!}",
                [`${baseUrl}/dashboard`]: "{!! trans('lang.home') !!}",
                [`${baseUrl}/foods/create`]: "{!! trans('lang.create_menu_item') !!}",
                [`${baseUrl}/foods/edit/`]: "{!! trans('lang.edit_menu_item') !!}", // NOWY WPIS
                [`${baseUrl}/foods`]: "{!! trans('lang.menu_management_title') !!}", 
                [`${baseUrl}/category/create`]: "{!! trans('lang.create_category') !!}",
                [`${baseUrl}/category`]: "{!! trans('lang.categories_management_title') !!}",
                [`${baseUrl}/users/profile`]: "{!! trans('lang.account') !!}",
                [`${baseUrl}/category/edit/`]: "{!! trans('lang.edit_category_title') !!}", 
                [`${baseUrl}/users/manage_profile`]: "{!! trans('lang.manage_profile') !!}",
                [`${baseUrl}/users/manage_users`]: "{!! trans('lang.user_management') !!}",
                [`${baseUrl}/users/payment_details`]: "{!! trans('lang.export_center_title') !!}",
                [`${baseUrl}/live-orders`]: "{!! trans('lang.live_orders') !!}",


            };
            
            const sortedPaths = Object.keys(urlMappings).sort((a, b) => b.length - a.length);

            for (const path of sortedPaths) {
                if (currentUrl.startsWith(path)) {
                    Alpine.store('header').title = urlMappings[path];
                    return; 
                }
            }
        }

        // ZMIANA: Poprawiona funkcja przekierowania do restauracji
        function handleRedirectToRestaurant() {
            if (!vendorId) {
                console.error("handleRedirectToRestaurant: Błąd - ID restauracji (vendorId) jest niedostępne.");
                return;
            }
            // Używamy zapytania 'where' zamiast 'doc', aby znaleźć restaurację po jej publicznym ID
            database.collection('vendors').where('id', '==', vendorId).get()
                .then(function (querySnapshot) {
                    if (querySnapshot.empty) {
                        console.error("handleRedirectToRestaurant: Nie znaleziono restauracji o ID:", vendorId);
                        return;
                    }
                    const restaurantData = querySnapshot.docs[0].data();
                    if (restaurantData.latitude && restaurantData.longitude) {
                        redirectToRestaurant(restaurantData.latitude, restaurantData.longitude);
                    } else {
                        console.error("handleRedirectToRestaurant: W danych restauracji brakuje szerokości lub długości geograficznej.");
                    }
                })
                .catch(function (error) {
                    console.error("handleRedirectToRestaurant: Błąd podczas pobierania danych restauracji:", error);
                });
        }

        // ZMIANA: Funkcja do pokazywania modala z kodem QR
        function showRestaurantQrCode() {
            if (!vendorId) {
                console.error("showRestaurantQrCode: Błąd - ID restauracji (vendorId) jest niedostępne.");
                return;
            }
            const url = `https://www.pubandgo.de/restaurant?id=${vendorId}`;

            if (qrCodeGenerator) {
                qrCodeGenerator.clear();
                qrCodeGenerator.makeCode(url + '&counterPickup=true');
            } else {
                console.error("showRestaurantQrCode: Generator QR kodu nie został zainicjowany.");
                return;
            }
            if (qrCodeModalInstance) { 
                qrCodeModalInstance.show(); 
            } else { 
                console.error("showRestaurantQrCode: Instancja modala nie została znaleziona."); 
            }
        }

        // ZMIANA: Poprawiona funkcja pobierania miasta na podstawie koordynatów
        function getCityFromLatLng(lat, lng, callback) {
            const url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&zoom=10&addressdetails=1`;
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    const city = response.address ? (response.address.city || response.address.town || response.address.village) : null;
                    callback(city);
                } else if (xhr.readyState === 4) {
                    console.error(`Błąd zapytania do Nominatim API, status: ${xhr.status}`);
                    callback(null);
                }
            };
            xhr.open("GET", url, true);
            xhr.send();
        }

        // ZMIANA: Poprawiona funkcja otwierająca stronę restauracji
        function redirectToRestaurant(lat, lng) {
            getCityFromLatLng(lat, lng, function (city) {
                if (city) {
                    setCookie('address_name', city, 7); setCookie('address_lat', lat, 7); setCookie('address_lng', lng, 7); setCookie('address_city', city, 7);
                } else {
                    console.error("Nie udało się ustalić miasta. Przekierowanie nastąpi bez ustawienia ciasteczek lokalizacji.");
                }
                // Otwieramy stronę w nowej karcie
                window.open(`https://www.pubandgo.de/restaurant?id=${vendorId}`, '_blank');
            });
        }

        function handleRedirectToStatusPage() {
            window.location.href = "{{ route('statusScreen') }}";
        }

        version.get().then(function (snapshots) { var version_data = snapshots.data(); if (version_data === undefined) { database.collection('settings').doc('Version').set({}); } try { $('.web_version').html("V: 1.0.0"); } catch (error) {} });
        globalSettings.get().then(function (snapshots) { var globalSettingsData = snapshots.data(); if (globalSettingsData === undefined) { database.collection('settings').doc('globalSettings').set({}); } try { if (!getCookie('meta_title')) { document.title = globalSettingsData.meta_title; setCookie('meta_title', globalSettingsData.meta_title, 365); } if (!getCookie('favicon')) { setCookie('favicon', globalSettingsData.favicon, 365); } } catch (error) {} });
    </script>

{{-- Modal potwierdzenia zmiany statusu --}}
<div x-show="$store.app.showStatusModal" x-transition:enter="transition ease-out duration-300"
    x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
    x-transition:leave="transition ease-in duration-200" x-transition:leave-start="opacity-100"
    x-transition:leave-end="opacity-0"
    class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-80" style="display: none;"
    x-cloak>
    <div @click.away="$store.app.hideModal()" x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
        x-transition:leave="transition ease-in duration-200" x-transition:leave-start="opacity-100 scale-100"
        x-transition:leave-end="opacity-0 scale-95"
        class="bg-white rounded-lg text-left overflow-hidden shadow-xl w-full max-w-md flex flex-col">

        <div class="p-6 text-center">
            <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-blue-100">
                <i class="fa-solid fa-store text-3xl text-blue-600"></i>
            </div>
            <h4 class="text-xl font-semibold text-gray-900 mt-4" x-html="$store.app.statusModalTitle"></h4>
            <p class="mt-2 text-sm text-gray-600" x-html="$store.app.statusModalText"></p>
        </div>

        <div class="bg-gray-50 px-4 py-4 border-t border-gray-200 flex flex-col gap-3">
            <button @click="$store.app.confirmStatusChange()" type="button"
                class="w-full h-12 flex items-center justify-center bg-blue-600 text-white text-base font-semibold rounded-md shadow-md uppercase transition-colors hover:bg-blue-700 focus:outline-none focus:ring-0 active:outline-none active:ring-0"
                style="box-shadow: 1px 1px 2px rgba(0,0,0,0.2);">{!! trans('lang.confirm') !!}</button>
            <button @click="$store.app.hideModal()" type="button"
                class="w-full h-12 flex items-center justify-center bg-white text-gray-700 border border-gray-300 text-base font-semibold rounded-md shadow-sm uppercase transition-colors hover:bg-gray-50 focus:outline-none focus:ring-0 active:outline-none active:ring-0">{!! trans('lang.cancel') !!}</button>
        </div>
    </div>
</div>

</body>

</html>