<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; }
            
            /* Enforce background colors in print */
            * {
                -webkit-print-color-adjust: exact !important;
                color-adjust: exact !important;
                print-color-adjust: exact !important;
            }

            .print-only { display: block !important; }
        }
        
        .print-only { display: none; }
    </style>

    <!-- Include xlsx-js-style for Excel Export -->
    <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">
            <!-- 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="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="short_name" wire:click="toggleColumn('short_name')" @if($columns['short_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="commercial_record" wire:click="toggleColumn('commercial_record')" @if($columns['commercial_record']) 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="unified_number" wire:click="toggleColumn('unified_number')" @if($columns['unified_number']) 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="tax_number" wire:click="toggleColumn('tax_number')" @if($columns['tax_number']) 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>

    <!-- Print Header -->
    <div class="print-only border-b-2 border-indigo-900 pb-4 mb-6">
        <h1 class="text-2xl font-black text-indigo-900 mb-1">{{ $settings['site_name'] ?? 'اسم الشركة' }}</h1>
        <h2 class="text-lg font-bold text-slate-800">بيان الكيانات</h2>
        <div class="text-xs text-slate-500 mt-1">تاريخ الطباعة: {{ now()->format('Y-m-d H:i') }}</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" id="entities-table">
                <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['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['short_name']) <th class="px-4 py-3 font-bold">الاسم المختصر</th> @endif
                        @if($columns['commercial_record']) <th class="px-4 py-3 font-bold">السجل التجاري</th> @endif
                        @if($columns['unified_number']) <th class="px-4 py-3 font-bold">الرقم الموحد</th> @endif
                        @if($columns['tax_number']) <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($entities as $index => $entity)
                    <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['code']) <td class="px-4 py-3 font-bold text-indigo-700" dir="ltr">{{ $entity->code }}</td> @endif
                        @if($columns['name']) <td class="px-4 py-3 font-bold text-slate-800">{{ $entity->name }}</td> @endif
                        @if($columns['short_name']) <td class="px-4 py-3 text-slate-600">{{ $entity->short_name ?: '-' }}</td> @endif
                        @if($columns['commercial_record']) <td class="px-4 py-3 text-slate-600">{{ $entity->commercial_record ?: '-' }}</td> @endif
                        @if($columns['unified_number']) <td class="px-4 py-3 text-slate-600">{{ $entity->unified_number ?: '-' }}</td> @endif
                        @if($columns['tax_number']) <td class="px-4 py-3 text-slate-600">{{ $entity->tax_number ?: '-' }}</td> @endif
                        @if($columns['address']) <td class="px-4 py-3 text-slate-600">{{ $entity->address ?: '-' }}</td> @endif
                        @if($columns['notes']) <td class="px-4 py-3 text-slate-600">{{ $entity->notes ?: '-' }}</td> @endif
                        @if($columns['is_active'])
                        <td class="px-4 py-3 text-center">
                            @if($entity->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">{{ $entity->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>

    <!-- 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 = [];
            for (var key in colsState) {
                if (colsState[key]) {
                    query.push('columns[' + key + ']=1');
                }
            }
            var url = "{{ route('reports.entities.print') }}?" + query.join('&');
            window.open(url, '_blank');
        }

        function exportExcel() {
            var data = [];
            var r = 0;
            
            // --- Styles ---
            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" } };

            // Get columns state from DOM
            var colsState = getActiveColumns();
            
            // 1. Title
            var activeColsCount = 1; // For the '#' column
            for(var key in colsState) {
                if(colsState[key]) activeColsCount++;
            }

            data.push([{ v: "بيان الكيانات", s: titleStyle }]);
            
            // Merge cells for title
            var mergeCells = [];
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: activeColsCount - 1 } }); 
            r++;

            data.push([]); r++; // Empty row

            // 2. Table Headers
            var colHeaders = [{ v: "#", s: tableHeaderStyle }];
            if(colsState['code']) colHeaders.push({ v: "الرمز", s: tableHeaderStyle });
            if(colsState['name']) colHeaders.push({ v: "الاسم", s: tableHeaderStyle });
            if(colsState['short_name']) colHeaders.push({ v: "الاسم المختصر", s: tableHeaderStyle });
            if(colsState['commercial_record']) colHeaders.push({ v: "السجل التجاري", s: tableHeaderStyle });
            if(colsState['unified_number']) colHeaders.push({ v: "الرقم الموحد", s: tableHeaderStyle });
            if(colsState['tax_number']) 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++;

            // 3. Rows
            var entities = @json($entities);
            
            entities.forEach(function(entity, index) {
                var row = [{ v: index + 1, s: boldCenter }];
                
                if(colsState['code']) row.push({ v: entity.code || '-', s: centerStyle });
                if(colsState['name']) row.push({ v: entity.name || '-', s: boldCenter });
                if(colsState['short_name']) row.push({ v: entity.short_name || '-', s: centerStyle });
                if(colsState['commercial_record']) row.push({ v: entity.commercial_record || '-', s: centerStyle });
                if(colsState['unified_number']) row.push({ v: entity.unified_number || '-', s: centerStyle });
                if(colsState['tax_number']) row.push({ v: entity.tax_number || '-', s: centerStyle });
                if(colsState['address']) row.push({ v: entity.address || '-', s: centerStyle });
                if(colsState['notes']) row.push({ v: entity.notes || '-', s: centerStyle });
                if(colsState['is_active']) {
                    var status = entity.is_active ? 'نشط' : 'غير نشط';
                    row.push({ v: status, s: { font: { bold: true, color: { rgb: entity.is_active ? "15803d" : "b91c1c" } }, alignment: { horizontal: "center", vertical: "center" } } });
                }
                if(colsState['created_at']) {
                    var date = new Date(entity.created_at);
                    var formattedDate = date.toISOString().split('T')[0];
                    row.push({ v: formattedDate, s: centerStyle });
                }
                
                data.push(row); r++;
            });

            // --- Create Worksheet ---
            var ws = XLSX.utils.aoa_to_sheet(data);
            
            // Apply RTL
            ws['!dir'] = 'rtl';
            
            // Apply Merges
            ws['!merges'] = mergeCells;
            
            // Set Column Widths based on active columns
            var colWidths = [{ wpx: 40 }]; // #
            if(colsState['code']) colWidths.push({ wpx: 80 });
            if(colsState['name']) colWidths.push({ wpx: 200 });
            if(colsState['short_name']) colWidths.push({ wpx: 120 });
            if(colsState['commercial_record']) colWidths.push({ wpx: 120 });
            if(colsState['unified_number']) colWidths.push({ wpx: 120 });
            if(colsState['tax_number']) colWidths.push({ wpx: 120 });
            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>
