// PDF Generation for Maintenance module
// Extracted from maintenance.php inline JS

// Ensure escapeHtml exists
if (typeof escapeHtml !== 'function') {
    function escapeHtml(text) {
        return String(text || '').replace(/[&"'<>]/g, function (s) {
            return ({'&':'&amp;','"':'&quot;',"'":"&#39;","<":"&lt;",">":"&gt;"})[s];
        });
    }
}

function generateWorkOrderPDF(jobId) {
    const fallbackWindow = window.open('', '_blank');
    $.get('api/maintenance.php', { action: 'job_details', job_id: jobId }, function (res) {
        if (res.status !== 'success') {
            alert('Unable to load job details');
            if (fallbackWindow && !fallbackWindow.closed) {
                fallbackWindow.close();
            }
            return;
        }

        const job = res.data;
        exportMaintenancePdfFromPreviewWindow(
            createWorkOrderPreviewHTML(job),
            `work_order_${job.work_order_number || job.id}.pdf`,
            fallbackWindow,
            `Work Order ${escapeHtml(job.work_order_number || job.id)}`
        );
    });
}

function generateJobOrderPDF(jobId) {
    const fallbackWindow = window.open('', '_blank');
    $.get('api/maintenance.php', { action: 'job_details', job_id: jobId }, function (res) {
        if (res.status !== 'success') {
            alert('Unable to load job details');
            if (fallbackWindow && !fallbackWindow.closed) {
                fallbackWindow.close();
            }
            return;
        }

        const job = res.data;
        exportMaintenancePdfFromPreviewWindow(
            createJobOrderPreviewHTML(job),
            `job_order_${job.work_order_number || job.id}.pdf`,
            fallbackWindow,
            `Job Order ${escapeHtml(job.work_order_number || job.id)}`
        );
    });
}

function exportMaintenancePdfFromPreviewWindow(html, filename, popup, title) {
    popup = popup || window.open('', '_blank');
    if (!popup) {
        alert('Unable to open PDF window. Please allow pop-ups for PDF export.');
        return;
    }

    popup.document.open();
    popup.document.write(`
        <html>
            <head>
                <title>${title || filename}</title>
                <meta charset="utf-8">
                <style>
                    html, body { margin: 0; padding: 0; background: #fff; color: #111; }
                    body { font-family: Arial, sans-serif; }
                    img { max-width: 100%; }
                    .pdf-status {
                        position: fixed;
                        right: 16px;
                        top: 16px;
                        z-index: 2147483647;
                        padding: 8px 12px;
                        border: 1px solid #ddd;
                        background: #fff;
                        color: #333;
                        font: 12px Arial, sans-serif;
                        box-shadow: 0 8px 20px rgba(0,0,0,.08);
                    }
                    @media print { .pdf-status { display: none !important; } }
                </style>
            </head>
            <body>
                <div class="pdf-status" id="pdfStatus">Preparing PDF...</div>
                <div id="pdfSource">${html}</div>
            </body>
        </html>
    `);
    popup.document.close();
    popup.focus();

    const finishWithPrint = function () {
        const status = popup.document.getElementById('pdfStatus');
        if (status) {
            status.textContent = 'Choose Save as PDF in the print dialog.';
        }
        popup.print();
    };

    const renderFromPopup = function () {
        const source = popup.document.getElementById('pdfSource');
        if (!source) {
            finishWithPrint();
            return;
        }

        finishWithPrint();
    };

    const waitForPopupImages = function () {
        const images = Array.from(popup.document.querySelectorAll('img'));
        const imagePromises = images.map(img => new Promise(resolve => {
            if (img.complete) return resolve();
            img.addEventListener('load', resolve);
            img.addEventListener('error', resolve);
        }));

        Promise.race([
            Promise.all(imagePromises),
            new Promise(resolve => setTimeout(resolve, 2000))
        ]).then(() => {
            popup.requestAnimationFrame(() => popup.requestAnimationFrame(renderFromPopup));
        });
    };

    if (popup.document.readyState === 'complete') {
        waitForPopupImages();
    } else {
        popup.addEventListener('load', waitForPopupImages, { once: true });
    }
}

