<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">
            <!-- 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="reference_number" wire:click="toggleColumn('reference_number')" @if($columns['reference_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="document_number" wire:click="toggleColumn('document_number')" @if($columns['document_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="phone" wire:click="toggleColumn('phone')" @if($columns['phone']) 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="email" wire:click="toggleColumn('email')" @if($columns['email']) 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="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>
                تصدير
            </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['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['reference_number']) <th class="px-4 py-3 font-bold">رقم المرجع</th> @endif
                        @if($columns['document_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['phone']) <th class="px-4 py-3 font-bold">الجوال</th> @endif
                        @if($columns['email']) <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['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($parties as $index => $party)
                    <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">{{ $party->code }}</td> @endif
                        @if($columns['name']) <td class="px-4 py-3 font-bold text-slate-800">{{ $party->name }}</td> @endif
                        @if($columns['short_name']) <td class="px-4 py-3 text-slate-600">{{ $party->short_name ?: '-' }}</td> @endif
                        @if($columns['reference_number']) <td class="px-4 py-3 text-slate-600" dir="ltr">{{ $party->reference_number ?: '-' }}</td> @endif
                        @if($columns['document_number']) <td class="px-4 py-3 text-slate-600" dir="ltr">{{ $party->document_number ?: '-' }}</td> @endif
                        @if($columns['tax_number']) <td class="px-4 py-3 text-slate-600" dir="ltr">{{ $party->tax_number ?: '-' }}</td> @endif
                        @if($columns['phone']) <td class="px-4 py-3 text-slate-600" dir="ltr">{{ $party->phone ?: '-' }}</td> @endif
                        @if($columns['email']) <td class="px-4 py-3 text-slate-600">{{ $party->email ?: '-' }}</td> @endif
                        @if($columns['address']) <td class="px-4 py-3 text-slate-600">{{ $party->address ?: '-' }}</td> @endif
                        @if($columns['is_active'])
                        <td class="px-4 py-3 text-center">
                            @if($party->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">{{ $party->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="parties-data" type="application/json">
        {!! json_encode($parties) !!}
    </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 Columns
            for (var key in colsState) {
                if (colsState[key]) {
                    query.push('columns[' + key + ']=1');
                }
            }
            var url = "{{ route('reports.parties.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 parties = JSON.parse(document.getElementById('parties-data').textContent || '[]');
            
            var activeColsCount = 1;
            for(var key in colsState) { if(colsState[key]) activeColsCount++; }

            var reportTitle = "بيان الأطراف";

            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['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['reference_number']) colHeaders.push({ v: "رقم المرجع", s: tableHeaderStyle });
            if(colsState['document_number']) colHeaders.push({ v: "الهوية/السجل", s: tableHeaderStyle });
            if(colsState['tax_number']) colHeaders.push({ v: "الرقم الضريبي", s: tableHeaderStyle });
            if(colsState['phone']) colHeaders.push({ v: "الجوال", s: tableHeaderStyle });
            if(colsState['email']) colHeaders.push({ v: "الإيميل", s: tableHeaderStyle });
            if(colsState['address']) 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++;

            parties.forEach(function(party, index) {
                var row = [{ v: index + 1, s: boldCenter }];
                
                if(colsState['code']) row.push({ v: party.code || '-', s: centerStyle });
                if(colsState['name']) row.push({ v: party.name || '-', s: boldCenter });
                if(colsState['short_name']) row.push({ v: party.short_name || '-', s: centerStyle });
                if(colsState['reference_number']) row.push({ v: party.reference_number || '-', s: centerStyle });
                if(colsState['document_number']) row.push({ v: party.document_number || '-', s: centerStyle });
                if(colsState['tax_number']) row.push({ v: party.tax_number || '-', s: centerStyle });
                if(colsState['phone']) row.push({ v: party.phone || '-', s: centerStyle });
                if(colsState['email']) row.push({ v: party.email || '-', s: centerStyle });
                if(colsState['address']) row.push({ v: party.address || '-', s: centerStyle });
                if(colsState['is_active']) {
                    var status = party.is_active ? 'نشط' : 'غير نشط';
                    row.push({ v: status, s: { font: { bold: true, color: { rgb: party.is_active ? "15803d" : "b91c1c" } }, alignment: { horizontal: "center", vertical: "center" } } });
                }
                if(colsState['created_at']) {
                    var formattedDate = party.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['code']) colWidths.push({ wpx: 80 });
            if(colsState['name']) colWidths.push({ wpx: 200 });
            if(colsState['short_name']) colWidths.push({ wpx: 120 });
            if(colsState['reference_number']) colWidths.push({ wpx: 120 });
            if(colsState['document_number']) colWidths.push({ wpx: 120 });
            if(colsState['tax_number']) colWidths.push({ wpx: 120 });
            if(colsState['phone']) colWidths.push({ wpx: 120 });
            if(colsState['email']) colWidths.push({ wpx: 150 });
            if(colsState['address']) 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>
