{{--
|--------------------------------------------------------------------------
| Dashboard | Order Dashboard
|--------------------------------------------------------------------------
| Wersja 11.0 - Dodano maskowanie e-mail klienta
| Opis:
| Zaimplementowano mechanizm z `live.blade.php` do pobierania i maskowania
| adresu e-mail klienta w kolumnie "CLIENT".
|
--}}


@extends('layouts.app')

@section('content')
<div id="main-wrapper" class="p-10 min-h-screen"
    x-data="ordersAlpine()" x-init="initOrders()">

    {{-- Główny kontener strony, organizujący nagłówek, tabelę i paginację w układzie pionowym. --}}
    <div class="flex flex-col gap-6">
        <div class="p-6 bg-gradient-to-r from-slate-900 via-blue-800 to-blue-500 rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0]">

            {{-- Loader --}}
            <div x-show="showLoader" class="
                fixed inset-0
                bg-black bg-opacity-80
                z-50
                flex items-center justify-center
                " 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" style="display: none;">
                    <div class="text-white text-lg flex flex-col items-center gap-2">
                        <i class="fa-solid fa-spinner fa-spin text-4xl"></i>
                        <span class="text-base">
                            {{ trans('lang.processing') }}
                        </span>
                    </div>
            </div>

            {{-- Header Section --}}
            <div class="mb-6">
                <h3 class="text-2xl font-bold text-slate-50">
                    {{ trans('lang.orders') }}
                </h3>
                <p class="text-sm text-slate-200 mt-1 m-0">{{ trans('lang.orders_desc') }}</p>
            </div>

            {{-- Search and Filter Section --}}
            <div class="flex flex-col md:flex-row items-start md:items-center gap-4 md:gap-6">

                {{-- Search Input --}}
                <div class="flex-1 relative">
                    <input x-model="searchTerm" type="text"
                        placeholder="{!! trans('lang.enter_customer_id_or_name') !!}"
                        class="w-full rounded-md pl-10 pr-4 py-2 text-sm border border-slate-300 focus:outline-none focus:ring-0 focus:border-slate-300 transition" />
                    <i class="fa fa-search text-lg absolute left-3 top-1/2 -translate-y-1/2 text-slate-700"></i>
                </div>

                {{-- Status Filter Dropdown --}}
                <div class="relative" @click.outside="open = false">

                    {{-- Button to toggle the dropdown --}}
                    <button type="button" x-ref="statusFilterButton" @click="toggleDropdown()" class="
                        flex items-center
                        space-x-2
                        px-3
                        py-2
                        text-sm
                        rounded-md
                        bg-white
                        border !border-slate-300
                        hover:bg-slate-100
                        focus:outline-none
                        transition
                    ">
                        <i class="fa-solid fa-filter text-sm text-slate-700"></i>
                        <span class="text-sm text-slate-700 font-regular" x-text="currentStatusLabel"></span>
                        <i class="fa fa-chevron-down text-xs text-slate-700 transition-transform" :class="{'rotate-180': open}"></i>
                    </button>

                    {{-- Dropdown Menu --}}
                    <ul x-show="open" x-transition
                        :class="dropUp ? 'bottom-full mb-2 right-0' : 'top-full mt-2 right-0'"
                        class="
                        absolute w-56
                        bg-white
                        border !border-slate-300
                        rounded-lg
                        shadow-lg
                        z-50
                        transition-all
                        overflow-hidden
                    " style="display: none;">
                        <template x-for="(item, idx) in statuses" :key="idx">
                            <li @click="setStatus(item.value)" class="
                                flex items-center gap-2
                                cursor-pointer
                                px-3 py-2
                                hover:bg-blue-100
                                text-sm
                                text-slate-700
                                whitespace-nowrap
                            ">
                                <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="selectedStatus === item.value ? 'opacity-100' : 'opacity-0'"></i>
                                <span x-text="item.label"></span>
                            </li>
                        </template>
                    </ul>
                </div>

            </div> 
        </div>


        {{-- Orders Table --}}
        <div class="bg-white border border-slate-200 rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0] relative">
            <table id="allOrdersTable" class="w-full text-sm text-slate-700">

                {{-- Table Header --}}
                <thead class="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 text-slate-50">
                    
                    <tr>
                        <th class="px-2 py-3 uppercase font-semibold font-stretch-condensed text-center align-middle
                                    relative
                                    before:absolute before:right-0 before:top-[20%] before:h-[60%]
                                    before:border-r before:border-slate-600">
                            {{ trans('lang.order_id') }}
                        </th>
                        <th class="px-2 py-3 uppercase font-semibold font-stretch-condensed text-center align-middle
                                    relative
                                    before:absolute before:right-0 before:top-[20%] before:h-[60%]
                                    before:border-r before:border-slate-600">
                            {{ trans('lang.order_user_id') }} </th>
                        <th class="px-2 py-3 uppercase font-semibold font-stretch-condensed text-center align-middle
                                    relative
                                    before:absolute before:right-0 before:top-[20%] before:h-[60%]
                                    before:border-r before:border-slate-600">
                            {{ trans('lang.order_order_status_id') }}
                        </th>
                        <th class="px-2 py-3 uppercase font-semibold font-stretch-condensed text-center align-middle
                                    relative
                                    before:absolute before:right-0 before:top-[20%] before:h-[60%]
                                    before:border-r before:border-slate-600">
                            {{ trans('lang.order_type') }}
                        </th>
                        <th class="px-2 py-3 uppercase font-semibold font-stretch-condensed text-center align-middle
                                relative
                                before:absolute before:right-0 before:top-[20%] before:h-[60%]
                                before:border-r before:border-slate-600
                                cursor-pointer
                            " @click="toggleSort('checkOutPrice')">
                            {{ trans('lang.total_amount') }}
                            <span class="ml-1" x-show="sortKey === 'checkOutPrice'">
                                <i x-show="sortDirection === 'asc'"
                                    class="fa-solid fa-arrow-down-wide-short text-xs"></i>
                                <i x-show="sortDirection === 'desc'"
                                    class="fa-solid fa-arrow-up-wide-short text-xs"></i>
                            </span>
                        </th>

                        {{-- Kolumna ilości --}}
                        <th class="px-2 py-3 uppercase font-semibold font-stretch-condensed text-center align-middle
                                    relative
                                    before:absolute before:right-0 before:top-[20%] before:h-[60%]
                                    before:border-r before:border-slate-600">
                            {{ trans('lang.quantity') }}
                        </th>

                        {{-- Kolumna statusu --}}
                        <th class="px-2 py-3 uppercase font-semibold font-stretch-condensed text-center align-middle
                                relative
                                before:absolute before:right-0 before:top-[20%] before:h-[60%]
                                before:border-r before:border-slate-600
                                cursor-pointer
                            " @click="toggleSort('createdAt')">
                            {{ trans('lang.date') }}
                            <span class="ml-1" x-show="sortKey === 'createdAt'">
                                <i x-show="sortDirection === 'asc'"
                                    class="fa-solid fa-arrow-down-wide-short text-xs"></i>
                                <i x-show="sortDirection === 'desc'"
                                    class="fa-solid fa-arrow-up-wide-short text-xs"></i>
                            </span>
                        </th>

                        {{-- Kolumna akcji --}}
                        <th class="px-2 py-3 uppercase font-semibold text-center align-middle
                                    relative">
                            {{ trans('lang.actions') }}
                        </th>
                    </tr>
                </thead>

                {{-- Table Body --}}
                <tbody class="divide-y divide-slate-200">
                    <template x-for="(order, index) in paginatedOrders" :key="order.id">
                        <tr
                            class="hover:bg-gradient-to-r from-blue-50 via-blue-100 to-blue-50 transition-colors delay-50 duration-300 ease-in-out">
                            {{-- ID zamówienia --}}
                            <td class="px-2 py-3 text-center align-middle">
                                <span x-text="order.id" class="font-medium text-slate-600"></span>
                            </td>
                            {{-- Email klienta --}}
                            <td class="px-2 py-3 text-center align-middle">
                                <span x-text="obfuscatedEmail(order.customerEmail)" class="text-slate-600"></span>
                            </td>
                            {{-- Status zamówienia --}}
                            <td class="px-2 py-3 text-center align-middle">
                                <span class="inline-flex items-center px-3 py-1 rounded-md text-xs font-medium"
                                    :class="statusBadgeClass(order.status)">
                                    <i class="mr-2 text-base" :class="statusIconClass(order.status)"></i>
                                    <span x-text="translatedStatus(order.status)"></span>
                                </span>
                            </td>
                            {{-- Typ zamówienia --}}
                            <td class="px-2 py-3 text-center align-middle" x-text="order.serviceLabel"></td>
                            {{-- Cena zamówienia --}}
                            <td class="px-2 py-3 text-center align-middle font-bold text-blue-500"
                                x-text="order.displayPrice"></td>
                            {{-- Ilość produktów --}}
                            <td class="px-2 py-3 text-center align-middle">
                                <div class="flex justify-center items-center gap-2 text-slate-700">
                                    <i class="fa-solid fa-shopping-cart text-sm"></i>
                                    <span x-text="order.itemsCount"></span>
                                </div>
                            </td>
                            {{-- Data zamówienia --}}
                            <td class="px-2 py-3 text-center align-middle leading-tight">
                                <div class="flex flex-col items-center">
                                    <span x-text="order.createdAtFormatted.date" class="text-slate-700"></span>
                                    <span class="inline-flex items-center gap-1 text-slate-500">
                                        <i class="fa-regular fa-clock text-xs"></i>
                                        <span x-text="order.createdAtFormatted.time"></span>
                                    </span>
                                </div>
                            </td>
                            {{-- Akcje --}}
                            <td class="px-2 py-3 text-center">
                                <div class="flex justify-center">
                                    <div x-data="{ tooltipVisible: false }" class="relative">
                                        <a :href="order.editUrl"
                                           @mouseenter="tooltipVisible = true" @mouseleave="tooltipVisible = false"
                                           class="flex h-10 w-10 items-center justify-center rounded-lg text-slate-400 hover:bg-blue-100 hover:text-blue-500 transition hover:no-underline">
                                            <i class="fa-solid fa-ellipsis text-xl"></i>
                                        </a>
                                        <div x-show="tooltipVisible"
                                             x-transition:enter="transition ease-out duration-300"
                                             x-transition:enter-start="opacity-0 translate-y-2"
                                             x-transition:enter-end="opacity-100 translate-y-0"
                                             x-transition:leave="transition ease-in duration-200"
                                             x-transition:leave-start="opacity-100 translate-y-0"
                                             x-transition:leave-end="opacity-0 translate-y-2"
                                             class="absolute top-full left-1/2 -translate-x-1/2 mt-2 w-max max-w-xs bg-slate-800 text-white text-center text-xs rounded py-2 px-3 z-10 pointer-events-none"
                                             style="display: none;">
                                             {!! trans('lang.edit') !!}
                                             <div class="absolute left-1/2 -translate-x-1/2 bottom-full w-0 h-0 border-x-8 border-x-transparent border-b-8 border-b-slate-800"></div>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <div class="flex items-center justify-between mt-2 text-sm">
            <div class="flex items-center gap-2 text-sm">
                <label class="whitespace-nowrap mb-0 text-gray-700 font-semibold">
                    {!! trans('lang.quantity') !!}
                </label>
                <div class="relative" @click.outside="openPageSize = false">
                    <button type="button" x-ref="pageSizeButton" @click="togglePageSizeDropdown()" class="
                            flex items-center
                            space-x-2
                            px-3
                            py-2
                            text-sm
                            rounded-md
                            bg-white
                            border !border-slate-300
                            hover:bg-slate-100
                            focus:outline-none
                            transition
                        ">
                        <span class="text-sm text-slate-700 font-regular" x-text="pageSize"></span>
                        <i class="fa fa-chevron-down text-xs text-slate-700 transition-transform" :class="{'rotate-180': openPageSize}"></i>
                    </button>
                    <ul x-show="openPageSize" x-transition :class="dropUpPageSize
                            ? 'bottom-full mb-2 left-0'
                            : 'top-full mt-2 left-0'" class="
                            absolute
                            w-28
                            bg-white
                            border !border-slate-300
                            rounded-lg
                            shadow-lg
                            z-50
                            transition-all
                            overflow-hidden
                        " style="display: none;">
                        <template x-for="number in [5, 10, 25, 50, 100]" :key="number">
                            <li @click="pageSize = number; openPageSize = false" class="
                                    flex items-center gap-2
                                    cursor-pointer
                                    px-3 py-2
                                    hover:bg-blue-100
                                    text-sm
                                    text-slate-700
                                    whitespace-nowrap
                                ">
                                <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="pageSize === number ? 'opacity-100' : 'opacity-0'"></i>
                                <span x-text="number"></span>
                            </li>
                        </template>
                    </ul>
                </div>
            </div>

            {{-- Pagination Info --}}
            <div class="text-slate-600 font-regular">
                <span x-text="paginationInfo"></span>
            </div>

            {{-- Pagination Controls --}}
            <div class="flex gap-2">
                <button class="
                        flex items-center gap-2
                        px-4 py-2
                        border !border-gray-300
                        bg-white
                        rounded-full
                        hover:bg-slate-100
                        disabled:opacity-50
                        text-gray-800
                        focus:outline-none focus:ring-0
                        transition
                    " :disabled="currentPage === 1" @click="prevPage">
                    <i class="fa-solid fa-chevron-left text-xs"></i>
                    <span>{{ trans('lang.previous') }}</span>
                </button>
                <button class="
                        flex items-center gap-2
                        px-4 py-2
                        border !border-gray-300
                        bg-white
                        rounded-full
                        hover:bg-slate-100
                        disabled:opacity-50
                        text-gray-800
                        focus:outline-none focus:ring-0
                        transition
                    " :disabled="endIndex >= filteredOrders.length" @click="nextPage">
                    <span>{{ trans('lang.next') }}</span>
                    <i class="fa-solid fa-chevron-right text-xs"></i>
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
    const translations = {
        showing: "{{ trans('lang.showing') }}",
        to: "{{ trans('lang.to') }}",
        of: "{{ trans('lang.of') }}",
        no_record_found: "{{ trans('lang.no_record_found') }}"
    };
    function ordersAlpine() {
        return {
            showLoader: false,
            orders: [],
            searchTerm: '',
            userId: "{{ $id ?? '' }}",
            open: false,
            dropUp: false,
            selectedStatus: '',
            statuses: [
                { value: '', label: "{{ trans('lang.all') }}" },
                { value: 'Order Placed', label: "{{ trans('lang.dashboard_order_placed') }}" },
                { value: 'Order Accepted', label: "{{ trans('lang.dashboard_order_accepted') }}" },
                { value: 'Order Rejected', label: "{{ trans('lang.dashboard_order_canceled') }}" },
                { value: 'Order Completed', label: "{{ trans('lang.dashboard_order_completed') }}" },
                { value: 'Payment Pending', label: "{{ trans('lang.dashboard_order_pending') }}" },
                { value: 'Payment Failed', label: "{{ trans('lang.dashboard_order_failed') }}" },
            ],
            currentPage: 1,
            pageSize: 10,
            sortKey: null,
            sortDirection: 'asc',
            openPageSize: false,
            dropUpPageSize: false,

            togglePageSizeDropdown() {
                this.openPageSize = !this.openPageSize;
                if (this.openPageSize) {
                    this.$nextTick(() => {
                        const btn = this.$refs.pageSizeButton;
                        if (!btn) return;
                        const rect = btn.getBoundingClientRect();
                        const distanceToBottom = window.innerHeight - rect.bottom;
                        this.dropUpPageSize = distanceToBottom < 150;
                    });
                }
            },

            async initOrders() {
                this.showLoader = true;
                try {
                    let userSnapshot = await database.collection('users').where('id', '==', this.userId).get();
                    if (userSnapshot.empty) {
                        console.error("Nie znaleziono usera:", this.userId);
                        this.showLoader = false;
                        return;
                    }
                    const vendorID = userSnapshot.docs[0].data().vendorID;
                    let ordersSnapshot = await database.collection('restaurant_orders').where('vendorID', '==', vendorID).orderBy('createdAt', 'desc').get();
                    this.orders = ordersSnapshot.docs.map(doc => {
                        const data = doc.data();
                        return {
                            id: data.id || '',
                            customer: data.customer || '',
                            
                            // ======================================================================
                            // KLUCZOWY KROK #2: Pobieranie adresu e-mail z Firestore.                
                            // Ta linia odczytuje pole `customerEmail` z dokumentu zamówienia.       
                            // Jeśli pole nie istnieje, przypisuje pusty ciąg znaków.                
                            // ======================================================================
                            customerEmail: data.customerEmail || '',

                            status: data.status || '',
                            serviceType: data.serviceType || '',
                            checkOutPrice: parseFloat(data.checkOutPrice || 0),
                            order: Array.isArray(data.order) ? data.order : [],
                            createdAt: data.createdAt ? data.createdAt.toDate() : null,
                            get editUrl() { return `{{ route("orders.edit", ":id") }}`.replace(':id', data.id); },
                            get serviceLabel() { return this.serviceType === 'tableService' ? "{{ trans('lang.table_service') }}" : "{{ trans('lang.counter_pickup') }}"; },
                            get itemsCount() { return this.order.length; },
                            get displayPrice() {
                                let symbol = "{{ $currentCurrency ?? '€ ' }}";
                                let atRight = false;
                                const amt = this.checkOutPrice.toFixed(2);
                                return atRight ? `${amt}${symbol}` : `${symbol}${amt}`;
                            },
                            get createdAtFormatted() {
                                return this.createdAt ? { date: moment(this.createdAt).format('DD.MM.YYYY'), time: moment(this.createdAt).format('HH:mm') } : { date: '-', time: '' };
                            },
                        }
                    });
                } catch (e) {
                    console.error("Błąd pobierania zamówień:", e);
                }
                this.showLoader = false;
            },

            toggleSort(column) {
                if (this.sortKey === column) {
                    this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
                } else {
                    this.sortKey = column;
                    this.sortDirection = 'desc';
                }
                this.currentPage = 1;
            },

            get currentStatusLabel() {
                const found = this.statuses.find(s => s.value === this.selectedStatus);
                return found ? found.label : "{{ trans('lang.all') }}";
            },
            
            toggleDropdown() {
                this.open = !this.open;
                if (this.open) {
                    this.$nextTick(() => {
                        const btn = this.$refs.statusFilterButton;
                        if (!btn) return;
                        const rect = btn.getBoundingClientRect();
                        const distanceToBottom = window.innerHeight - rect.bottom;
                        this.dropUp = distanceToBottom < 250;
                    });
                }
            },

            setStatus(value) {
                this.selectedStatus = value;
                this.open = false;
                this.currentPage = 1;
            },

            get filteredOrders() {
                let arr = [...this.orders];
                if (this.searchTerm.trim()) {
                    const st = this.searchTerm.toLowerCase();
                    arr = arr.filter(o => o.id.toLowerCase().includes(st) || (o.customer && o.customer.toLowerCase().includes(st)));
                }
                if (this.selectedStatus) {
                    arr = arr.filter(o => o.status === this.selectedStatus);
                }
                if (this.sortKey) {
                    arr.sort((a, b) => {
                        let va = a[this.sortKey], vb = b[this.sortKey];
                        if (va == null) va = ''; if (vb == null) vb = '';
                        if (this.sortKey === 'createdAt' && va && vb) { va = va.getTime(); vb = vb.getTime(); }
                        if (this.sortDirection === 'asc') { return va > vb ? 1 : (va < vb ? -1 : 0); } 
                        else { return va < vb ? 1 : (va > vb ? -1 : 0); }
                    });
                }
                return arr;
            },

            get paginatedOrders() {
                const start = (this.currentPage - 1) * this.pageSize;
                return this.filteredOrders.slice(start, start + Number(this.pageSize));
            },
            get endIndex() {
                const end = this.currentPage * this.pageSize;
                return end > this.filteredOrders.length ? this.filteredOrders.length : end;
            },
            prevPage() { if (this.currentPage > 1) this.currentPage--; },
            nextPage() { if (this.endIndex < this.filteredOrders.length) this.currentPage++; },
            get paginationInfo() {
                if (!this.filteredOrders.length) return "{{ trans('lang.no_record_found') }}";
                const start = (this.currentPage - 1) * this.pageSize + 1;
                return `${translations.showing} ${start} ${translations.to} ${this.endIndex} ${translations.of} ${this.filteredOrders.length}`;
            },
            
            // ======================================================================
            // KLUCZOWY KROK #3: Dodanie funkcji maskującej e-mail.                     
            // Ta funkcja jest dostępna w całym komponencie Alpine.js i jest wywoływana
            // z kodu HTML (z Kroku #1), aby przetworzyć adres e-mail.                
            // ======================================================================
            obfuscatedEmail(e) {
                if (!e) return '-';
                const i = e.indexOf('@');
                if (i === -1) return e;
                const name = e.slice(0, i);
                const dom = e.slice(i);
                return name.length > 3
                    ? name.slice(0, 3) + '...' + dom
                    : e;
            },

            // 1) statusBadgeClass
            statusBadgeClass(s) {
                switch (s) {
                    case 'Order Placed':
                        return 'bg-amber-50 border !border-amber-500 text-amber-500';
                    case 'Order Accepted':
                        return 'bg-blue-50 border !border-blue-600 text-blue-600';
                    case 'Order Completed':
                        return 'bg-green-50 border !border-green-600 text-green-600';
                    case 'Order Accepted by Bar':
                    case 'Order Accepted by Kitchen':
                        return 'bg-green-50 border !border-green-600 text-green-600';
                    case 'Order Rejected':
                        return 'bg-red-50 border !border-red-600 text-red-600';
                    default:
                        return 'bg-slate-100 border !border-slate-600 text-slate-600';
                }
            },
            // 2) statusIconClass
            statusIconClass(s) {
                switch (s) {
                    case 'Order Placed':
                        return 'fa fa-shopping-bag';
                    case 'Order Accepted':
                    case 'Order Accepted by Bar':
                    case 'Order Accepted by Kitchen':
                    case 'Order Completed':
                        return 'fa fa-check-circle';
                    case 'Order Rejected':
                        return 'fa fa-times-circle';
                    default:
                        return 'fa fa-info-circle';
                }
            },
            // 3) translatedStatus
            translatedStatus(s) {
                switch (s) {
                    case 'Order Placed':
                        return "{{ trans('lang.dashboard_order_placed') }}";
                    case 'Order Accepted':
                        return "{{ trans('lang.dashboard_order_accepted') }}";
                    case 'Order Accepted by Bar':
                        return "{{ trans('lang.order_accepted_by_bar') }}";
                    case 'Order Accepted by Kitchen':
                        return "{{ trans('lang.order_accepted_by_kitchen') }}";
                    case 'Order Rejected':
                        return "{{ trans('lang.dashboard_order_canceled') }}";
                    case 'Order Completed':
                        return "{{ trans('lang.dashboard_order_completed') }}";
                    default:
                        return s;
            }
        },
        }
    }
</script>
@endsection