function exportMaintenancePdf(html, filename, fallbackWindow = null) {
    if (typeof window.html2pdf === 'function') {
        // Ensure we pass a DOM element to html2pdf so styles and images render correctly.
        let container;
        if (typeof html === 'string') {
            container = document.createElement('div');
            container.style.position = 'absolute';
            container.style.left = '0';
            container.style.top = `${window.scrollY || document.documentElement.scrollTop || 0}px`;
            container.style.zIndex = '2147483647';
            container.style.width = '210mm';
            container.style.boxSizing = 'border-box';
            container.style.background = '#fff';
            container.style.color = '#111';
            container.style.pointerEvents = 'none';
            container.innerHTML = html;
            document.body.appendChild(container);
        } else if (html instanceof Element) {
            container = html;
        } else {
            // fallback: wrap whatever it is
            container = document.createElement('div');
            container.style.position = 'absolute';
            container.style.left = '0';
            container.style.top = `${window.scrollY || document.documentElement.scrollTop || 0}px`;
            container.style.zIndex = '2147483647';
            container.style.width = '210mm';
            container.style.background = '#fff';
            container.style.color = '#111';
            container.style.pointerEvents = 'none';
            container.appendChild(document.createTextNode(String(html)));
            document.body.appendChild(container);
        }

        // Wait for images to load (or timeout) before generating PDF
        const images = Array.from(container.querySelectorAll('img'));
        const imagePromises = images.map(img => new Promise(resolve => {
            if (img.complete) return resolve();
            img.addEventListener('load', resolve);
            img.addEventListener('error', resolve);
            // set crossOrigin to try to avoid tainting if possible
            try { img.crossOrigin = 'anonymous'; } catch (e) {}
            // also try to reload if src is data? leave as-is
        }));

        const waitForImages = Promise.race([
            Promise.all(imagePromises),
            new Promise(resolve => setTimeout(resolve, 2000))
        ]);

        waitForImages.then(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))).then(() => {
            try {
                // choose orientation based on content width
                const useLandscape = container.scrollWidth && container.scrollWidth > 1000;
                const orientation = useLandscape ? 'landscape' : 'portrait';
                window.html2pdf().set({
                    margin: 0.35,
                    filename: filename,
                    image: { type: 'jpeg', quality: 0.98 },
                    html2canvas: { scale: 3, useCORS: true, allowTaint: false, backgroundColor: '#ffffff' },
                    jsPDF: { unit: 'in', format: 'a4', orientation: orientation }
                }).from(container).save().then(() => {
                    if (container && container.parentNode) container.parentNode.removeChild(container);
                    if (fallbackWindow && !fallbackWindow.closed) {
                        fallbackWindow.close();
                    }
                }).catch(() => {
                    // ensure cleanup
                    if (container && container.parentNode) container.parentNode.removeChild(container);
                    openMaintenancePrintFallback(html, filename, fallbackWindow);
                });
            } catch (e) {
                if (container && container.parentNode) container.parentNode.removeChild(container);
                console.error('html2pdf error', e);
                openMaintenancePrintFallback(html, filename, fallbackWindow);
            }
        });
        return;
    }

    openMaintenancePrintFallback(html, filename, fallbackWindow);
}

function openMaintenancePrintFallback(html, filename, fallbackWindow = null) {
    const popup = fallbackWindow || window.open('', '_blank');
    if (!popup) {
        alert('Unable to open print window. Please allow pop-ups for PDF export.');
        return;
    }

    popup.document.write(`
        <html>
            <head>
                <title>${filename}</title>
                <style>body { font-family: Arial, sans-serif; margin: 24px; }</style>
            </head>
            <body>${html}</body>
        </html>
    `);
    popup.document.close();
    popup.focus();
    popup.print();
}

