<div>
    <style>
        @media print {
            nav, footer { display: none !important; }
            main, .max-w-7xl { max-width: 100% !important; margin: 0 !important; padding: 0 !important; }
            .no-print { display: none !important; }
            body { background: white !important; }
            * {
                -webkit-print-color-adjust: exact !important;
                color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        }
    </style>

    <script src="https://cdn.jsdelivr.net/npm/xlsx-js-style@1.2.0/dist/xlsx.min.js"></script>

    <!-- Toolbar (No Print) -->
    <div class="no-print flex flex-col md:flex-row justify-between items-center bg-white p-4 rounded-2xl shadow-sm border border-slate-100 mb-6 gap-4">
        <div>
            <h1 class="text-xl font-black text-slate-800">بيان المراكز</h1>
            <p class="text-xs text-slate-500 mt-1">كشف تفصيلي ببيانات المراكز (مراكز التكلفة/المراكز الرئيسية)</p>
        </div>

        <div class="flex items-center gap-3 flex-wrap">
            
            <!-- Entity Filter -->
            <div class="w-full md:w-56" x-data="{
                open: false,
                search: '',
                selected: @entangle('entity_id').live,
                options: {{ Js::from($entities->map(fn($e) => ['id' => $e->id, 'name' => $e->name])) }},
                get filteredOptions() {
                    return this.search === '' ? this.options : this.options.filter(o => o.name.includes(this.search));
                },
                get selectedName() {
                    let opt = this.options.find(o => o.id == this.selected);
                    return opt ? opt.name : 'جميع الكيانات';
                }
            }" @click.away="open = false">
                <div class="relative">
                    <button @click="open = !open" type="button" class="w-full text-right bg-white border border-slate-200 rounded-xl px-4 py-2.5 text-sm focus:ring-indigo-500 focus:border-indigo-500 shadow-sm flex items-center justify-between">
                        <span x-text="selectedName" class="font-bold text-slate-700"></span>
                        <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
                    </button>

                    <div x-show="open" x-cloak class="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-xl shadow-xl overflow-hidden" style="display: none;">
                        <div class="p-2 border-b border-slate-100 bg-slate-50">
                            <input type="text" x-model="search" placeholder="ابحث عن كيان..." class="w-full border-slate-200 rounded-lg text-sm py-1.5 px-3 focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                        <ul class="max-h-48 overflow-y-auto py-1">
                            <li @click="selected = ''; open = false; search = ''" 
                                class="px-4 py-2 text-sm cursor-pointer hover:bg-slate-50 transition-colors"
                                :class="selected == '' ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-slate-700'">
                                جميع الكيانات
                            </li>
                            <template x-for="option in filteredOptions" :key="option.id">
                                <li @click="selected = option.id; open = false; search = ''" 
                                    class="px-4 py-2 text-sm cursor-pointer hover:bg-slate-50 transition-colors"
                                    :class="selected == option.id ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-slate-700'">
                                    <span x-text="option.name"></span>
                                </li>
                            </template>
                            <li x-show="filteredOptions.length === 0" class="px-4 py-3 text-sm text-slate-500 text-center">لا توجد نتائج</li>
                        </ul>
                    </div>
                </div>
                <input type="hidden" id="entity_id_filter" :value="selected">
            </div>

            <!-- Branch Filter -->
            <div class="w-full md:w-56" wire:key="branch-filter-{{ $entity_id }}" x-data="{
                open: false,
                search: '',
                selected: @entangle('branch_id').live,
                options: {{ Js::from($branches->map(fn($b) => ['id' => $b->id, 'name' => $b->name])) }},
                get filteredOptions() {
                    return this.search === '' ? this.options : this.options.filter(o => o.name.includes(this.search));
                },
                get selectedName() {
                    let opt = this.options.find(o => o.id == this.selected);
                    return opt ? opt.name : 'جميع الفروع';
                }
            }" @click.away="open = false">
                <div class="relative">
                    <button @click="open = !open" type="button" class="w-full text-right bg-white border border-slate-200 rounded-xl px-4 py-2.5 text-sm focus:ring-indigo-500 focus:border-indigo-500 shadow-sm flex items-center justify-between">
                        <span x-text="selectedName" class="font-bold text-slate-700"></span>
                        <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
                    </button>

                    <div x-show="open" x-cloak class="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-xl shadow-xl overflow-hidden" style="display: none;">
                        <div class="p-2 border-b border-slate-100 bg-slate-50">
                            <input type="text" x-model="search" placeholder="ابحث عن فرع..." class="w-full border-slate-200 rounded-lg text-sm py-1.5 px-3 focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                        <ul class="max-h-48 overflow-y-auto py-1">
                            <li @click="selected = ''; open = false; search = ''" 
                                class="px-4 py-2 text-sm cursor-pointer hover:bg-slate-50 transition-colors"
                                :class="selected == '' ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-slate-700'">
                                جميع الفروع
                            </li>
                            <template x-for="option in filteredOptions" :key="option.id">
                                <li @click="selected = option.id; open = false; search = ''" 
                                    class="px-4 py-2 text-sm cursor-pointer hover:bg-slate-50 transition-colors"
                                    :class="selected == option.id ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-slate-700'">
                                    <span x-text="option.name"></span>
                                </li>
                            </template>
                            <li x-show="filteredOptions.length === 0" class="px-4 py-3 text-sm text-slate-500 text-center">لا توجد نتائج</li>
                        </ul>
                    </div>
                </div>
                <input type="hidden" id="branch_id_filter" :value="selected">
            </div>

            <!-- Columns Dropdown -->
            <div class="relative" x-data="{ open: false }" @click.away="open = false">
                <button @click="open = !open" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-xl shadow-sm font-bold text-sm flex items-center gap-2 transition">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2"></path></svg>
                    الأعمدة
                    <svg class="w-3 h-3 transition-transform" :class="{'rotate-180': open}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
                </button>
                <div x-show="open" x-transition class="absolute right-0 mt-2 w-56 bg-white rounded-xl shadow-lg border border-slate-100 p-2 z-50 text-sm" style="display: none;">
                    <label class="flex items-center gap-2 p-2 hover:bg-slate-50 rounded cursor-pointer">
                        <input type="checkbox" data-column="entity" wire:click="toggleColumn('entity')" @if($columns['entity']) checked @endif class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                        <span class="font-bold text-slate-700">الكيان</span>
                    </label>
                    <label class="flex items-center gap-2 p-2 hover:bg-slate-50 rounded cursor-pointer">
                        <input type="checkbox" data-column="branch" wire:click="toggleColumn('branch')" @if($columns['branch']) checked @endif class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                        <span class="font-bold text-slate-700">الفرع</span>
                    </label>
                    <label class="flex items-center gap-2 p-2 hover:bg-slate-50 rounded cursor-pointer">
                        <input type="checkbox" data-column="code" wire:click="toggleColumn('code')" @if($columns['code']) checked @endif class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                        <span class="font-bold text-slate-700">الرمز</span>
                    </label>
                    <label class="flex items-center gap-2 p-2 hover:bg-slate-50 rounded cursor-pointer">
                        <input type="checkbox" data-column="name" wire:click="toggleColumn('name')" @if($columns['name']) checked @endif class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                        <span class="font-bold text-slate-700">الاسم</span>
                    </label>
                    <label class="flex items-center gap-2 p-2 hover:bg-slate-50 rounded cursor-pointer">
                        <input type="checkbox" data-column="address" wire:click="toggleColumn('address')" @if($columns['address']) checked @endif class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                        <span class="font-bold text-slate-700">العنوان</span>
                    </label>
                    <label class="flex items-center gap-2 p-2 hover:bg-slate-50 rounded cursor-pointer">
                        <input type="checkbox" data-column="notes" wire:click="toggleColumn('notes')" @if($columns['notes']) checked @endif class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                        <span class="font-bold text-slate-700">الملاحظات</span>
                    </label>
                    <label class="flex items-center gap-2 p-2 hover:bg-slate-50 rounded cursor-pointer">
                        <input type="checkbox" data-column="is_active" wire:click="toggleColumn('is_active')" @if($columns['is_active']) checked @endif class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                        <span class="font-bold text-slate-700">الحالة</span>
                    </label>
                    <label class="flex items-center gap-2 p-2 hover:bg-slate-50 rounded cursor-pointer">
                        <input type="checkbox" data-column="created_at" wire:click="toggleColumn('created_at')" @if($columns['created_at']) checked @endif class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                        <span class="font-bold text-slate-700">تاريخ الإضافة</span>
                    </label>
                </div>
            </div>

            <!-- Print Button -->
            <button onclick="openPrint()" class="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 rounded-xl shadow-sm font-bold text-sm flex items-center gap-2 transition">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path></svg>
                طباعة
            </button>

            <!-- Excel Export Button -->
            <button onclick="exportExcel()" class="bg-emerald-600 hover:bg-emerald-500 text-white px-4 py-2 rounded-xl shadow-sm font-bold text-sm flex items-center gap-2 transition">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
                تصدير Excel
            </button>
        </div>
    </div>

    <!-- Table Container -->
    <div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-sm text-right">
                <thead class="bg-indigo-50 text-indigo-900 border-b-2 border-indigo-100">
                    <tr>
                        <th class="px-4 py-3 font-bold w-12 text-center">#</th>
                        @if($columns['entity']) <th class="px-4 py-3 font-bold">الكيان</th> @endif
                        @if($columns['branch']) <th class="px-4 py-3 font-bold">الفرع</th> @endif
                        @if($columns['code']) <th class="px-4 py-3 font-bold">الرمز</th> @endif
                        @if($columns['name']) <th class="px-4 py-3 font-bold">الاسم</th> @endif
                        @if($columns['address']) <th class="px-4 py-3 font-bold">العنوان</th> @endif
                        @if($columns['notes']) <th class="px-4 py-3 font-bold">الملاحظات</th> @endif
                        @if($columns['is_active']) <th class="px-4 py-3 font-bold text-center">الحالة</th> @endif
                        @if($columns['created_at']) <th class="px-4 py-3 font-bold">تاريخ الإضافة</th> @endif
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    @forelse($centers as $index => $center)
                    <tr class="hover:bg-slate-50 transition-colors">
                        <td class="px-4 py-3 text-center text-slate-500 font-bold">{{ $index + 1 }}</td>
                        @if($columns['entity']) <td class="px-4 py-3 text-slate-800">{{ $center->branch->entity->name ?? '-' }}</td> @endif
                        @if($columns['branch']) <td class="px-4 py-3 text-slate-800 font-bold">{{ $center->branch->name ?? '-' }}</td> @endif
                        @if($columns['code']) <td class="px-4 py-3 font-bold text-indigo-700" dir="ltr">{{ $center->code }}</td> @endif
                        @if($columns['name']) <td class="px-4 py-3 font-bold text-slate-800">{{ $center->name }}</td> @endif
                        @if($columns['address']) <td class="px-4 py-3 text-slate-600">{{ $center->address ?: '-' }}</td> @endif
                        @if($columns['notes']) <td class="px-4 py-3 text-slate-600">{{ $center->notes ?: '-' }}</td> @endif
                        @if($columns['is_active'])
                        <td class="px-4 py-3 text-center">
                            @if($center->is_active)
                                <span class="bg-emerald-100 text-emerald-700 px-2 py-0.5 rounded text-xs font-bold print:bg-transparent print:text-emerald-700">نشط</span>
                            @else
                                <span class="bg-red-100 text-red-700 px-2 py-0.5 rounded text-xs font-bold print:bg-transparent print:text-red-700">غير نشط</span>
                            @endif
                        </td>
                        @endif
                        @if($columns['created_at']) <td class="px-4 py-3 text-slate-500 text-xs" dir="ltr">{{ $center->created_at->format('Y-m-d') }}</td> @endif
                    </tr>
                    @empty
                    <tr>
                        <td colspan="20" class="px-4 py-8 text-center text-slate-500 font-bold">لا يوجد مراكز مسجلة بعد.</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <!-- Data Island for JS Export -->
    <script id="centers-data" type="application/json">
        {!! json_encode($centers) !!}
    </script>

    <!-- JavaScript Functions -->
    <script>
        function getActiveColumns() {
            var cols = {};
            document.querySelectorAll('input[data-column]').forEach(function(checkbox) {
                cols[checkbox.getAttribute('data-column')] = checkbox.checked;
            });
            return cols;
        }

        function openPrint() {
            var colsState = getActiveColumns();
            var query = [];
            
            // Add Filters
            var entityId = document.getElementById('entity_id_filter').value;
            if(entityId) {
                query.push('entity_id=' + entityId);
            }
            var branchId = document.getElementById('branch_id_filter').value;
            if(branchId) {
                query.push('branch_id=' + branchId);
            }

            // Add Columns
            for (var key in colsState) {
                if (colsState[key]) {
                    query.push('columns[' + key + ']=1');
                }
            }
            var url = "{{ route('reports.centers.print') }}?" + query.join('&');
            window.open(url, '_blank');
        }

        function exportExcel() {
            var data = [];
            var r = 0;
            
            var titleStyle = { font: { bold: true, sz: 16, color: { rgb: "FFFFFF" } }, fill: { fgColor: { rgb: "312e81" } }, alignment: { horizontal: "center", vertical: "center" } };
            var tableHeaderStyle = { font: { bold: true, color: { rgb: "FFFFFF" } }, fill: { fgColor: { rgb: "4f46e5" } }, alignment: { horizontal: "center", vertical: "center" } };
            var centerStyle = { alignment: { horizontal: "center", vertical: "center" } };
            var boldCenter = { font: { bold: true }, alignment: { horizontal: "center", vertical: "center" } };

            var colsState = getActiveColumns();
            var centers = JSON.parse(document.getElementById('centers-data').textContent || '[]');
            
            var activeColsCount = 1;
            for(var key in colsState) { if(colsState[key]) activeColsCount++; }

            var entityId = document.getElementById('entity_id_filter').value;
            var entityName = document.querySelector('div[wire\\:key^="branch-filter"]')?.previousElementSibling?.querySelector('span[x-text="selectedName"]')?.innerText || '';
            if(entityName === 'جميع الكيانات') entityName = '';
            
            var branchId = document.getElementById('branch_id_filter').value;
            var branchName = document.querySelector('div[wire\\:key^="branch-filter"]')?.querySelector('span[x-text="selectedName"]')?.innerText || '';
            if(branchName === 'جميع الفروع') branchName = '';

            var reportTitle = "بيان المراكز";
            if(entityId && branchId) {
                reportTitle += " - الكيان: " + entityName + " - الفرع: " + branchName;
            } else if (entityId) {
                reportTitle += " - الكيان: " + entityName;
            } else if (branchId) {
                reportTitle += " - الفرع: " + branchName;
            }

            data.push([{ v: reportTitle, s: titleStyle }]);
            var mergeCells = [{ s: { r: r, c: 0 }, e: { r: r, c: activeColsCount - 1 } }]; 
            r++;

            data.push([]); r++; 

            var colHeaders = [{ v: "#", s: tableHeaderStyle }];
            if(colsState['entity']) colHeaders.push({ v: "الكيان", s: tableHeaderStyle });
            if(colsState['branch']) colHeaders.push({ v: "الفرع", s: tableHeaderStyle });
            if(colsState['code']) colHeaders.push({ v: "الرمز", s: tableHeaderStyle });
            if(colsState['name']) colHeaders.push({ v: "الاسم", s: tableHeaderStyle });
            if(colsState['address']) colHeaders.push({ v: "العنوان", s: tableHeaderStyle });
            if(colsState['notes']) colHeaders.push({ v: "الملاحظات", s: tableHeaderStyle });
            if(colsState['is_active']) colHeaders.push({ v: "الحالة", s: tableHeaderStyle });
            if(colsState['created_at']) colHeaders.push({ v: "تاريخ الإضافة", s: tableHeaderStyle });
            
            data.push(colHeaders); r++;

            centers.forEach(function(center, index) {
                var row = [{ v: index + 1, s: boldCenter }];
                
                var entityNameValue = center.branch && center.branch.entity ? center.branch.entity.name : '-';
                var branchNameValue = center.branch ? center.branch.name : '-';

                if(colsState['entity']) row.push({ v: entityNameValue, s: boldCenter });
                if(colsState['branch']) row.push({ v: branchNameValue, s: boldCenter });
                if(colsState['code']) row.push({ v: center.code || '-', s: centerStyle });
                if(colsState['name']) row.push({ v: center.name || '-', s: boldCenter });
                if(colsState['address']) row.push({ v: center.address || '-', s: centerStyle });
                if(colsState['notes']) row.push({ v: center.notes || '-', s: centerStyle });
                if(colsState['is_active']) {
                    var status = center.is_active ? 'نشط' : 'غير نشط';
                    row.push({ v: status, s: { font: { bold: true, color: { rgb: center.is_active ? "15803d" : "b91c1c" } }, alignment: { horizontal: "center", vertical: "center" } } });
                }
                if(colsState['created_at']) {
                    var formattedDate = center.created_at;
                    if(formattedDate && formattedDate.includes('T')) {
                        formattedDate = formattedDate.split('T')[0];
                    }
                    row.push({ v: formattedDate || '-', s: centerStyle });
                }
                
                data.push(row); r++;
            });

            var ws = XLSX.utils.aoa_to_sheet(data);
            ws['!dir'] = 'rtl';
            ws['!merges'] = mergeCells;
            
            var colWidths = [{ wpx: 40 }];
            if(colsState['entity']) colWidths.push({ wpx: 150 });
            if(colsState['branch']) colWidths.push({ wpx: 150 });
            if(colsState['code']) colWidths.push({ wpx: 80 });
            if(colsState['name']) colWidths.push({ wpx: 200 });
            if(colsState['address']) colWidths.push({ wpx: 250 });
            if(colsState['notes']) colWidths.push({ wpx: 250 });
            if(colsState['is_active']) colWidths.push({ wpx: 80 });
            if(colsState['created_at']) colWidths.push({ wpx: 100 });
            
            ws['!cols'] = colWidths;

            var wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "بيان المراكز");
            
            var today = new Date().toISOString().split('T')[0];
            XLSX.writeFile(wb, "بيان_المراكز_" + today + ".xlsx");
        }
    </script>
</div>
