@extends('layouts.app')

@section('content')
<div id="main-wrapper" class="p-10"
    x-data="vouchersAlpine()" x-init="initVouchers()">

    {{-- 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="flex flex-col md:flex-row justify-between md:items-start gap-4 mb-6">
                <div>
                    <h3 class="text-2xl font-bold text-slate-50">
                        {{ trans('lang.vouchers') }}
                    </h3>
                    <p class="text-sm text-slate-200 mt-1 m-0">{{ trans('lang.vouchers_desc') }}</p>
                </div>
                <div class="flex-shrink-0 mt-2 md:mt-0">
                    <a href="{{ route('voucher.create') }}" class="flex items-center gap-2 px-4 py-2 text-sm bg-white text-slate-600 rounded-md hover:bg-slate-100 hover:text-slate-900 hover:no-underline transition focus:outline-none whitespace-nowrap">
                        <i class="fa-solid fa-plus text-xs"></i>
                        <span>{{ trans('lang.add_voucher') }}</span>
                    </a>
                </div>
            </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_voucher_id_or_name') !!}"
                        class="w-full rounded-md pl-10 pr-4 py-2 text-sm focus:outline-none focus:ring-0 transition border-0" />
                    <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="px-4 py-2 rounded-md bg-white text-slate-600 text-sm transition focus:outline-none flex items-center justify-center gap-2 whitespace-nowrap hover:no-underline hover:bg-slate-100 hover:text-slate-900">
                        <i class="fa-solid fa-filter"></i>
                        <span class="font-regular" x-text="currentStatusLabel"></span>
                        <i class="fa fa-chevron-down text-xs 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>


        {{-- Vouchers Table --}}
        <div class="bg-white border border-slate-200 rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0] relative">
            <table id="allVouchersTable" 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>
                    {{-- ID --}}
                    <th class="px-2 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 rounded-tl-lg">
                        {{ trans('lang.id') }}
                    </th>

                    {{-- Voucher Name --}}
                    <th class="px-2 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.voucher_name') }}
                    </th>

                    {{-- Title --}}
                    <th class="px-2 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.title') }}
                    </th>

                    {{-- Description --}}
                    <th class="px-2 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.description') }}
                    </th>

                    {{-- Type --}}
                    <th class="px-2 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.type') }}
                    </th>

                    {{-- Validity --}}
                    <th class="px-2 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.validity') }}
                    </th>

                    {{-- Status --}}
                    <th class="px-2 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.status') }}
                    </th>

                    {{-- Date (sortable) --}}
                    <th class="px-2 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 cursor-pointer"
                        @click="toggleSort('created_at')">
                        {{ trans('lang.date') }}
                        <span class="ml-1" x-show="sortKey === 'created_at'">
                            <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>

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

                            {{-- Table Body --}}
            <tbody class="divide-y divide-slate-200">
                <template x-for="(voucher, index) in paginatedVouchers" :key="voucher.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 --}}
                        <td class="px-2 py-3 text-center align-middle">
                            <span x-text="voucher.id" class="font-medium text-slate-600"></span>
                        </td>

                        {{-- Voucher Name --}}
                        <td class="px-2 py-3 text-center align-middle">
                            <span x-text="voucher.voucher_name" class="text-slate-600"></span>
                        </td>

                        {{-- Title --}}
                        <td class="px-2 py-3 text-center align-middle">
                            <span x-text="voucher.title" class="text-slate-600"></span>
                        </td>

                        {{-- Description --}}
                        <td class="px-2 py-3 text-center align-middle">
                            <span x-text="voucher.description" class="text-slate-600"></span>
                        </td>

                        {{-- Type --}}
                        <td class="px-2 py-3 text-center align-middle">
                            <span x-text="voucher.typeLabel" class="text-slate-600"></span>
                        </td>

                        {{-- Validity (days) --}}
                        <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-regular fa-calendar text-sm"></i>
                                <span x-text="voucher.validity ?? '-'"></span>
                            </div>
                        </td>

                        {{-- Status Badge --}}
                        <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(voucher.status)">
                                <i class="mr-2 text-base" :class="statusIconClass(voucher.status)"></i>
                                <span x-text="translatedStatus(voucher.status)"></span>
                            </span>
                        </td>

                        {{-- Date --}}
                        <td class="px-2 py-3 text-center align-middle leading-tight">
                            <div class="flex flex-col items-center">
                                <span x-text="voucher.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="voucher.createdAtFormatted.time"></span>
                                </span>
                            </div>
                        </td>

                        {{-- Actions --}}
                        <td class="px-2 py-3 text-center">
                            <div class="flex justify-center">
                                <div x-data="{ tooltipVisible: false }" class="relative">
                                    <a :href="voucher.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 vouchersAlpine() {
        return {
            showLoader: false,
            vouchers: [],
            searchTerm: '',
            open: false,
            dropUp: false,
            selectedStatus: '',

            // status is smallint: 0 = inactive, 1 = active, 2 = expired — adjust values to match your app
            statuses: [
                { value: '',  label: "{{ trans('lang.all') }}" },
                { value: '1', label: "{{ trans('lang.active') }}" },
                { value: '0', label: "{{ trans('lang.inactive') }}" },
            ],

            currentPage: 1,
            pageSize: 10,
            sortKey: 'created_at',
            sortDirection: 'desc',
            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();
                        this.dropUpPageSize = (window.innerHeight - rect.bottom) < 150;
                    });
                }
            },

            // ============================================================
            // MAIN FETCH: Replaces all Firebase logic.
            // Calls Laravel route GET /api/vouchers (no vendorID needed,
            // backend scopes via auth middleware).
            // ============================================================
            async initVouchers() {
                this.showLoader = true;
                try {
                    const response = await fetch('/voucher_master', {
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        }
                    });

                    if (!response.ok) {
                        console.error('Failed to fetch vouchers:', response.status);
                        this.showLoader = false;
                        return;
                    }

                    const json = await response.json();
                    const data = Array.isArray(json) ? json : json.data; // supports { data: [...] } or plain array

                    this.vouchers = data.map(v => ({
                        id:           v.id           ?? '',
                        voucher_name: v.voucher_name ?? '',
                        title:        v.title        ?? '',
                        description:  v.description  ?? '',
                        type:         v.type         ?? null,   // smallint
                        trigger:      v.trigger      ?? null,   // smallint
                        limit_type:   v.limit_type   ?? null,   // smallint
                        validity:     v.validity     ?? null,   // integer (days)
                        status:       v.status       ?? null,   // smallint
                        created_at:   v.created_at   ? new Date(v.created_at) : null,
                        created_by:   v.created_by   ?? '',

                        // Computed helpers

                        get editUrl() {
                            return `{{ route("voucher.edit", ":id") }}`.replace(':id', v.id);
                        },
                        
                        get typeLabel() {
                            // Adjust these mappings to match your smallint enum
                            const types = { 1: 'Free Product', 2: 'Partially Paid' };
                            return types[this.type] ?? '-';
                        },
                        get triggerLabel() {
                            const triggers = { 1: 'Registration', 2: 'Festive Offer', 3: 'Referral Link' };
                            return triggers[this.trigger] ?? '-';
                        },
                        get limitTypeLabel() {
                            const limits = { 1: 'One Time Use', 2: 'Max 2 redemption' };
                            return limits[this.limit_type] ?? '-';
                        },
                        get createdAtFormatted() {
                            if (!this.created_at) return { date: '-', time: '' };
                            return {
                                date: moment(this.created_at).format('DD.MM.YYYY'),
                                time: moment(this.created_at).format('HH:mm'),
                            };
                        },
                    }));

                } catch (e) {
                    console.error('Error fetching vouchers:', 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();
                        this.dropUp = (window.innerHeight - rect.bottom) < 250;
                    });
                }
            },

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

            get filteredVouchers() {
                let arr = [...this.vouchers];

                // Search by voucher_name or title
                if (this.searchTerm.trim()) {
                    const st = this.searchTerm.toLowerCase();
                    arr = arr.filter(v =>
                        v.voucher_name.toLowerCase().includes(st) ||
                        v.title.toLowerCase().includes(st)
                    );
                }

                // Filter by status (smallint stored as string in dropdown value)
                if (this.selectedStatus !== '') {
                    arr = arr.filter(v => String(v.status) === this.selectedStatus);
                }

                // Sort
                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 === 'created_at' && 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 paginatedVouchers() {
                const start = (this.currentPage - 1) * this.pageSize;
                return this.filteredVouchers.slice(start, start + Number(this.pageSize));
            },

            get endIndex() {
                const end = this.currentPage * this.pageSize;
                return end > this.filteredVouchers.length ? this.filteredVouchers.length : end;
            },

            prevPage() { if (this.currentPage > 1) this.currentPage--; },
            nextPage() { if (this.endIndex < this.filteredVouchers.length) this.currentPage++; },

            get paginationInfo() {
                if (!this.filteredVouchers.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.filteredVouchers.length}`;
            },

            // ============================================================
            // STATUS BADGE — maps smallint status to Tailwind CSS classes
            // ============================================================
            statusBadgeClass(s) {
                switch (parseInt(s)) {
                    case 1:  return 'bg-green-50 border !border-green-600 text-green-600';   // active
                    case 0:  return 'bg-slate-100 border !border-slate-500 text-slate-600';  // inactive
                    default: return 'bg-slate-100 border !border-slate-600 text-slate-600';
                }
            },

            statusIconClass(s) {
                switch (parseInt(s)) {
                    case 1:  return 'fa fa-check-circle';   // active
                    case 0:  return 'fa fa-ban';             // inactive
                    default: return 'fa fa-info-circle';
                }
            },

            translatedStatus(s) {
                switch (parseInt(s)) {
                    case 1:  return "{{ trans('lang.active') }}";
                    case 0:  return "{{ trans('lang.inactive') }}";
                    default: return '-';
                }
            },
        }
    }
</script>

@endsection