@extends('layouts.app')

@section('title', 'عرض البيانات')

@section('content')
<div x-data="recordsTable()" x-init="loadRecords()">
    <div class="px-4 py-5 sm:p-6">
        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">عرض بيانات Excel</h3>

        <!-- Search and Filters -->
        <div class="bg-white shadow rounded-lg p-6 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <!-- Search -->
                <div class="md:col-span-2">
                    <label for="search" class="block text-sm font-medium text-gray-700 mb-2">بحث</label>
                    <input type="text" 
                           id="search" 
                           x-model="filters.search"
                           @input.debounce.500ms="loadRecords()"
                           placeholder="ابحث في الاسم، رقم الموبايل، العنوان..."
                           class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                </div>

                <!-- Governorate Filter -->
                <div>
                    <label for="governorate" class="block text-sm font-medium text-gray-700 mb-2">المحافظة</label>
                    <input type="text" 
                           id="governorate" 
                           x-model="filters.governorate"
                           @input.debounce.500ms="loadRecords()"
                           placeholder="المحافظة"
                           class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                </div>

                <!-- Membership Type Filter -->
                <div>
                    <label for="membership_type" class="block text-sm font-medium text-gray-700 mb-2">نوع العضوية</label>
                    <input type="text" 
                           id="membership_type" 
                           x-model="filters.membership_type"
                           @input.debounce.500ms="loadRecords()"
                           placeholder="نوع العضوية"
                           class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                </div>
            </div>
        </div>

        <!-- Data Table -->
        <div class="bg-white shadow rounded-lg overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th @click="sort('name')" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100">
                                الاسم
                                <span x-show="sortColumn === 'name'" x-text="sortDirection === 'asc' ? '↑' : '↓'"></span>
                            </th>
                            <th @click="sort('mobile_number')" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100">
                                رقم الموبايل
                                <span x-show="sortColumn === 'mobile_number'" x-text="sortDirection === 'asc' ? '↑' : '↓'"></span>
                            </th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">رقم بطاقة العضوية</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">العنوان</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الحي</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">المحافظة</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">تاريخ الانتهاء</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">نوع العضوية</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">ساري حق</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200" x-show="!loading">
                        <template x-for="record in records" :key="record.id">
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="record.name || '-'"></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="record.mobile_number || '-'"></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="record.membership_card_number || '-'"></td>
                                <td class="px-6 py-4 text-sm text-gray-900" x-text="(record.address || '-')"></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="record.neighborhood || '-'"></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="record.governorate || '-'"></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="record.expiry_date || '-'"></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="record.membership_type || '-'"></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="record.valid_status || '-'"></td>
                            </tr>
                        </template>
                        <tr x-show="records.length === 0 && !loading">
                            <td colspan="9" class="px-6 py-4 text-center text-sm text-gray-500">لا توجد بيانات</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Loading Indicator -->
            <div x-show="loading" x-cloak class="p-8 text-center">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
                <p class="mt-2 text-sm text-gray-500">جاري التحميل...</p>
            </div>

            <!-- Pagination -->
            <div x-show="!loading && total > 0" class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
                <div class="flex-1 flex justify-between sm:hidden">
                    <button @click="changePage(currentPage - 1)" 
                            :disabled="currentPage === 1"
                            class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50">
                        السابق
                    </button>
                    <button @click="changePage(currentPage + 1)" 
                            :disabled="currentPage === lastPage"
                            class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50">
                        التالي
                    </button>
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-gray-700">
                            عرض
                            <span class="font-medium" x-text="from"></span>
                            إلى
                            <span class="font-medium" x-text="to"></span>
                            من
                            <span class="font-medium" x-text="total"></span>
                            نتيجة
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                            <button @click="changePage(currentPage - 1)" 
                                    :disabled="currentPage === 1"
                                    class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                                السابق
                            </button>
                            <template x-for="page in getPageNumbers()" :key="page">
                                <button @click="changePage(page)" 
                                        :class="page === currentPage ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'"
                                        class="relative inline-flex items-center px-4 py-2 border text-sm font-medium"
                                        x-text="page">
                                </button>
                            </template>
                            <button @click="changePage(currentPage + 1)" 
                                    :disabled="currentPage === lastPage"
                                    class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                                التالي
                            </button>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function recordsTable() {
    return {
        records: [],
        loading: false,
        currentPage: 1,
        lastPage: 1,
        perPage: 50,
        total: 0,
        from: 0,
        to: 0,
        sortColumn: 'id',
        sortDirection: 'desc',
        filters: {
            search: '',
            governorate: '',
            membership_type: ''
        },

        async loadRecords() {
            this.loading = true;
            
            const params = new URLSearchParams({
                page: this.currentPage,
                per_page: this.perPage,
                sort_column: this.sortColumn,
                sort_direction: this.sortDirection,
            });

            if (this.filters.search) {
                params.append('search', this.filters.search);
            }

            const filterParams = {};
            if (this.filters.governorate) {
                filterParams.governorate = this.filters.governorate;
            }
            if (this.filters.membership_type) {
                filterParams.membership_type = this.filters.membership_type;
            }

            if (Object.keys(filterParams).length > 0) {
                Object.entries(filterParams).forEach(([key, value]) => {
                    params.append(`filters[${key}]`, value);
                });
            }

            try {
                const response = await fetch(`/api/records?${params.toString()}`);
                const data = await response.json();
                
                this.records = data.data;
                this.currentPage = data.current_page;
                this.lastPage = data.last_page;
                this.total = data.total;
                this.from = data.from || 0;
                this.to = data.to || 0;
            } catch (error) {
                console.error('Error loading records:', error);
            } finally {
                this.loading = false;
            }
        },

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

        changePage(page) {
            if (page >= 1 && page <= this.lastPage) {
                this.currentPage = page;
                this.loadRecords();
            }
        },

        getPageNumbers() {
            const pages = [];
            const maxPages = 5;
            let start = Math.max(1, this.currentPage - Math.floor(maxPages / 2));
            let end = Math.min(this.lastPage, start + maxPages - 1);
            
            if (end - start < maxPages - 1) {
                start = Math.max(1, end - maxPages + 1);
            }
            
            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
            
            return pages;
        }
    }
}
</script>
@endsection