function previewWorkOrder(jobId) {
    $.get('api/maintenance.php', { action: 'job_details', job_id: jobId }, function (res) {
        if (res.status !== 'success') {
            alert('Unable to load job details');
            return;
        }
        const job = res.data;
            const html = createWorkOrderPreviewHTML(job);
        const popup = window.open('', '_blank');
        if (!popup) { alert('Please allow pop-ups to preview the work order.'); return; }
        popup.document.write(`
            <html>
            <head>
                <title>Work Order ${escapeHtml(job.work_order_number || job.id)}</title>
                <meta charset="utf-8">
                <style>body{font-family: Arial, sans-serif; margin:24px; color:#111;} img{max-width:100%;}</style>
            </head>
            <body>
                ${html}
            </body>
            </html>
        `);
        popup.document.close();
        popup.focus();
    }, 'json');
}

function previewJobOrder(jobId) {
    $.get('api/maintenance.php', { action: 'job_details', job_id: jobId }, function (res) {
        if (res.status !== 'success') {
            alert('Unable to load job details');
            return;
        }
        const job = res.data;
            const html = createJobOrderPreviewHTML(job);
        const popup = window.open('', '_blank');
        if (!popup) { alert('Please allow pop-ups to preview the job order.'); return; }
        popup.document.write(`
            <html>
            <head>
                <title>Job Order ${escapeHtml(job.work_order_number || job.id)}</title>
                <meta charset="utf-8">
                <style>body{font-family: Arial, sans-serif; margin:24px; color:#111;} img{max-width:100%;}</style>
            </head>
            <body>
                ${html}
            </body>
            </html>
        `);
        popup.document.close();
        popup.focus();
    }, 'json');
}

    function createWorkOrderPreviewHTML(job) {
        const compact = createWorkOrderHTML(job);

        return `
            <div>${compact}</div>
        `;
    }

    function createJobOrderPreviewHTML(job) {
        const compact = createJobOrderHTML(job);

        return `
            <div>${compact}</div>
        `;
    }

