<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; ">
        <?php if(method_exists($list, 'total')): ?>
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Row: <?php echo e($list->total()); ?> (Showing: <?php echo e($list->count()); ?>)</p>
        <?php else: ?>
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Row <?php echo e($list->count() ?? 0); ?> </p>
        <?php endif; ?>
        <?php if(isset($totals)): ?>
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Amount: <?php echo e(number_format($totals->total_paid_amount ?? 0, 2)); ?> TK</p>
        <?php endif; ?>
        <p class="p-1 " style="border:2px solid #fed7aa; ">Page Amount: <?php echo e(number_format($list->sum('paid_amount'), 2)); ?> TK</p>
        

        <?php if(isset($totals)): ?>
            <p class="p-1 " style="border:2px solid #fed7aa; ">Total Discount: <?php echo e(number_format($totals->total_discount_amount ?? 0, 2)); ?></p>
        <?php endif; ?>
        <p class="p-1 " style="border:2px solid #fed7aa; ">Page Discount: <?php echo e(number_format($list->sum('discount_amount'), 2)); ?></p>
        <?php if(globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable'): ?>
            <?php if(isset($totals)): ?>
                <p class="p-1 " style="border:2px solid #fed7aa; ">Total VAT Amount: <?php echo e(number_format($totals->total_vat_amount ?? 0, 2)); ?> TK</p>
                <p class="p-1 " style="border:2px solid #fed7aa; ">Total Reseller Commission: <?php echo e(number_format($totals->total_reseller_commission_amount ?? 0, 2)); ?> TK</p>
            <?php endif; ?>
            <p class="p-1 " style="border:2px solid #fed7aa; ">Page VAT Amount: <?php echo e(number_format($list->sum('vat_amount'), 2)); ?> TK</p>
            <p class="p-1 " style="border:2px solid #fed7aa; ">Page Reseller Commission: <?php echo e(number_format($list->sum('reseller_commission_amount'), 2)); ?> TK</p>
        <?php endif; ?>
    </div>
</div>
<br>
<div class="col-md-12">

<?php if(method_exists($list, 'links')): ?>
    <div class="mt-3 mb-3">
        <?php echo e($list->appends(request()->except('page'))->links()); ?>

    </div>
    <div class="mt-2 mb-2 text-muted">
        <small>Showing <?php echo e($list->firstItem() ?? 0); ?> to <?php echo e($list->lastItem() ?? 0); ?> of <?php echo e($list->total()); ?> results</small>
    </div>
<?php 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>
                <?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(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>
                <?php endif; ?>
                


                <?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(globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable'): ?>
                        <td class="text-right"><?php echo e($p->reseller_vat_percentage ?? 0); ?>%</td>
                        <td class="text-right"><?php echo e($p->vat_amount ?? 0); ?></td>
                        <td class="text-right"><?php echo e($p->reseller_commission_percentage ?? 0); ?>%</td>
                        <td class="text-right"><?php echo e($p->reseller_commission_amount ?? 0); ?></td>
                    <?php endif; ?>
                    



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


            
            <?php if(getBillingType() == 'day_to_day'): ?>
                <tr class="hidden">
                    
                    <?php for($i = 0; $i < 15; $i++): ?>
                        <td></td>
                    <?php endfor; ?>
                    <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(globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable'): ?>
                        
                        <td></td>
                        
                        <td class="text-right"><b><?php echo e($list->sum('vat_amount')); ?> TK</b></td>
                        
                        <td></td>
                        
                        <td class="text-right"><b><?php echo e($list->sum('reseller_commission_amount')); ?> TK</b></td>
                    <?php endif; ?>
                    <?php if($hideColumn == false): ?>
                        <td class="text-right"><b><?php echo e($list->sum('discount_amount')); ?> TK</b></td>
                    <?php endif; ?>
                </tr>
            <?php else: ?>
                <tr class="hidden">
                    
                    <?php for($i = 0; $i < 14; $i++): ?>
                        <td></td>
                    <?php endfor; ?>
                    <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(globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable'): ?>
                        
                        <td></td>
                        
                        <td class="text-right"><b><?php echo e($list->sum('vat_amount')); ?> TK</b></td>
                        
                        <td></td>
                        
                        <td class="text-right"><b><?php echo e($list->sum('reseller_commission_amount')); ?> TK</b></td>
                    <?php endif; ?>
                    <?php if($hideColumn == false): ?>
                        <td class="text-right"><b><?php echo e($list->sum('discount_amount')); ?> TK</b></td>
                    <?php endif; ?>
                </tr>
            <?php endif; ?>
        </table>
    </div>
</div>


<?php if(method_exists($list, 'links')): ?>
    <div class="mt-3">
        <?php echo e($list->appends(request()->except('page'))->links()); ?>

    </div>
    <div class="mt-2 text-muted">
        <small>Showing <?php echo e($list->firstItem() ?? 0); ?> to <?php echo e($list->lastItem() ?? 0); ?> of <?php echo e($list->total()); ?> results</small>
    </div>
<?php 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>
<?php /**PATH /var/www/html/extranet/radius-circle/resources/views/paymenthistory/result.blade.php ENDPATH**/ ?>