{{--
|--------------------------------------------------------------------------
| Plik Widoku: Panel Centrum Eksportu (Export Center)
|--------------------------------------------------------------------------
|
| Lokalizacja: resources/views/exports/center.blade.php (przykładowa)
| Wersja: 1.0 (Pobieranie i filtrowanie danych po stronie klienta)
| Ostatnia modyfikacja: 27 czerwca 2025
|
|--------------------------------------------------------------------------
| Opis Przeznaczenia
|--------------------------------------------------------------------------
|
| Ten plik Blade renderuje interfejs "Centrum Eksportu", który umożliwia
| użytkownikom dynamiczne filtrowanie transakcji i generowanie raportów
| w formacie CSV. Widok jest w pełni interaktywny, pozwalając na wybór
| zakresu dat, typu raportu oraz podgląd danych w paginowanej tabeli
| przed ich finalnym wyeksportowaniem.
|
|--------------------------------------------------------------------------
| Kluczowe Funkcjonalności
|--------------------------------------------------------------------------
|
| - Dynamiczne filtrowanie transakcji według zdefiniowanego zakresu dat.
| - Szybkie presety do wyboru okresu (np. ostatnie 7 dni, bieżący miesiąc).
| - Filtrowanie według typu raportu (np. tylko zrealizowane, wszystkie opłacone).
| - Podgląd odfiltrowanych danych w czasie rzeczywistym w tabeli.
| - Paginacja wyników po stronie klienta z możliwością zmiany liczby
|   rekordów na stronie.
| - Generowanie i pobieranie pliku CSV z odfiltrowanymi danymi bezpośrednio
|   w przeglądarce użytkownika.
| - Komunikaty o stanie ładowania, błędach lub braku danych w danym okresie.
|
|--------------------------------------------------------------------------
| Stos Technologiczny
|--------------------------------------------------------------------------
|
| - Backend: Laravel (silnik szablonów Blade, system tłumaczeń, routing)
| - Frontend (Interaktywność): Alpine.js
| - Frontend (Style): Tailwind CSS
| - Baza Danych (Źródło danych): Firebase Firestore
| - Ikony: Font Awesome
|
|--------------------------------------------------------------------------
| Wskazówki dla Programisty Backend
|--------------------------------------------------------------------------
|
| Aby ten widok działał w pełni poprawnie, backend musi zapewnić
| następujące elementy:
|
| 1.  **Routing:** Muszą istnieć i być poprawnie nazwane następujące trasy:
|     - Trasa wyświetlająca ten widok (np. `exports.center`).
|     - Trasa powrotu do panelu głównego: `dashboard`.
|
| 2.  **Autoryzacja:** Widok ten musi być chroniony przez middleware `auth`,
|     ponieważ operuje na danych specyficznych dla zalogowanego użytkownika.
|
| 3.  **Przekazywanie Danych:** Kontroler odpowiedzialny za ten widok musi
|     przekazać do niego zmienną `$id` z identyfikatorem zalogowanego
|     użytkownika.
|
| 4.  **Konfiguracja Firebase:** Środowisko aplikacji musi mieć poprawnie
|     skonfigurowane klucze dostępowe do Firebase, ponieważ logika JS
|     bezpośrednio odpytuje bazę Firestore.
|
| 5.  **Lokalizacja (i18n):** Pliki językowe (np. `lang.php`) muszą zawierać
|     wszystkie klucze używane w widoku i skrypcie JS, m.in.:
|     `export_center_title`, `filter_by_date`, `last_7_days`, `order_id`,
|     `showing`, `of` oraz wszystkie statusy i opisy raportów.
|
| 6.  **UWAGA DOT. WYDAJNOŚCI:** Obecna implementacja pobiera wszystkie
|     transakcje do klienta i tam je filtruje. W przypadku dużej ilości
|     danych jest to niewydajne. Docelowo backend powinien udostępnić
|     dedykowany endpoint API, który przyjmie parametry filtrowania
|     i zwróci już przetworzone i spaginowane dane.
|
|--------------------------------------------------------------------------
| Zależności
|--------------------------------------------------------------------------
|
| - Skonfigurowany i działający system tłumaczeń Laravela.
| - Skonfigurowane połączenie z Firebase.
| - Dołączone biblioteki JavaScript/CSS w głównym szablonie aplikacji:
|   1. Alpine.js
|   2. Tailwind CSS
|   3. Font Awesome
|   4. Globalna reguła CSS dla `[x-cloak] { display: none !important; }`.
|
--}}
@php
    $startDate = $startDate ?? now()->startOfMonth()->format('Y-m-d');
    $endDate = $endDate ?? now()->format('Y-m-d');
