<button class="btn btn-primary mb-2" onclick="export2csv()">Download csv</button>
{{-- <button class="btn btn-danger mb-2" onclick="export2pdf()">Download PDF</button> --}}
<button class="btn btn-success mb-2" onclick="printTable()">🖨️ Print</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://unpkg.com/jspdf-autotable@3.6.0/dist/jspdf.plugin.autotable.js"></script>
<h2 id="printTitle" class="d-none text-center mb-2">Payment History</h2>
<div class="col-md-12">
    <div id="paymentSummary" class="float-right d-flex amount-container" style="text-align:center; gap:3px !important; ">
        @if(method_exists($list, 'total'))
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Row: {{ $list->total() }} (Showing: {{ $list->count() }})</p>
        @else
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Row {{ $list->count() ?? 0 }} </p>
        @endif
        @if(isset($totals))
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Amount: {{ number_format($totals->total_paid_amount ?? 0, 2) }} TK</p>
        @endif
        <p class="p-1 " style="border:2px solid #fed7aa; ">Page Amount: {{ number_format($list->sum('paid_amount'), 2) }} TK</p>
        {{-- @can('company_commission')
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Company Miscellaneous Expense
                {{ $list->sum('paid_amount') - $list->sum('sub_manager_commission') - $list->sum('manager_commission') }} TK
            </p>
        @endcan
        @can('manager_commission')
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Manager Miscellaneous Expense
                {{ $list->sum('manager_commission') }} TK</p>
        @endcan
        @can('sub_manager_commission')
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Sub Manager Miscellaneous Expense
                {{ $list->sum('sub_manager_commission') }} TK</p>
        @endcan --}}

        @if(isset($totals))
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Discount: {{ number_format($totals->total_discount_amount ?? 0, 2) }}</p>
        @endif
        <p class="p-1 " style="border:2px solid #fed7aa; ">Page Discount: {{ number_format($list->sum('discount_amount'), 2) }}</p>
        @if (globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable')
            @if(isset($totals))
                <p class="p-1 " style="border:2px solid #fed7aa; ">Total VAT Amount: {{ number_format($totals->total_vat_amount ?? 0, 2) }} TK</p>
                <p class="p-1 " style="border:2px solid #fed7aa; ">Total Reseller Commission: {{ number_format($totals->total_reseller_commission_amount ?? 0, 2) }} TK</p>
            @endif
            <p class="p-1 " style="border:2px solid #fed7aa; ">Page VAT Amount: {{ number_format($list->sum('vat_amount'), 2) }} TK</p>
            <p class="p-1 " style="border:2px solid #fed7aa; ">Page Reseller Commission: {{ number_format($list->sum('reseller_commission_amount'), 2) }} TK</p>
        @endif
    </div>
</div>
<br>
<div class="col-md-12">
{{-- Pagination Links (upper section) --}}
@if(method_exists($list, 'links'))
    <div class="mt-3 mb-3">
        {{ $list->appends(request()->except('page'))->links() }}
    </div>
    <div class="mt-2 mb-2 text-muted">
        <small>Showing {{ $list->firstItem() ?? 0 }} to {{ $list->lastItem() ?? 0 }} of {{ $list->total() }} results</small>
    </div>
@endif
</div>
<div id="paymenthistory" class="mt-10">
    <div class="table-responsive">
        <table class="table table-bordered " id="tableDownload">
            <thead>
            <tr>
                <th>#id</th>
                <th>Date</th>
                <th>Type</th>
                <th>CID</th>
                <th>C Name</th>
                <th>username</th>
                <th>Contact</th>
                @if (getBillingType() == 'day_to_day')
                    <th>Expire Date</th>
                @endif
                <th>Reseller</th>
                <th>POP</th>
                <th>Area</th>
                <th>MR ID</th>
                <th>Entry BY</th>
                <th>Col By</th>
                <th>Package</th>
                <th style="max-width: 150px">Description</th>
                <th>Amount</th>
                @if (globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable')
                    <th>Reseller VAT %</th>
                    <th>VAT Amount</th>
                    <th>Reseller Comm. %</th>
                    <th>Reseller Comm. Amt</th>
                @endif
                {{-- @can('company_commission')
                    <th>Company Miscellaneous Expense</th>
                @endcan
                @can('manager_commission')
                    <th>Manager Miscellaneous Expense</th>
                @endcan
                @can('sub_manager_commission')
                    <th>Sub Manager Miscellaneous Expense</th>
                @endcan --}}


                @if ($hideColumn == false)
                    <th>Discount</th>
                    {{-- <th>Due</th> --}}
                @elseif ($hideColumn == true)
                @endif
            </tr>
            </thead>
            <tbody>
            @php($totalDue = 0)
            @foreach ($list as $p)
                <tr>
                    <td>{{ $p->id }}</td>
                    <td class="text-center">{{ date('d-M-Y h:i:s A', strtotime($p->created_at)) }}</td>
                    <td>{{ $p->income->head->name ?? '' }}</td>
                    <td>{{ $p->clients->id ?? '' }}</td>
                    <td>{{ $p->clientsinfo->clients_name ?? '' }}</td>
                    <td>{{ $p->clients->userid ?? '' }}</td>
                    <td>'{{ $p->clientsinfo->contact_no ?? '' }}</td>
                    @if (getBillingType() == 'day_to_day')
                        <td> {{ $p->clients->expire_date }}</td>
                    @endif
                    <td>{{ $p->clients->pop->reseller->name ?? '' }}</td>
                    <td>{{ $p->clients->pop->popname ?? '' }}</td>
                    <td>{{ $p->clients->clientsinfo->area ?? '' }}</td>
                    <td>{{ $p->money_receipt_number }}</td>
                    <td>{{ $p->user->name ?? '' }}</td>
                    <td class="text-center">{{ $p->employee->name ?? '' }}</td>
                    <td> {{ $p->clients->packages->package_name ?? '' }}</td>
                    <td style="max-width: 150px">{{ $p->description ?? '' }}</td>
                    <td class="text-right"> {{ $p->paid_amount }}</td>
                    @if (globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable')
                        <td class="text-right">{{ $p->reseller_vat_percentage ?? 0 }}%</td>
                        <td class="text-right">{{ $p->vat_amount ?? 0 }}</td>
                        <td class="text-right">{{ $p->reseller_commission_percentage ?? 0 }}%</td>
                        <td class="text-right">{{ $p->reseller_commission_amount ?? 0 }}</td>
                    @endif
                    {{-- @can('company_commission')
                        <td class="text-right"> {{ $p->paid_amount - $p->sub_manager_commission - $p->manager_commission }}
                        </td>
                    @endcan
                    @can('manager_commission')
                        <td class="text-right"> {{ $p->manager_commission }}</td>
                    @endcan
                    @can('sub_manager_commission')
                        <td class="text-right"> {{ $p->sub_manager_commission }}</td>
                    @endcan --}}



                    @if ($hideColumn == false)
                        <td class="text-right"> {{ $p->discount_amount }}</td>
                        {{-- <td class="text-right">
                                {{ $p->clients->customerAccount->dueAmount > 0 ? $p->clients->customerAccount->dueAmount : 0 }}
                                @php($totalDue+= ($p->clients->customerAccount->dueAmount > 0 ? $p->clients->customerAccount->dueAmount : 0) )

                            </td> --}}
                    @elseif ($hideColumn == true)
                    @endif
                </tr>
            @endforeach
            </tbody>


            {{-- Totals row --}}
            @if (getBillingType() == 'day_to_day')
                <tr class="hidden">
                    {{-- 17 columns before Amount in day_to_day mode, we keep 1 for "Total:" --}}
                    @for ($i = 0; $i < 15; $i++)
                        <td></td>
                    @endfor
                    <td class="text-right"><b>Total:</b></td>
                    <td class="text-right"><b>{{ $list->sum('paid_amount') }} TK</b></td>
                    @if (globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable')
                        {{-- Reseller VAT % total not meaningful --}}
                        <td></td>
                        {{-- Total VAT amount --}}
                        <td class="text-right"><b>{{ $list->sum('vat_amount') }} TK</b></td>
                        {{-- Reseller commission % total not meaningful --}}
                        <td></td>
                        {{-- Total reseller commission amount --}}
                        <td class="text-right"><b>{{ $list->sum('reseller_commission_amount') }} TK</b></td>
                    @endif
                    @if ($hideColumn == false)
                        <td class="text-right"><b>{{ $list->sum('discount_amount') }} TK</b></td>
                    @endif
                </tr>
            @else
                <tr class="hidden">
                    {{-- 16 columns before Amount in normal mode, we keep 1 for "Total:" --}}
                    @for ($i = 0; $i < 14; $i++)
                        <td></td>
                    @endfor
                    <td class="text-right"><b>Total:</b></td>
                    <td class="text-right"><b>{{ $list->sum('paid_amount') }} TK</b></td>
                    @if (globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable')
                        {{-- Reseller VAT % total not meaningful --}}
                        <td></td>
                        {{-- Total VAT amount --}}
                        <td class="text-right"><b>{{ $list->sum('vat_amount') }} TK</b></td>
                        {{-- Reseller commission % total not meaningful --}}
                        <td></td>
                        {{-- Total reseller commission amount --}}
                        <td class="text-right"><b>{{ $list->sum('reseller_commission_amount') }} TK</b></td>
                    @endif
                    @if ($hideColumn == false)
                        <td class="text-right"><b>{{ $list->sum('discount_amount') }} TK</b></td>
                    @endif
                </tr>
            @endif
        </table>
    </div>
</div>

{{-- Pagination Links --}}
@if(method_exists($list, 'links'))
    <div class="mt-3">
        {{ $list->appends(request()->except('page'))->links() }}
    </div>
    <div class="mt-2 text-muted">
        <small>Showing {{ $list->firstItem() ?? 0 }} to {{ $list->lastItem() ?? 0 }} of {{ $list->total() }} results</small>
    </div>
@endif

<script>
    function export2csv() {
        // Add BOM for Excel to recognize UTF-8
        let data = "\uFEFF";
        const tableData = [];
        const rows = document.querySelectorAll("table#tableDownload tr");

        for (const row of rows) {
            const rowData = [];
            const cells = row.querySelectorAll("th, td");

            for (let i = 0; i < cells.length; i++) {
                const cellText = cells[i].innerText.trim();

                // Properly escape fields with quotes, commas, or newlines
                // Description is usually at index 13 (14th column)
                if (cellText.includes(',') || cellText.includes('\n') || cellText.includes('"') ||
                    i === 13 || cells[i].tagName === 'TH') {
                    // Double any quotes in the text and wrap in quotes
                    const escaped = cellText.replace(/"/g, '""');
                    rowData.push('"' + escaped + '"');
                } else {
                    rowData.push(cellText);
                }
            }

            tableData.push(rowData.join(","));
        }

        data += tableData.join("\r\n"); // Use CRLF for better Excel compatibility

        const a = document.createElement("a");
        a.href = URL.createObjectURL(new Blob([data], {
            type: "text/csv;charset=utf-8"
        }));
        a.setAttribute("download", "payment_history.csv");
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }


    function export2pdf() {
        const {
            jsPDF
        } = window.jspdf;
        const doc = new jsPDF({
            orientation: 'landscape' // Optional: use landscape orientation
        });


        doc.text("Payment History", 14, 10);
        doc.autoTable({
            html: "#tableDownload",
            startY: 20,
            theme: "grid",
            headStyles: {
                fillColor: [22, 160, 133]
            },
            didParseCell: function(data) {
                if (data.column.index === 13) {
                    data.cell.styles.cellWidth = 'auto';
                }
            },
            styles: {
                fontSize: 7
            },
            tableWidth: 'auto'
        });

        doc.save("data.pdf");
    }

    function printTable() {
        const table = document.getElementById('tableDownload');
        const summary = document.getElementById('paymentSummary');

        if (!table || table.rows.length <= 1) {
            alert('No data to print. Please search first.');
            return;
        }

        const printStyle = document.createElement('style');
        printStyle.id = 'payment-print-style';
        printStyle.innerHTML = `
            @media print {
                @page {
                    margin: 0.5cm;
                    size: A4 landscape;
                }

                * {
                    color: #000 !important;
                    -webkit-print-color-adjust: exact !important;
                    print-color-adjust: exact !important;
                    visibility: hidden;
                }

                nav, header, footer, .navbar, .sidebar,
                button, .btn,
                .filter-form,
                form {
                    display: none !important;
                }

                .card-body,
                .card-body * {
                    visibility: visible;
                }

                .card-body {
                    position: relative !important;
                    width: 100% !important;
                    padding: 0 !important;
                    margin: 0 !important;
                }

                #paymentSummary {
                    display: flex !important;
                    flex-direction: row !important;
                    justify-content: center !important;
                    gap: 10px !important;
                    margin-bottom: 15px !important;
                    width: 100% !important;
                }

                #paymentSummary p {
                    border: 1px solid #000 !important;
                    padding: 6px 12px !important;
                    margin: 0 !important;
                    font-size: 9px !important;
                }

                .amount-container {
                    flex-direction: row !important;
                }

                #printTitle {
                    display: block !important;
                    visibility: visible !important;
                    text-align: center !important;
                    margin-bottom: 15px !important;
                    font-size: 14px !important;
                    font-weight: bold !important;
                }

                #paymenthistory {
                    display: block !important;
                    width: 100% !important;
                }

                .table-responsive {
                    display: block !important;
                    overflow: visible !important;
                }

                #tableDownload {
                    width: 100% !important;
                    border-collapse: collapse !important;
                    font-size: 9px !important;
                }

                #tableDownload th,
                #tableDownload td {
                    border: 1px solid #000 !important;
                    padding: 4px !important;
                    font-size: 9px !important;
                }

                #tableDownload th {
                    font-weight: bold !important;
                }
            }
        `;

        const existingStyle = document.getElementById('payment-print-style');
        if (existingStyle) {
            existingStyle.remove();
        }

        document.head.appendChild(printStyle);
        window.print();
    }
</script>

<style>
    .amount-container {
        flex-direction: column;
    }

    @media (min-width:640px) {
        .amount-container {
            flex-direction: row;
        }
    }
</style>
