<button class="btn btn-primary mb-2" onclick="export2csv()">Download csv</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; ">
        <p class="p-1 " style="border:2px solid #fed7aa; ">Total Row <?php echo e($list->count() ?? 0); ?> </p>
        <p class="p-1 " style="border:2px solid #fed7aa; ">Total Amount <?php echo e($list->sum('paid_amount')); ?> TK</p>
        

        <p class="p-1 " style="border:2px solid #fed7aa; ">Total Discount: <?php echo e($list->sum('discount_amount')); ?></p>
    </div>
</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>
                <?php if(getBillingType() == 'day_to_day'): ?>
                    <th>Expire Date</th>
                <?php 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>
                


                <?php if($hideColumn == false): ?>
                    <th>Discount</th>
                    
                <?php elseif($hideColumn == true): ?>
                <?php endif; ?>
            </tr>
            </thead>
            <tbody>
            <?php ($totalDue = 0); ?>
            <?php $__currentLoopData = $list; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $p): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <tr>
                    <td><?php echo e($p->id); ?></td>
                    <td class="text-center"><?php echo e(date('d-M-Y h:i:s A', strtotime($p->created_at))); ?></td>
                    <td><?php echo e($p->income->head->name ?? ''); ?></td>
                    <td><?php echo e($p->clients->id ?? ''); ?></td>
                    <td><?php echo e($p->clientsinfo->clients_name ?? ''); ?></td>
                    <td><?php echo e($p->clients->userid ?? ''); ?></td>
                    <td>'<?php echo e($p->clientsinfo->contact_no ?? ''); ?></td>
                    <?php if(getBillingType() == 'day_to_day'): ?>
                        <td> <?php echo e($p->clients->expire_date); ?></td>
                    <?php endif; ?>
                    <td><?php echo e($p->clients->pop->reseller->name ?? ''); ?></td>
                    <td><?php echo e($p->clients->pop->popname ?? ''); ?></td>
                    <td><?php echo e($p->clients->clientsinfo->area ?? ''); ?></td>
                    <td><?php echo e($p->money_receipt_number); ?></td>
                    <td><?php echo e($p->user->name ?? ''); ?></td>
                    <td class="text-center"><?php echo e($p->employee->name ?? ''); ?></td>
                    <td> <?php echo e($p->clients->packages->package_name ?? ''); ?></td>
                    <td style="max-width: 150px"><?php echo e($p->description ?? ''); ?></td>
                    <td class="text-right"> <?php echo e($p->paid_amount); ?></td>
                    



                    <?php if($hideColumn == false): ?>
                        <td class="text-right"> <?php echo e($p->discount_amount); ?></td>
                        
                    <?php elseif($hideColumn == true): ?>
                    <?php endif; ?>
                </tr>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </tbody>


            <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>
                <?php if(getBillingType() == 'day_to_day'): ?>
                    <td> </td>
                <?php endif; ?>
                <td></td>
                <td class="text-right"><b>Total:</b> </td>
                <td class="text-right"><b><?php echo e($list->sum('paid_amount')); ?> TK</b></td>
                
                <?php if($hideColumn == false): ?>
                    <td class="text-right"><b><?php echo e($list->sum('discount_amount')); ?> TK</b></td>
                <?php elseif($hideColumn == true): ?>
                <?php 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");
    }

    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>
<?php /**PATH /var/www/html/fastbangla/radius-circle/resources/views/paymenthistory/result.blade.php ENDPATH**/ ?>