<!DOCTYPE html>
<html lang="en">
{% load static %}

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Processing Invoice Download...</title>

    <!-- Include JSZip for ZIP file creation -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script>

    <!-- Include jsPDF for PDF rendering -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

    <!-- Include html2pdf for converting HTML to PDF -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.min.js"></script>

    <style>
        /* Hide the invoice container from the user */
        #invoices {
            display: none;
        }
    </style>
</head>

<body>
    <div id="invoices"></div> <!-- This will hold dynamically inserted invoices -->

    <script>
        window.onload = function() {
            var invoiceIds = "{{ invoice_ids }}".split(',');

            if (invoiceIds.length === 0) {
                alert("No invoices selected.");
                return;
            }

            fetchInvoices(invoiceIds)
                .then(data => {
                    if (data.invoices && data.invoices.length > 0) {
                        if (invoiceIds.length === 1) {
                            processSingleInvoice(data.invoices[0]);  // Single PDF case
                        } else {
                            processInvoicesForZip(data.invoices);   // ZIP case for multiple PDFs
                        }
                    } else {
                        alert('No invoices found.');
                    }
                })
                .catch(error => {
                    console.error('Error fetching invoices: ', error);
                });
        };

        function fetchInvoices(invoiceIds) {
            return fetch(`/showcase/generate-pdfs/?invoice_ids=${invoiceIds.join(',')}`)
                .then(response => response.json());
        }

        // Process a single invoice and download as PDF
        function processSingleInvoice(invoice) {
            var invoiceContainer = document.getElementById('invoices');
            var invoiceDiv = document.createElement('div');
            invoiceDiv.id = `invoice_${invoice.id}`;
            invoiceDiv.innerHTML = invoice.rendered_html;
            invoiceContainer.appendChild(invoiceDiv);

            // Convert HTML to PDF using html2pdf.js and download as a single PDF
            html2pdf()
                .from(invoiceDiv)
                .set({
                    margin: 1,
                    filename: `${invoice.title}_invoice_${invoice.id}.pdf`,
                    html2canvas: { scale: 2 },
                    jsPDF: { orientation: 'portrait', unit: 'mm', format: 'a4' }
                })
                .save()
                .then(function() {
                    // Redirect back to the previous page after download
                    setTimeout(function() {
                        var previousUrl = document.referrer;
                        window.location.href = previousUrl;
                    }, 1000);
                });
        }

        // Process multiple invoices and merge them into a ZIP file
        async function processInvoicesForZip(invoices) {
            var zip = new JSZip();
            var invoiceContainer = document.getElementById('invoices');
            invoiceContainer.innerHTML = ''; // Clear container to append invoices

            // Create an array to hold all the promises
            let pdfPromises = invoices.map(function(invoice, index) {
                var invoiceDiv = document.createElement('div');
                invoiceDiv.id = `invoice_${invoice.id}`;
                invoiceDiv.innerHTML = invoice.rendered_html;
                invoiceContainer.appendChild(invoiceDiv);

                // Return a promise that resolves when the PDF is ready
                return html2pdf()
                    .from(invoiceDiv)
                    .set({
                        margin: 1,
                        filename: `${invoice.title}_invoice_${invoice.id}.pdf`,
                        html2canvas: { scale: 2 },
                        jsPDF: { orientation: 'portrait', unit: 'mm', format: 'a4' }
                    })
                    .outputPdf('blob')  // Generate PDF as Blob
                    .then(function(pdfBlob) {
                        // Add the generated PDF Blob to ZIP file
                        zip.file(`${invoice.title}_invoice_${invoice.id}.pdf`, pdfBlob);
                    });
            });

            // Wait for all the PDFs to be generated before generating the ZIP file
            await Promise.all(pdfPromises);

            // Generate the ZIP file and offer it for download
            zip.generateAsync({ type: 'blob' }).then(function(content) {
                var link = document.createElement('a');
                link.href = URL.createObjectURL(content);
                link.download = 'invoices.zip';
                link.click();

                // Redirect back to the previous page after download
                setTimeout(function() {
                    var previousUrl = document.referrer;
                    window.location.href = previousUrl;
                }, 1000);
            });
        }
    </script>
</body>

</html>