@endphp

@extends('layouts.app')

@section('content')
<div id="main-wrapper" class="p-10 min-h-screen"
    x-data="exportCenter({ 
            initialStartDate: '{{ $startDate }}', 
            initialEndDate: '{{ $endDate }}' 
         })" x-init="init()">

    {{-- Loader --}}
    <div x-show="isLoading" class="fixed inset-0 bg-black bg-opacity-80 z-50 flex items-center justify-center">
        <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.loading_data') }}</span>
        </div>
    </div>

    <div class="flex flex-col gap-6">

        {{-- Nagłówek z tytułem i głównym przyciskiem eksportu --}}
        <div
            class="rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0] p-6 bg-gradient-to-r from-slate-900 via-blue-800 to-blue-500 flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-slate-50">{{ trans('lang.export_center_title') }}</h1>
                <p class="text-sm text-slate-200 mt-1 m-0">{{ trans('lang.export_center_desc') }}</p>
            </div>
            <div class="flex items-center gap-4">
                <a href="{!! route('dashboard') !!}"
                    class="px-4 py-2 rounded-md bg-white text-slate-700 text-sm transition focus:outline-none focus:ring-0 flex items-center gap-2 hover:no-underline hover:text-slate-700">
                    <i class="fa fa-rotate-left"></i>
                    <span>{{ trans('lang.go_back_to_menu') }}</span>
                </a>
                <button @click="generateExport()" :disabled="isLoading || filteredTransactions.length === 0 || isGeneratingExport"
                    class="px-4 py-2 rounded-md bg-white text-slate-700 text-sm hover:bg-slate-100 transition focus:outline-none focus:ring-0 flex items-center justify-center gap-2 disabled:bg-gray-300 disabled:text-gray-500 disabled:cursor-not-allowed whitespace-nowrap">
                    <template x-if="!isGeneratingExport">
                        <span class="flex items-center gap-2">
                            <i class="fa-solid fa-download"></i>
                            <span>{{ trans('lang.export_to_csv') }}</span>
                        </span>
                    </template>
                    <template x-if="isGeneratingExport">
                        <span class="flex items-center gap-2">
                            <i class="fa-solid fa-spinner fa-spin"></i>
                            <span>{{ trans('lang.processing') }}</span>
                        </span>
                    </template>
                </button>
            </div>
        </div>

        {{-- Panel filtrowania danych --}}
        <div class="p-6 bg-white border !border-slate-300 rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0]">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-x-8 gap-y-6 items-start">
                
                {{-- Filtrowanie po dacie --}}
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">{{ trans('lang.filter_by_date') }}</label>
                    <div class="flex flex-col sm:flex-row gap-4 items-center">
                        <input type="date" x-model="startDate"
                            class="form-input w-full rounded-md !border-slate-300 text-sm shadow-sm focus:ring-0 focus:border-gray-300 focus:bg-blue-50 transition">
                        <span class="text-slate-500">{{ trans('lang.to') }}</span>
                        <input type="date" x-model="endDate"
                            class="form-input w-full rounded-md !border-slate-300 text-sm shadow-sm focus:ring-0 focus:border-gray-300 focus:bg-blue-50 transition">
                        <button @click="filterTransactions()"
                            class="px-4 py-2 text-sm font-regular text-white bg-blue-500 hover:bg-blue-600 rounded-md transition whitespace-nowrap">{{ trans('lang.apply') }}</button>
                    </div>
                    <div class="flex items-center gap-2 flex-wrap mt-3">
                        <span class="text-sm text-slate-500 mr-2">{{ trans('lang.quick_select') }}</span>
                        <button @click="setPresetDateRange('last7days')"
                            class="text-sm rounded-md px-4 py-2 transition focus:outline-none focus:ring-0"
                            :class="{ 'bg-blue-500 text-white font-semibold': activePreset === 'last7days', 'bg-white text-slate-700 font-medium border !border-slate-300': activePreset !== 'last7days' }">
                            {{ trans('lang.last_7_days') }}
                        </button>
                        <button @click="setPresetDateRange('thisMonth')"
                            class="text-sm rounded-md px-4 py-2 transition focus:outline-none focus:ring-0"
                            :class="{ 'bg-blue-500 text-white font-semibold': activePreset === 'thisMonth', 'bg-white text-slate-700 font-medium border !border-slate-300': activePreset !== 'thisMonth' }">
                            {{ trans('lang.this_month') }}
                        </button>
                        <button @click="setPresetDateRange('lastMonth')"
                            class="text-sm rounded-md px-4 py-2 transition focus:outline-none focus:ring-0"
                            :class="{ 'bg-blue-500 text-white font-semibold': activePreset === 'lastMonth', 'bg-white text-slate-700 font-medium border !border-slate-300': activePreset !== 'lastMonth' }">
                            {{ trans('lang.last_month') }}
                        </button>
                    </div>
                </div>
                
                {{-- Filtrowanie po typie raportu --}}
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">{{ trans('lang.report_type') }}</label>
                    <div class="p-3 bg-slate-50 rounded-md border !border-slate-300">
                        <div class="relative" @click.outside="open = false">
                            <button type="button" @click="open = !open" 
                                class="flex w-full items-center justify-between px-3 py-2 text-sm rounded-md border !border-slate-300 hover:bg-blue-50 focus:outline-none transition"
                                :class="{ 'bg-blue-50': open, 'bg-white': !open }">
                                <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>
                            <ul class="absolute right-0 mt-2 bg-white border border-slate-300 rounded-lg shadow-lg z-50 transition-all overflow-hidden max-h-60 overflow-y-auto" 
                                x-show="open" x-transition style="display: none;">
                                <template x-for="item in statuses" :key="item.value">
                                    <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">
                                        <div class="w-5 text-center">
                                            <i class="fa-solid fa-check text-blue-600" x-show="reportType === item.value" style="display: none;"></i>
                                        </div>
                                        <span x-text="item.label"></span>
                                    </li>
                                </template>
                            </ul>
                        </div>
                        <p class="text-xs text-slate-500 mt-2" x-text="currentReportDescription"></p>
                    </div>
                </div>
                
            </div>
        </div>
        
        <!-- Komunikat o błędzie podczas ładowania danych -->
        <template x-if="hasError">
            <div class="p-4 bg-red-100 border-l-4 border-red-500 text-red-800 rounded-lg" role="alert">
                <p class="font-bold">{{ trans('lang.error_occurred') }}</p>
                <p>{{ trans('lang.data_loading_error_message') }}</p>
            </div>
        </template>

       <!-- Podgląd danych do eksportu -->
        <div class="bg-white border !border-slate-300 rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden">
            <div class="p-4">
                <h3 class="text-xl text-slate-800 font-bold m-0">{{ trans('lang.export_data_preview') }}</h3>
                <p class="text-sm text-slate-600 m-0">{{ trans('lang.found') }} <strong x-text="filteredTransactions.length"></strong>
                    {{ trans('lang.transactions_for_selected_period') }}</p>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full text-sm text-slate-700">
                    <thead class="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 text-slate-50">
                        <tr>
                            <th class="px-4 py-3 uppercase font-semibold 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-4 py-3 uppercase font-semibold 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.date') }}</th>
                            <th class="px-4 py-3 uppercase font-semibold 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.customer') }}</th>
                            <th class="px-4 py-3 uppercase font-semibold 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_amount') }}</th>
                            <th class="px-4 py-3 uppercase font-semibold 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.tip') }}</th>
                            <th class="px-4 py-3 uppercase font-semibold text-center align-middle relative">{{ trans('lang.status') }}</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-200">
                        <template x-for="transaction in paginatedTransactions" :key="transaction.docId">
                            <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">
                                <td class="px-4 py-3 text-center align-middle" x-text="transaction.id"></td>
                                <td class="px-4 py-3 text-center align-middle" x-text="formatDate(transaction.createdAt)"></td>
                                <td class="px-4 py-3 text-center align-middle" x-text="obfuscatedEmail(transaction.customerEmail)"></td>
                                <td class="px-4 py-3 text-center align-middle font-bold text-blue-500"
                                    x-text="formatCurrency((parseFloat(transaction.checkOutPrice) || 0) - (parseFloat(transaction.tip_amount) || 0))">
                                </td>
                                <td class="px-4 py-3 text-center align-middle font-semibold text-amber-500"
                                    x-text="formatCurrency(transaction.tip_amount)">
                                </td>
                                <td class="px-4 py-3 text-center align-middle" x-text="transaction.paymentStatus"></td>
                            </tr>
                        </template>
                        <template x-if="!isLoading && filteredTransactions.length === 0 && !hasError">
                            <tr>
                                <td colspan="6" class="text-sm text-center py-10 px-4 text-slate-500">
                                    <i class="fa-solid fa-cloud-moon text-slate-400 text-3xl mb-2"></i>
                                    <p>{{ trans('lang.no_transactions_in_period') }}</p>
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="flex items-center justify-between mt-4 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 border !border-slate-300 hover:bg-blue-50 focus:outline-none transition"
                        :class="{ 'bg-blue-50': openPageSize, 'bg-white': !openPageSize }">
                        <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 [10, 25, 50, 100]" :key="number">
                            <li @click="pageSize = number; openPageSize = false; currentPage = 1" 
                                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-600 transition-opacity" :class="pageSize === number ? 'opacity-100' : 'opacity-0'"></i>
                                <span x-text="number"></span>
                            </li>
                        </template>
                    </ul>
                </div>
            </div>
            <div class="text-slate-600 font-regular">
                <span x-text="paginationInfo"></span>
            </div>
            <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-2 focus:ring-blue-400 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-2 focus:ring-blue-400 transition"
                    :disabled="endIndex >= filteredTransactions.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 translationStrings = {
        showing: '{{ trans("lang.showing") }}',
        to: '{{ trans("lang.to") }}',
        of: '{{ trans("lang.of") }}',
        no_date: '{{ trans("lang.no_date") }}',
        no_data_to_export: '{{ trans("lang.no_data_to_export") }}',
        export_headers: {
            order_id: '{{ trans("lang.order_id") }}',
            date: '{{ trans("lang.date") }}',
            customer_id: '{{ trans("lang.customer_id") }}',
            order_amount_no_tip: '{{ trans("lang.order_amount_no_tip") }}',
            tip: '{{ trans("lang.tip") }}',
            payment_method: '{{ trans("lang.payment_method") }}',
            payment_status: '{{ trans("lang.payment_status") }}'
        },
        // ZMIANA: Dodano nowe klucze tłumaczeń
        report_info_completed_sale: '{!! trans("lang.report_type_info_completed_sale") !!}',
        report_info_all_paid: '{!! trans("lang.report_type_info_all_paid") !!}',
        report_info_failed_incomplete: '{!! trans("lang.report_type_info_failed_incomplete") !!}',
        report_info_all: '{!! trans("lang.report_type_info_all") !!}',
        completed_sales_label: '{!! trans("lang.completed_sales_label") !!}',
        all_paid_transactions_label: '{!! trans("lang.all_paid_transactions_label") !!}',
        failed_transactions_label: '{!! trans("lang.failed_transactions_label") !!}',
        all_transactions_label: '{!! trans("lang.all_transactions_label") !!}',
    };

    function exportCenter(config) {
        return {
            startDate: config.initialStartDate,
            endDate: config.initialEndDate,
            isLoading: true,
            hasError: false,
            isGeneratingExport: false,
            allTransactions: [],
            filteredTransactions: [],
            currentPage: 1,
            pageSize: 10,
            openPageSize: false,
            dropUpPageSize: false,
            activePreset: 'thisMonth',

            // ZMIANA: Dodano nowe stany do obsługi dropdownu
            reportType: 'completed_sale',
            open: false, 
            statuses: [],

            async init() {
                // ZMIANA: Wypełniamy opcje dla nowego dropdownu na początku
                this.statuses = [
                    { value: 'completed_sale', label: translationStrings.completed_sales_label },
                    { value: 'all_paid', label: translationStrings.all_paid_transactions_label },
                    { value: 'failed_incomplete', label: translationStrings.failed_transactions_label },
                    { value: 'all', label: translationStrings.all_transactions_label },
                ];

                this.isLoading = true;
                this.hasError = false;
                const db = firebase.firestore();
                const user_id = @json($id);
                try {
                    const userSnapshot = await db.collection('users').doc(user_id).get();
                    const vendorId = userSnapshot.data().vendorID;
                    const snapshots = await db.collection('restaurant_orders').where('vendorID', '==', vendorId).get();
                    this.allTransactions = snapshots.docs.map(doc => ({ docId: doc.id, ...doc.data() }));
                    this.filterTransactions(false);
                } catch (e) {
                    console.error("Błąd podczas pobierania danych:", e);
                    this.hasError = true;
                } finally {
                    this.isLoading = false;
                }
            },

            obfuscatedEmail(email) {
                if (!email) return '-';
                const i = email.indexOf('@');
                if (i === -1) return email;
                const name = email.slice(0, i);
                const domain = email.slice(i);
                return name.slice(0, 3) + '...' + domain;
            },

            filterTransactions(resetPreset = true) {
                this.currentPage = 1;
                if (resetPreset) { this.activePreset = null; }
                if (!this.startDate || !this.endDate) return;
                const start = new Date(this.startDate);
                start.setHours(0, 0, 0, 0);
                const end = new Date(this.endDate);
                end.setHours(23, 59, 59, 999);
                this.filteredTransactions = this.allTransactions.filter(t => {
                    if (!t.createdAt || typeof t.createdAt.toDate !== 'function') return false;
                    const transactionDate = t.createdAt.toDate();
                    const isDateInRange = transactionDate >= start && transactionDate <= end;
                    if (!isDateInRange) return false;
                    switch (this.reportType) {
                        case 'completed_sale': return t.status === 'Order Completed' && t.paymentStatus === 'captured';
                        case 'all_paid': return ['captured', 'uncaptured'].includes(t.paymentStatus);
                        case 'failed_incomplete': return ['incomplete', 'Payment Failed'].includes(t.paymentStatus) || t.status === 'Payment Failed';
                        case 'all': return true;
                        default: return false;
                    }
                });
                this.filteredTransactions.sort((a, b) => b.createdAt.seconds - a.createdAt.seconds);
            },
            
            setPresetDateRange(preset) {
                this.activePreset = preset;
                this.currentPage = 1;
                const now = new Date();
                let startDate, endDate;
                if (preset === 'last7days') {
                    endDate = new Date();
                    startDate = new Date();
                    startDate.setDate(startDate.getDate() - 6);
                } else if (preset === 'lastMonth') {
                    startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
                    endDate = new Date(now.getFullYear(), now.getMonth(), 0);
                } else { // thisMonth
                    startDate = new Date(now.getFullYear(), now.getMonth(), 1);
                    endDate = new Date();
                }
                const formatDateForInput = (date) => {
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`;
                };
                this.startDate = formatDateForInput(startDate);
                this.endDate = formatDateForInput(endDate);
                this.filterTransactions(false);
            },

            generateExport() {
                if (this.filteredTransactions.length === 0 || this.isGeneratingExport) {
                    if(this.filteredTransactions.length === 0) alert(translationStrings.no_data_to_export); 
                    return; 
                }
                this.isGeneratingExport = true;
                setTimeout(() => {
                    try {
                        const headers = Object.values(translationStrings.export_headers);
                        const dataRows = this.filteredTransactions.map(t => {
                            const tipAmount = parseFloat(t.tip_amount) || 0;
                            const orderAmount = (parseFloat(t.checkOutPrice) || 0) - tipAmount;
                            return [
                                `"${t.id}"`, 
                                `"${this.formatDate(t.createdAt)}"`,
                                `"${this.obfuscatedEmail(t.customerEmail)}"`, 
                                orderAmount.toFixed(2).toString().replace('.', ','),
                                tipAmount.toFixed(2).toString().replace('.', ','),
                                `"${t.payment_method || 'N/A'}"`, 
                                `"${t.paymentStatus}"`
                            ].join(';');
                        });
                        const csvContent = [headers.join(';'), ...dataRows].join('\n');
                        const blob = new Blob(["\uFEFF" + csvContent], { type: 'text/csv;charset=utf-8;' });
                        const link = document.createElement('a');
                        link.href = URL.createObjectURL(blob);
                        link.download = `eksport_transakcji_${this.startDate}_${this.endDate}.csv`;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    } finally {
                        this.isGeneratingExport = false;
                    }
                }, 50);
            },

            formatDate(timestamp) {
                if (!timestamp || typeof timestamp.seconds !== 'number') return translationStrings.no_date;
                return new Date(timestamp.seconds * 1000).toLocaleString('pl-PL', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
            },

            formatCurrency(amount, currency = 'EUR') {
                const num = parseFloat(amount) || 0;
                return new Intl.NumberFormat('pl-PL', { style: 'currency', currency: currency }).format(num);
            },

            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 < 200;
                    });
                }
            },
            prevPage() {
                if (this.currentPage > 1) this.currentPage--;
            },
            nextPage() {
                if (this.endIndex < this.filteredTransactions.length) this.currentPage++;
            },
            get paginatedTransactions() {
                const start = (this.currentPage - 1) * this.pageSize;
                return this.filteredTransactions.slice(start, start + Number(this.pageSize));
            },
            get endIndex() {
                const end = this.currentPage * this.pageSize;
                return end > this.filteredTransactions.length ? this.filteredTransactions.length : end;
            },
            get paginationInfo() {
                if (!this.filteredTransactions.length) return '{{ trans("lang.no_transactions_in_period") }}';
                const start = (this.currentPage - 1) * this.pageSize + 1;
                return `${translationStrings.showing} ${start} ${translationStrings.to} ${this.endIndex} ${translationStrings.of} ${this.filteredTransactions.length}`;
            },

            // ZMIANA: Nowe metody i właściwości do obsługi niestandardowego dropdownu
            setStatus(value) {
                this.reportType = value;
                this.open = false;
                this.filterTransactions(false);
            },
            get currentStatusLabel() {
                const found = this.statuses.find(s => s.value === this.reportType);
                return found ? found.label : '';
            },
            get currentReportDescription() {
                switch (this.reportType) {
                    case 'completed_sale': return translationStrings.report_info_completed_sale;
                    case 'all_paid': return translationStrings.report_info_all_paid;
                    case 'failed_incomplete': return translationStrings.report_info_failed_incomplete;
                    case 'all': return translationStrings.report_info_all;
                    default: return '';
                }
            },
        }
    }
</script>
@endsection