<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>كشف حساب - {{ $page->name ?? 'غير محدد' }}</title>
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    @if(isset($settings['font_print']) && $settings['font_print'])
        <link href="https://fonts.googleapis.com/css2?family={{ str_replace(' ', '+', $settings['font_print']) }}:wght@400;500;700;900&display=swap" rel="stylesheet">
    @else
        <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;900&display=swap" rel="stylesheet">
    @endif
    
    <!-- Include html2pdf & xlsx-js-style -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xlsx-js-style@1.2.0/dist/xlsx.min.js"></script>
    
    <!-- Scripts & Tailwind -->
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    
    <style>
        body {
            font-family: '{{ $settings['font_print'] ?? 'Tajawal' }}', sans-serif;
            background-color: #f8fafc;
            color: #0f172a;
        }
        
        .print-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
            background: white;
            min-height: 100vh;
            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
        }

        /* Modern Table Styling */
        table {
            border-collapse: collapse;
            width: 100%;
        }
        
        @media print {
            body { background: white; }
            .print-container { box-shadow: none; padding: 0; margin: 0; max-width: 100%; min-height: auto; }
            .no-print { display: none !important; }
            @page { margin: 1cm; }
            
            /* Better page breaks for table rows */
            tr { page-break-inside: avoid; }
            thead { display: table-header-group; }
            tfoot { display: table-footer-group; }
            
            /* Enforce background colors in print */
            * {
                -webkit-print-color-adjust: exact !important;
                color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            .page-number:after { content: counter(page); }
        }
        
        @media screen {
            .page-number:after { content: '1'; } /* Placeholder for screen */
        }
    </style>
</head>
<body>

    <div class="no-print bg-slate-800 text-white p-4 sticky top-0 z-50 flex justify-between items-center shadow-lg">
        <div class="font-bold">خيارات التقرير</div>
        <div class="flex gap-2">
            <button onclick="window.print()" class="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 rounded shadow font-bold text-sm flex items-center gap-2">
                <span>🖨️ طباعة / PDF</span>
            </button>
            <button onclick="exportExcel()" class="bg-emerald-600 hover:bg-emerald-500 text-white px-4 py-2 rounded shadow font-bold text-sm flex items-center gap-2">
                <span>📊 تصدير Excel</span>
            </button>
            <button onclick="window.close()" class="bg-slate-600 hover:bg-slate-500 text-white px-4 py-2 rounded shadow font-bold text-sm flex items-center gap-2">
                <span>إغلاق</span>
            </button>
        </div>
    </div>

    <div class="print-container flex flex-col justify-between">
        
        <div>
            <!-- HEADER -->
        <div class="border-b-2 border-indigo-900 pb-6 mb-6 flex justify-between items-start">
            <div class="space-y-1">
                <h1 class="text-xl font-black text-indigo-900 mb-2">{{ $page->ledger->entity->name ?? $settings['site_name'] ?? 'اسم الشركة' }}</h1>
                @if($page->ledger->branch) <div class="text-xs font-bold text-slate-700">الفرع: {{ $page->ledger->branch->name }}</div> @endif
                @if($page->ledger->center) <div class="text-xs font-bold text-slate-700">المركز: {{ $page->ledger->center->name }}</div> @endif
                @if($page->ledger->project) <div class="text-xs font-bold text-slate-700">المشروع: {{ $page->ledger->project->name }}</div> @endif
            </div>
            
            <div class="text-left space-y-1">
                <h2 class="text-lg font-black text-slate-800 mb-2">كشف حساب</h2>
                <div class="text-xs font-bold text-slate-700">{{ $page->name }} <span dir="ltr">({{ $page->page_number }})</span></div>
                <div class="text-xs font-bold text-slate-700">{{ $page->ledger->name }} <span dir="ltr">({{ $page->ledger->code }})</span></div>
                <div class="text-xs font-bold text-slate-700">
                    الفترة: 
                    @if($dateFrom || $dateTo)
                        من <span dir="ltr">{{ $dateFrom ?? 'البداية' }}</span> إلى <span dir="ltr">{{ $dateTo ?? 'النهاية' }}</span>
                    @else
                        كافة العمليات
                    @endif
                </div>
            </div>
        </div>

        <!-- PARTIES INFO -->
        <div class="mb-4 text-xs font-bold border border-slate-300 bg-slate-50">
            <div class="flex flex-col sm:flex-row sm:items-center px-3 py-1.5 {{ !isset($hideCreditParty) || !$hideCreditParty ? 'border-b border-slate-200' : '' }}">
                <div class="flex items-center ml-4 shrink-0 whitespace-nowrap">
                    <div class="w-2 h-2 ml-2 shrink-0" style="background-color: {{ $settings['color_debit_text'] ?? '#166534' }}"></div>
                    <span class="text-slate-600">الطرف المدين:</span>
                </div>
                <div class="flex flex-wrap items-center gap-x-4">
                    <div class="text-slate-900">{{ $page->debitAccount->party->name ?? '-' }} <span class="text-[11px] text-slate-500 ml-1" dir="ltr">({{ $page->debitAccount->party->code ?? '-' }})</span></div>
                    <div class="text-slate-300 hidden sm:block">|</div>
                    <div class="text-slate-700">الحساب: {{ $page->debitAccount->name ?? '-' }} <span class="text-indigo-700 ml-1" dir="ltr">[{{ $page->debitAccount->account_number ?? '-' }}]</span></div>
                </div>
            </div>
            @if(!isset($hideCreditParty) || !$hideCreditParty)
            <div class="flex flex-col sm:flex-row sm:items-center px-3 py-1.5">
                <div class="flex items-center ml-4 shrink-0 whitespace-nowrap">
                    <div class="w-2 h-2 ml-2 shrink-0" style="background-color: {{ $settings['color_credit_text'] ?? '#991b1b' }}"></div>
                    <span class="text-slate-600">الطرف الدائن:</span>
                </div>
                <div class="flex flex-wrap items-center gap-x-4">
                    <div class="text-slate-900">{{ $page->creditAccount->party->name ?? '-' }} <span class="text-[11px] text-slate-500 ml-1" dir="ltr">({{ $page->creditAccount->party->code ?? '-' }})</span></div>
                    <div class="text-slate-300 hidden sm:block">|</div>
                    <div class="text-slate-700">الحساب: {{ $page->creditAccount->name ?? '-' }} <span class="text-indigo-700 ml-1" dir="ltr">[{{ $page->creditAccount->account_number ?? '-' }}]</span></div>
                </div>
            </div>
            @endif
        </div>

        <!-- TABLE -->
        <table id="report-table" class="w-full text-right text-xs mb-8 border-collapse">
            <thead class="bg-indigo-50 text-indigo-900" style="border-bottom: 2px solid #c7d2fe;">
                <tr>
                    <th class="px-3 py-3 font-bold text-center w-12 border border-slate-200">#</th>
                    <th class="px-3 py-3 font-bold border border-slate-200 whitespace-nowrap w-[1%]">التاريخ</th>
                    @if(!$hideTransactionNumber) <th class="px-3 py-3 font-bold border border-slate-200">رقم الحركة</th> @endif
                    <th class="px-3 py-3 font-bold border border-slate-200">البيان</th>
                    @if(!$hideReference) <th class="px-3 py-3 font-bold border border-slate-200">المرجع</th> @endif
                    <th class="px-3 py-3 font-bold border border-slate-200 whitespace-nowrap w-[1%]">مدين (+)</th>
                    <th class="px-3 py-3 font-bold border border-slate-200 whitespace-nowrap w-[1%]">دائن (-)</th>
                    <th class="px-3 py-3 font-bold border border-slate-200 whitespace-nowrap w-[1%]">الرصيد</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-200">
                @if($withOpeningBalance)
                <tr class="bg-slate-50 font-bold" style="background-color: #f8fafc;">
                    <td class="px-3 py-3 text-center border border-slate-200">-</td>
                    <td class="px-3 py-3 border border-slate-200 whitespace-nowrap">{{ $dateFrom ?? '-' }}</td>
                    @if(!$hideTransactionNumber) <td class="px-3 py-3 border border-slate-200">-</td> @endif
                    <td class="px-3 py-3 border border-slate-200">رصيد افتتاحي (ما قبل الفترة)</td>
                    @if(!$hideReference) <td class="px-3 py-3 border border-slate-200">-</td> @endif
                    <td class="px-3 py-3 border border-slate-200 text-left whitespace-nowrap" dir="ltr">{{ $openingDebit > 0 ? number_format($openingDebit, 2) : '-' }}</td>
                    <td class="px-3 py-3 border border-slate-200 text-left whitespace-nowrap" dir="ltr">{{ $openingCredit > 0 ? number_format($openingCredit, 2) : '-' }}</td>
                    <td class="px-3 py-3 border border-slate-200 text-left font-black whitespace-nowrap" dir="ltr" style="color: {{ $openingBalance > 0 ? ($settings['color_debit_text'] ?? '#166534') : ($openingBalance < 0 ? ($settings['color_credit_text'] ?? '#991b1b') : '#1e293b') }}">{{ $openingBalance > 0 ? '+' : ($openingBalance < 0 ? '-' : '') }}{{ number_format(abs($openingBalance), 2) }}</td>
                </tr>
                @endif

                @foreach($transactions as $index => $trx)
                <tr style="{{ $trx->type === 'note' ? 'background-color: #fffbeb;' : '' }}" class="font-bold text-slate-900">
                    <td class="px-3 py-2 text-center border border-slate-200 text-[11px]">{{ $index + 1 }}</td>
                    <td class="px-3 py-2 border border-slate-200 text-[11px] whitespace-nowrap" dir="ltr">{{ $trx->transaction_date->format($settings['date_format'] ?? 'Y-m-d') }}</td>
                    @if(!$hideTransactionNumber) 
                        <td class="px-3 py-2 border border-slate-200 text-[11px] whitespace-nowrap" dir="ltr">
                            {{ $trx->transaction_number }}
                            @if($trx->type === 'note') 📝 @endif
                        </td> 
                    @endif
                    <td class="px-3 py-2 border border-slate-200">{{ $trx->description }}</td>
                    @if(!$hideReference) <td class="px-3 py-2 border border-slate-200 text-[11px] whitespace-nowrap">{{ $trx->reference_number ?? '-' }}</td> @endif
                    
                    @if($trx->type === 'note')
                        <td class="px-3 py-2 border border-slate-200 text-center text-slate-400">-</td>
                        <td class="px-3 py-2 border border-slate-200 text-center text-slate-400">-</td>
                    @else
                        <td class="px-3 py-2 border border-slate-200 text-left font-bold whitespace-nowrap" dir="ltr" style="color: {{ $trx->debit_amount > 0 ? ($settings['color_debit_text'] ?? '#166534') : 'inherit' }}">
                            {{ $trx->debit_amount > 0 ? number_format($trx->debit_amount, 2) : '-' }}
                        </td>
                        <td class="px-3 py-2 border border-slate-200 text-left font-bold whitespace-nowrap" dir="ltr" style="color: {{ $trx->credit_amount > 0 ? ($settings['color_credit_text'] ?? '#991b1b') : 'inherit' }}">
                            {{ $trx->credit_amount > 0 ? number_format($trx->credit_amount, 2) : '-' }}
                        </td>
                    @endif
                    
                    <td class="px-3 py-2 border border-slate-200 text-left font-black whitespace-nowrap" dir="ltr" style="color: {{ $trx->running_balance > 0 ? ($settings['color_debit_text'] ?? '#166534') : ($trx->running_balance < 0 ? ($settings['color_credit_text'] ?? '#991b1b') : '#1e293b') }}">
                        {{ $trx->running_balance > 0 ? '+' : ($trx->running_balance < 0 ? '-' : '') }}{{ number_format(abs($trx->running_balance), 2) }}
                    </td>
                </tr>
                @endforeach
            </tbody>
            
            <!-- TOTALS -->
            <tfoot class="bg-indigo-50 font-black" style="background-color: #eef2ff; border-top: 2px solid #c7d2fe;">
                <tr>
                    <td colspan="{{ 3 + ($hideTransactionNumber ? 0 : 1) + ($hideReference ? 0 : 1) }}" class="px-3 py-4 text-left border border-slate-200">الإجماليات الكلية:</td>
                    <td class="px-3 py-4 text-left border border-slate-200 whitespace-nowrap" dir="ltr" style="color: {{ $settings['color_debit_text'] ?? '#166534' }}">
                        {{ number_format($totalDebit, 2) }}
                    </td>
                    <td class="px-3 py-4 text-left border border-slate-200 whitespace-nowrap" dir="ltr" style="color: {{ $settings['color_credit_text'] ?? '#991b1b' }}">
                        {{ number_format($totalCredit, 2) }}
                    </td>
                    <td class="px-3 py-4 text-left border border-slate-200 whitespace-nowrap" dir="ltr" style="color: {{ $netBalance > 0 ? ($settings['color_debit_text'] ?? '#166534') : ($netBalance < 0 ? ($settings['color_credit_text'] ?? '#991b1b') : '#1e293b') }}">
                        {{ $netBalance > 0 ? '+' : ($netBalance < 0 ? '-' : '') }}{{ number_format(abs($netBalance), 2) }}
                    </td>
                </tr>
                <tr style="background-color: #f8fafc;">
                    <td colspan="{{ 6 + ($hideTransactionNumber ? 0 : 1) + ($hideReference ? 0 : 1) }}" class="px-2 py-1.5 border border-slate-200 text-right leading-snug">
                        <div class="text-xs font-bold text-slate-600">الرصيد كتابة: <span class="text-indigo-700 font-black">{{ $tafqeet ?: 'صفر' }}</span></div>
                        <div class="text-xs font-bold text-slate-600">الحالة النهائية: <span class="text-indigo-900 font-black">{{ $finalStatus }}</span></div>
                    </td>
                </tr>
            </tfoot>
        </table>
        </div>

        <!-- NOTES -->
        <div class="mt-auto text-center text-xs font-bold text-slate-600 border-t border-slate-200 pt-6 mb-6">
            {{ $settings['footer_print_notes'] ?? '' }}
        </div>

        <!-- PRINT FOOTER (Right, Center, Left) -->
        <div class="w-full flex justify-between items-center text-[11px] font-bold text-slate-500 border-t border-slate-200 pt-4 pb-2">
            <div class="text-right">{!! $footerRight !!}</div>
            <div class="text-center">{!! $footerCenter !!}</div>
            <div class="text-left" dir="ltr">{!! $footerLeft !!}</div>
        </div>
    </div>

    <!-- Export Excel Script -->
    <script>
        function exportExcel() {
            var data = [];
            var mergeCells = [];
            var r = 0;
            
            // --- Styles ---
            var titleStyle = { font: { bold: true, sz: 16, color: { rgb: "FFFFFF" } }, fill: { fgColor: { rgb: "312e81" } }, alignment: { horizontal: "center", vertical: "center" } };
            var subHeaderStyle = { font: { bold: true, sz: 12 }, alignment: { horizontal: "center" } };
            var boldCenter = { font: { bold: true }, alignment: { horizontal: "center", vertical: "center" } };
            var boldRight = { font: { bold: true }, alignment: { horizontal: "right", vertical: "center" } };
            var amountStyle = { numFmt: "#,##0.00", alignment: { horizontal: "center", vertical: "center" } };
            var boldAmountStyle = { font: { bold: true }, numFmt: "#,##0.00", alignment: { horizontal: "center", vertical: "center" }, fill: { fgColor: { rgb: "f8fafc" } } };
            var partiesHeaderStyle = { font: { bold: true }, fill: { fgColor: { rgb: "e2e8f0" } }, alignment: { horizontal: "center", vertical: "center" } };
            var tableHeaderStyle = { font: { bold: true, color: { rgb: "FFFFFF" } }, fill: { fgColor: { rgb: "4f46e5" } }, alignment: { horizontal: "center", vertical: "center" } };

            // 1. Company Name
            data.push([{ v: "{{ $page->ledger->entity->name ?? $settings['site_name'] ?? 'اسم الشركة' }}", s: titleStyle }]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 7 } }); r++;

            // 2. Report Name & Ledger
            data.push([{ v: "كشف حساب: {{ $page->name }} ({{ $page->page_number }})", s: subHeaderStyle }]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 7 } }); r++;
            
            data.push([{ v: "الدفتر: {{ $page->ledger->name }} ({{ $page->ledger->code }})", s: subHeaderStyle }]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 7 } }); r++;

            // 3. Period
            data.push([{ v: "الفترة: @if($dateFrom || $dateTo) من {{ $dateFrom ?? 'البداية' }} إلى {{ $dateTo ?? 'النهاية' }} @else كافة العمليات @endif", s: boldCenter }]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 7 } }); r++;

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

            // 4. Parties Info
            @if(!isset($hideCreditParty) || !$hideCreditParty)
            data.push([
                { v: "الطرف المدين", s: partiesHeaderStyle }, "", "", "",
                { v: "الطرف الدائن", s: partiesHeaderStyle }
            ]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 3 } });
            mergeCells.push({ s: { r: r, c: 4 }, e: { r: r, c: 7 } }); r++;

            data.push([
                { v: "الاسم: {{ $page->debitAccount->party->name ?? '-' }} ({{ $page->debitAccount->party->code ?? '-' }})", s: boldRight }, "", "", "",
                { v: "الاسم: {{ $page->creditAccount->party->name ?? '-' }} ({{ $page->creditAccount->party->code ?? '-' }})", s: boldRight }
            ]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 3 } });
            mergeCells.push({ s: { r: r, c: 4 }, e: { r: r, c: 7 } }); r++;

            data.push([
                { v: "الحساب: {{ $page->debitAccount->name ?? '-' }} [{{ $page->debitAccount->account_number ?? '-' }}]", s: boldRight }, "", "", "",
                { v: "الحساب: {{ $page->creditAccount->name ?? '-' }} [{{ $page->creditAccount->account_number ?? '-' }}]", s: boldRight }
            ]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 3 } });
            mergeCells.push({ s: { r: r, c: 4 }, e: { r: r, c: 7 } }); r++;
            @else
            data.push([{ v: "الطرف المدين", s: partiesHeaderStyle }]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 7 } }); r++;

            data.push([{ v: "الاسم: {{ $page->debitAccount->party->name ?? '-' }} ({{ $page->debitAccount->party->code ?? '-' }})", s: boldRight }]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 7 } }); r++;

            data.push([{ v: "الحساب: {{ $page->debitAccount->name ?? '-' }} [{{ $page->debitAccount->account_number ?? '-' }}]", s: boldRight }]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: 7 } }); r++;
            @endif

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

            // 5. Table Headers
            var colHeaders = [
                { v: "#", s: tableHeaderStyle },
                { v: "التاريخ", s: tableHeaderStyle }
            ];
            @if(!$hideTransactionNumber) colHeaders.push({ v: "رقم الحركة", s: tableHeaderStyle }); @endif
            @if(!$hideReference) colHeaders.push({ v: "المرجع", s: tableHeaderStyle }); @endif
            colHeaders.push(
                { v: "البيان", s: tableHeaderStyle },
                { v: "مدين (+)", s: tableHeaderStyle },
                { v: "دائن (-)", s: tableHeaderStyle },
                { v: "الرصيد", s: tableHeaderStyle }
            );
            data.push(colHeaders); r++;

            // 6. Transactions
            @if(isset($withOpeningBalance) && $withOpeningBalance)
            var openingRow = [
                { v: "-", s: boldCenter },
                { v: "-", s: boldCenter }
            ];
            @if(!$hideTransactionNumber) openingRow.push({ v: "-", s: boldCenter }); @endif
            @if(!$hideReference) openingRow.push({ v: "-", s: boldCenter }); @endif
            openingRow.push(
                { v: "الرصيد الافتتاحي", s: { font: { bold: true }, alignment: { horizontal: "right", vertical: "center" }, fill: { fgColor: { rgb: "f8fafc" } } } },
                { v: {{ $openingBalance > 0 ? $openingBalance : 0 }}, s: boldAmountStyle },
                { v: {{ $openingBalance < 0 ? abs($openingBalance) : 0 }}, s: boldAmountStyle },
                { v: {{ $openingBalance }}, s: boldAmountStyle }
            );
            data.push(openingRow); r++;
            @endif

            @foreach($transactions as $index => $trx)
            var trxRow = [
                { v: {{ $index + 1 }}, s: boldCenter },
                { v: "{{ $trx->transaction_date->format($settings['date_format'] ?? 'Y-m-d') }}", s: boldCenter }
            ];
            @if(!$hideTransactionNumber) trxRow.push({ v: "{{ $trx->transaction_number }}", s: boldCenter }); @endif
            @if(!$hideReference) trxRow.push({ v: "{{ $trx->reference_number ?? '-' }}", s: boldCenter }); @endif
            trxRow.push(
                { v: "{!! addslashes(str_replace(["\r", "\n"], ' ', $trx->description)) !!}" + (@if(isset($withNotes) && $withNotes && $trx->notes) " - {!! addslashes(str_replace(["\r", "\n"], ' ', $trx->notes)) !!}" @else "" @endif), s: { font: { bold: true }, alignment: { horizontal: "right", vertical: "center" } } },
                { v: {{ $trx->debit_amount }}, s: amountStyle },
                { v: {{ $trx->credit_amount }}, s: amountStyle },
                { v: {{ $trx->running_balance }}, s: boldAmountStyle }
            );
            data.push(trxRow); r++;
            @endforeach

            // 7. Totals
            var totalRow = [
                { v: "", s: boldCenter },
                { v: "", s: boldCenter }
            ];
            @if(!$hideTransactionNumber) totalRow.push({ v: "", s: boldCenter }); @endif
            @if(!$hideReference) totalRow.push({ v: "", s: boldCenter }); @endif
            totalRow.push(
                { v: "الإجمالي", s: { font: { bold: true, sz: 12 }, alignment: { horizontal: "center", vertical: "center" }, fill: { fgColor: { rgb: "e2e8f0" } } } },
                { v: {{ $totalDebit }}, s: { font: { bold: true }, numFmt: "#,##0.00", alignment: { horizontal: "center", vertical: "center" }, fill: { fgColor: { rgb: "e2e8f0" } } } },
                { v: {{ $totalCredit }}, s: { font: { bold: true }, numFmt: "#,##0.00", alignment: { horizontal: "center", vertical: "center" }, fill: { fgColor: { rgb: "e2e8f0" } } } },
                { v: {{ $netBalance }}, s: { font: { bold: true, color: { rgb: "FFFFFF" } }, numFmt: "#,##0.00", alignment: { horizontal: "center", vertical: "center" }, fill: { fgColor: { rgb: "4338ca" } } } }
            );
            data.push(totalRow); r++;

            data.push([]); r++; // Empty row
            
            // 8. Footer (Final Status)
            var finalColsCount = 3;
            @if(!$hideTransactionNumber) finalColsCount++; @endif
            @if(!$hideReference) finalColsCount++; @endif
            
            var finalStatusStyle = { font: { bold: true, sz: 12, color: { rgb: "1e3a8a" } }, alignment: { horizontal: "right", vertical: "center" } };
            data.push([{ v: "الرصيد كتابة: {{ $tafqeet ?: 'صفر' }}", s: finalStatusStyle }]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: finalColsCount + 3 } }); r++;
            
            data.push([{ v: "الحالة النهائية: {{ $finalStatus }}", s: finalStatusStyle }]);
            mergeCells.push({ s: { r: r, c: 0 }, e: { r: r, c: finalColsCount + 3 } }); r++;

            // --- Create Worksheet ---
            var ws = XLSX.utils.aoa_to_sheet(data);
            
            // Apply RTL
            ws['!dir'] = 'rtl';
            
            // Apply Merges
            ws['!merges'] = mergeCells;
            
            // Set Column Widths
            var cols = [
                { wpx: 40 },  // #
                { wpx: 90 }   // Date
            ];
            @if(!$hideTransactionNumber) cols.push({ wpx: 90 }); @endif
            @if(!$hideReference) cols.push({ wpx: 90 }); @endif
            cols.push(
                { wpx: 350 }, // Description
                { wpx: 110 }, // Debit
                { wpx: 110 }, // Credit
                { wpx: 120 }  // Balance
            );
            ws['!cols'] = cols;

            var wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "كشف حساب");
            XLSX.writeFile(wb, "كشف_حساب_{{ $page->ledger->name }}_{{ date('Ymd') }}.xlsx");
        }
    </script>
</body>
</html>