function createWorkOrderHTML(job) {
    const hideFields = shouldHideRaisedWorkOrderFields(job);
    const finalWorkshop = job.final_workshop || { name: (job.selected_final_workshop || job.workshop || '-') };
    const company = job.company || null;
    const workOrderHeading = hideFields ? '' : `<h2 style="margin: 5px 0; color: #666;">${job.work_order_number || 'WO-' + job.id}</h2>`;

    // header with company and workshop details
    const companyHtml = company ? `
        <div style="display:flex;align-items:center;gap:10px;">
            ${company.logo_path ? `<img src="${company.logo_path}" alt="Logo" style="height:60px;object-fit:contain;">` : ''}
            <div>
                <div style="font-size:18px;font-weight:700;">${escapeHtml(company.name || '')}</div>
                <div style="font-size:12px;color:#444;">${escapeHtml(company.email || '')} | ${escapeHtml(company.phone || '')}</div>
            </div>
        </div>
    ` : '';

    const workshopHtml = finalWorkshop ? `
        <div style="text-align:right;font-size:12px;color:#333;">
            <div style="font-weight:700;">${escapeHtml(finalWorkshop.name || finalWorkshop)}</div>
            ${finalWorkshop.contact_person ? `<div>Contact: ${escapeHtml(finalWorkshop.contact_person)}</div>` : ''}
            ${finalWorkshop.phone ? `<div>Phone: ${escapeHtml(finalWorkshop.phone)}</div>` : ''}
            ${finalWorkshop.email ? `<div>Email: ${escapeHtml(finalWorkshop.email)}</div>` : ''}
            ${finalWorkshop.address ? `<div style="max-width:300px;">${escapeHtml(finalWorkshop.address)}</div>` : ''}
        </div>
    ` : '';

    const style = `
        <style>
            .wo-wrapper { font-family: Arial, Helvetica, sans-serif; color: #111; box-sizing: border-box; width:100%; }
            .wo-container { max-width: 190mm; margin: 0 auto; padding: 18mm; background: #fff; }
            .wo-header { display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #e6e6e6; padding-bottom:8px; }
            .wo-company { display:flex; align-items:center; gap:12px; }
            .wo-company img { height:56px; object-fit:contain; }
            .wo-title { text-align:center; }
            .wo-title h1 { margin:0; font-size:20px; letter-spacing:1px; }
            .wo-meta { border:1px solid #e6e6e6; padding:8px; font-size:12px; width:220px; }
            .section { margin-top:12px; }
            .two-col { display:flex; gap:12px; }
            .col { flex:1; background:#fff; padding:8px; border:1px solid #eee; }
            table.line-items { width:100%; border-collapse:collapse; margin-top:8px; font-size:13px; }
            table.line-items th, table.line-items td { border:1px solid #ddd; padding:8px; }
            table.line-items th { background:#f6f6f6; font-weight:700; }
            .cost-cell { text-align:right; }
            .signature { margin-top:20px; display:flex; gap:20px; }
            .sig-block { flex:1; text-align:left; }
            .sig-line { border-top:1px solid #000; width:80%; margin-top:40px; }
            .page-break { page-break-before: always; }
            table.line-items tr { page-break-inside: avoid; }
            table.line-items td, table.line-items th { page-break-inside: avoid; }
            @media print {
                .wo-container { padding: 12mm; }
                .avoid-break { page-break-inside: avoid; }
            }
        </style>
    `;

    return `${style}<div class="wo-wrapper"><div class="wo-container">
            <div class="wo-header">
                <div class="wo-company">${companyHtml}</div>
                <div class="wo-title">
                    <h1>WORK ORDER</h1>
                    ${workOrderHeading}
                </div>
                <div class="wo-meta">
                    <div><strong>WO #:</strong> ${escapeHtml(job.work_order_number || 'WO-' + job.id)}</div>
                    <div><strong>Order Date:</strong> ${formatDate(job.complaint_log_date)}</div>
                    <div><strong>Expected:</strong> ${formatDate(job.expected_completion_date)}</div>
                    ${hideFields ? '' : `<div><strong>Status:</strong> ${escapeHtml(job.workflow_stage || '-')}</div>`}
                </div>
            </div>

            <div class="section two-col">
                <div class="col">
                    <div style="font-weight:700;margin-bottom:6px;color:#333;">Vehicle Information</div>
                    <div><strong>Plate:</strong> ${escapeHtml(job.plate_number || '-')}</div>
                    <div><strong>Vehicle:</strong> ${escapeHtml(job.vehicle_name || '-')}</div>
                    <div><strong>Driver:</strong> ${escapeHtml(job.driver_name || '-')}</div>
                    <div><strong>Mileage:</strong> ${escapeHtml(job.current_service_mileage_km || '-')}${job.current_service_mileage_km ? ' km' : ''}</div>
                </div>
                <div class="col">
                    <div style="font-weight:700;margin-bottom:6px;color:#333;">Workshop</div>
                    <div><strong>${escapeHtml(finalWorkshop.name || finalWorkshop)}</strong></div>
                    ${finalWorkshop.contact_person ? `<div>Contact: ${escapeHtml(finalWorkshop.contact_person)}</div>` : ''}
                    ${finalWorkshop.phone ? `<div>Phone: ${escapeHtml(finalWorkshop.phone)}</div>` : ''}
                    ${finalWorkshop.email ? `<div>Email: ${escapeHtml(finalWorkshop.email)}</div>` : ''}
                    ${finalWorkshop.address ? `<div style="max-width:100%">${escapeHtml(finalWorkshop.address)}</div>` : ''}
                </div>
            </div>

            <div class="section">
                <div style="font-weight:700;margin-bottom:6px;color:#333;">Job Description</div>
                <div><strong>Title:</strong> ${escapeHtml(job.complaint_title || '-')}</div>
                <div style="margin-top:6px;">${escapeHtml(job.complaint_description || 'No description provided')}</div>
            </div>

            <div class="section avoid-break">
                <div style="font-weight:700;margin-bottom:6px;color:#333;">Line Items</div>
                ${renderJobOrderLineItems(job)}
            </div>

            <div class="section">
                <div class="col">
                    <div style="font-weight:700;margin-bottom:6px;color:#333;">Maintenance Comments</div>
                    <div>${escapeHtml(job.maintenance_comment || 'No comments')}</div>
                </div>
            </div>

            <div class="signature">
                <div class="sig-block">
                    <div>Prepared by:</div>
                    <div class="sig-line"></div>
                </div>
                <div class="sig-block">
                    <div>Approved by:</div>
                    <div class="sig-line"></div>
                </div>
            </div>

            <div style="margin-top:24px;padding:10px;border-top:1px solid #ddd;font-size:10px;color:#666;text-align:justify;">
                <strong>Disclaimer:</strong> This work order is for internal use only. All costs are estimates and subject to final approval. The company reserves the right to amend, cancel, or suspend this work order at any time without prior notice. Any liability arising from the use of this document is expressly disclaimed.
            </div>

        </div></div>`;
}

