<button class="btn btn-primary mb-2" onclick="export2csv()">Download csv</button>
<button class="btn btn-danger mb-2" onclick="export2pdf()">Download PDF</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>
<div class="col-md-12">
    <div class=" float-right d-flex amount-container" style="text-align:center; gap:3px !important; ">
        <p class="p-1 " style="border:2px solid #fed7aa; ">Total Row {{ $list->count() ?? 0 }} </p>
        <p class="p-1 " style="border:2px solid #fed7aa; ">Total Amount {{ $list->sum('paid_amount') }} 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

        <p class="p-1 " style="border:2px solid #fed7aa; ">Total Discount: {{ $list->sum('discount_amount') }}</p>
    </div>
</div>
<div id="paymenthistory" class="mt-10">
    <div class="table-responsive">
        <table class="table table-bordered " id="tableDownload">
            <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>
                @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>

            @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>
                    @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

            <tr class="hidden">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                @if (getBillingType() == 'day_to_day')
                    <td> </td>
                @endif
                <td></td>
                <td class="text-right"><b>Total:</b> </td>
                <td class="text-right"><b>{{ $list->sum('paid_amount') }} TK</b></td>
                @can('company_commission')
                    <td class="text-right">
                        <b>{{ $list->sum('paid_amount') - $list->sum('sub_manager_commission') - $list->sum('manager_commission') }}
                            TK</b></td>
                @endcan
                @can('manager_commission')
                    <td class="text-right"><b>{{ $list->sum('manager_commission') }} TK</b></td>
                @endcan
                @can('sub_manager_commission')
                    <td class="text-right"><b>{{ $list->sum('sub_manager_commission') }} TK</b></td>
                @endcan
                @if ($hideColumn == false)
                    <td class="text-right"><b>{{ $list->sum('discount_amount') }} TK</b></td>
                @elseif ($hideColumn == true)
                @endif
            </tr>
        </table>
    </div>
</div>

<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");
    }
</script>

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

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