function createJobOrderHTML(job) {
    const hideFields = shouldHideRaisedWorkOrderFields(job);
    const finalWorkshop = job.final_workshop || { name: (job.selected_final_workshop || job.workshop || '-') };
    const company = job.company || null;
    const jobOrderHeading = hideFields ? '' : `<h2 style="margin: 5px 0; color: #666;">${job.work_order_number || 'JO-' + job.id}</h2>`;
    const lineItemsHtml = renderJobOrderLineItems(job);

    const style = `
        <style>
            .jo-wrapper { font-family: Arial, Helvetica, sans-serif; color:#111; }
            .jo-container { max-width: 190mm; margin:0 auto; padding:18mm; box-sizing:border-box; }
            .jo-header { display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #e6e6e6; padding-bottom:8px; }
            .jo-title h1 { margin:0; font-size:20px; }
            .two-col { display:flex; gap:12px; }
            .col { flex:1; background:#fff; padding:8px; border:1px solid #eee; }
            table.line-items { width:100%; border-collapse:collapse; margin-top:8px; font-size:13px; }
            table.line-items th, table.line-items td { border:1px solid #ddd; padding:8px; }
            table.line-items th { background:#f6f6f6; font-weight:700; }
            .signature { margin-top:20px; display:flex; gap:20px; }
            .sig-line { border-top:1px solid #000; width:80%; margin-top:40px; }
            .page-break { page-break-before: always; }
            table.line-items tr { page-break-inside: avoid; }
            table.line-items td, table.line-items th { page-break-inside: avoid; }
            @media print { .jo-container { padding:12mm; } }
        </style>
    `;

    return `${style}<div class="jo-wrapper"><div class="jo-container">
        <div class="jo-header">
            <div>${company ? `<div style="display:flex;align-items:center;gap:10px">${company.logo_path ? `<img src="${company.logo_path}" alt="Logo" style="height:56px;object-fit:contain">` : ''}<div><div style="font-weight:700">${escapeHtml(company.name || '')}</div><div style="font-size:12px;color:#444">${escapeHtml(company.email || '')} | ${escapeHtml(company.phone || '')}</div></div></div>` : ''}</div>
            <div class="jo-title"><h1>JOB ORDER</h1>${jobOrderHeading}</div>
            <div style="text-align:right;">${finalWorkshop ? `<div style="font-weight:700">${escapeHtml(finalWorkshop.name || finalWorkshop)}</div>` : ''}</div>
        </div>

        <div class="section two-col" style="margin-top:12px;">
            <div class="col">
                <div style="font-weight:700;margin-bottom:6px;color:#333;">Workshop Information</div>
                <div><strong>Workshop:</strong> ${escapeHtml(finalWorkshop.name || finalWorkshop)}</div>
                ${!hideFields && job.work_order_number ? `<div><strong>Work Order #:</strong> ${escapeHtml(job.work_order_number)}</div>` : ''}
                <div><strong>Job Start Date:</strong> ${formatDate(job.workshop_received_date)}</div>
                <div><strong>Expected Completion:</strong> ${formatDate(job.expected_completion_date)}</div>
            </div>
            <div class="col">
                <div style="font-weight:700;margin-bottom:6px;color:#333;">Vehicle Details</div>
                <div><strong>Plate:</strong> ${escapeHtml(job.plate_number || '-')}</div>
                <div><strong>Vehicle:</strong> ${escapeHtml(job.vehicle_name || '-')}</div>
                <div><strong>Driver:</strong> ${escapeHtml(job.driver_name || '-')}</div>
                <div><strong>Mileage:</strong> ${escapeHtml(job.current_service_mileage_km || '-')}${job.current_service_mileage_km ? ' km' : ''}</div>
            </div>
        </div>

        <div class="section" style="margin-top:12px;">
            <div style="font-weight:700;margin-bottom:6px;color:#333;">Job Description</div>
            <div><strong>Complaint:</strong> ${escapeHtml(job.complaint_title || '-')}</div>
            <div style="margin-top:6px;">${escapeHtml(job.complaint_description || 'No description provided')}</div>
        </div>

        <div class="section" style="margin-top:12px;">
            <div style="font-weight:700;margin-bottom:6px;color:#333;">Cost Breakdown</div>
            ${lineItemsHtml}
        </div>

        <div class="signature">
            <div style="flex:1"><div>Prepared by:</div><div class="sig-line"></div></div>
            <div style="flex:1"><div>Approved by:</div><div class="sig-line"></div></div>
        </div>

        <div style="margin-top:24px;padding:10px;border-top:1px solid #ddd;font-size:10px;color:#666;text-align:justify;">
            <strong>Disclaimer:</strong> This job order is for internal use only. All costs are estimates and subject to final approval. The company reserves the right to amend, cancel, or suspend this job order at any time without prior notice. Any liability arising from the use of this document is expressly disclaimed.
        </div>

    </div></div>`;
}

function renderJobOrderLineItems(job) {
    const items = Array.isArray(job.line_items) ? job.line_items : [];
    if (items.length) {
        let total = 0;
        const rows = items.map((item, index) => {
            const cost = Number(item.cost || 0) || 0;
            total += cost;
            return `<tr><td style="padding:8px;border:1px solid #ddd;text-align:center">${index + 1}</td><td style="padding:8px;border:1px solid #ddd">${escapeHtml(item.description || '-')}</td><td style="padding:8px;border:1px solid #ddd;text-align:right">&#8358;${formatCurrency(cost)}</td></tr>`;
        }).join('');

        return `
            <table style="width:100%;border-collapse:collapse;font-size:13px;">
                <thead>
                    <tr>
                        <th style="padding:8px;border:1px solid #ddd;background:#f9f9f9;">#</th>
                        <th style="padding:8px;border:1px solid #ddd;background:#f9f9f9;">Description</th>
                        <th style="padding:8px;border:1px solid #ddd;background:#f9f9f9;text-align:right">Cost</th>
                    </tr>
                </thead>
                <tbody>
                    ${rows}
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="2" style="padding:8px;border:1px solid #ddd;text-align:right;font-weight:700;background:#f5f5f5">Total</td>
                        <td style="padding:8px;border:1px solid #ddd;text-align:right;font-weight:700;background:#f5f5f5">&#8358;${formatCurrency(total)}</td>
                    </tr>
                </tfoot>
            </table>
        `;
    }

    const amount = Number(job.approved_amount || job.quote_amount || job.cost_of_repair) || 0;
    return `
        <table style="width:100%;border-collapse:collapse;font-size:13px;">
            <thead>
                <tr>
                    <th style="padding:8px;border:1px solid #ddd;background:#f9f9f9;">Description</th>
                    <th style="padding:8px;border:1px solid #ddd;background:#f9f9f9;text-align:right">Amount</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td style="padding:8px;border:1px solid #ddd">${escapeHtml(job.nature_of_fault || 'General maintenance')}</td>
                    <td style="padding:8px;border:1px solid #ddd;text-align:right">&#8358;${formatCurrency(amount)}</td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td style="padding:8px;border:1px solid #ddd;text-align:right;font-weight:700;background:#f5f5f5">Total Approved Amount</td>
                    <td style="padding:8px;border:1px solid #ddd;text-align:right;font-weight:700;background:#f5f5f5">&#8358;${formatCurrency(amount)}</td>
                </tr>
            </tfoot>
        </table>
    `;
}

function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return Number.isNaN(date.getTime()) ? dateString : date.toLocaleDateString('en-GB');
}
