<%
function nv(val) { 
    if (val == null || val === "" || val === undefined) return "";
    if (typeof val === "string" && val.trim().toUpperCase() === "NULL") return "";
    if (val === "") return "NA";
    return val;
}

const productData = product || [];
const batches = summary || [];
%>

<table class="header-table">
    <tr>
        <th style="width: 25%;">Product Name</th>
        <td colspan="3"><%= nv(productData.ProductName) %></td>
    </tr>

    <tr>
        <th style="width: 25%;">Batch No.</th>
        <td style="width: 25%;"><%= nv(productData.BatchNo) %></td>
        <th style="width: 25%;">Department</th>
        <td style="width: 25%;"><%= nv(productData.Department) %></td>
    </tr>

    <tr>
        <th style="width: 25%;">BFG Code No.</th>
        <td style="width: 25%;"><%= nv(productData.BFGCode) %></td>
        <th style="width: 25%;">Stage</th>
        <td style="width: 25%;"><%= nv(productData.Stage) %></td>
    </tr>

    <tr>
        <th style="width: 25%;">Std. Disintegration Time (NMT) (<%= timeFormat %>)</th>
        <td style="width: 25%;"><%= nv(productData.StdTime) || 'NA' %></td>
        <th style="width: 25%;">Temperature Range( °C)</th>
        <td style="width: 25%;"><%= nv(productData.TempRange) || 'NA' %></td>
    </tr>
</table>

<table class="data-table">
    <tr>
        <th colspan="5">Batch Summary</th>
    </tr>

    <tr>
        <th>Minimum Disintegration Time (<%= timeFormat %>)</th>
        <th>Maximum Disintegration Time (<%= timeFormat %>)</th>
        <th>Average Disintegration Time (<%= timeFormat %>)</th>
    </tr>

    <% if (productData && Object.keys(productData).length) { %>
    <tr>
        <td><%= nv(productData.FinalMinDT) || 'NA' %></td>
        <td><%= nv(productData.FinalMaxDT) || 'NA' %></td>
        <td><%= nv(productData.FinalAvgDT) || 'NA' %></td>
    </tr>
    <% } else { %>
        <tr>
        <% for (let j=0; j < 5; j++) { %>
            <td>&nbsp;</td>
        <% } %>
        </tr>
    <% } %>
</table>

<canvas id="disintegrationBatch" width="700" height="300"></canvas>

<table class="data-table">
    <tr><th colspan="12">Detailed Report</th></tr>
    <tr>
        <th style="width: 18%;">Test No.</th>
        <th style="width: 18%;">Date</th>
        <th style="width: 18%;">Time (<%= timeFormat %>)</th>
        <th style="width: 15%;">Disintegration Tester Code No.</th>
        <th style="width: 15%;">Side</th>
        <th style="width: 15%;">Disintegration Time (<%= timeFormat %>)</th>
        <th style="width: 15%;">Test Result</th>
        <th style="width: 15%;">Performed By</th>
    </tr>

    <% if (batches.length) { %>
        <% batches.forEach(test => { %>
            <% test.rows.forEach(row => { %>
            <% if (row.TestResult === 'Complies') { %>
            <tr>
                <td><%= nv(row.RecSeqNo) %></td>
                <td><%= nv(row.Date) ? moment(nv(row.Date)).format(dateFormat) : "" %></td>
                <td><%= nv(row.Time) ? moment.utc(nv(row.Time)).format(timeFormat) : "" %></td>
                <td><%= nv(row.InstrumentID) %></td>
                <td><%= nv(row.Side) || 'NA' %></td>
                <td><%= nv(row.DT_Time) %></td>

                <% let result = (config.lbl_Remark || '').split('/'); %>
                
                <td style="color: green;"><%= result[0] %></td>
                
                <td><%= nv(row.UserID) %></td>
            </tr>
            <% } %>
            <% }) %>
        <% }) %>
    <% } else { %>
        <tr>
        <% for (let j=0; j < 12; j++) { %>
            <td>&nbsp;</td>
        <% } %>
        </tr>
    <% } %>
</table>

<script>
    const dashedGridPlugin = {
        id: 'dashedGrid',
        beforeDraw(chart) {
            const { ctx, chartArea, scales } = chart;

            ctx.save();
            ctx.setLineDash([4, 4]);       // Dashed pattern
            ctx.strokeStyle = '#cfcfcf';
            ctx.lineWidth = 1;

            // Horizontal grid lines
            scales.y.ticks.forEach((tick, i) => {
                const y = scales.y.getPixelForTick(i);
                ctx.beginPath();
                ctx.moveTo(chartArea.left, y);
                ctx.lineTo(chartArea.right, y);
                ctx.stroke();
            });

            // Vertical grid lines
            scales.x.ticks.forEach((tick, i) => {
                const x = scales.x.getPixelForTick(i);
                ctx.beginPath();
                ctx.moveTo(x, chartArea.top);
                ctx.lineTo(x, chartArea.bottom);
                ctx.stroke();
            });

            ctx.restore();
        }
    };
    Chart.register(dashedGridPlugin);

    const limitValueLabels = {
        id: 'limitValueLabels',
        afterDatasetsDraw(chart, args, pluginOptions) {
            const { ctx, chartArea, scales } = chart;
            const yScale = scales.y;

            const {
                labels = ['Standard'],
                xPadding = 10,
                font = 'bold 14px Arial',
                formatValue = (value) => formatMinutesToTime(value)
            } = pluginOptions;

            chart.data.datasets.forEach((dataset, index) => {
                if (!labels.includes(dataset.label)) return;

                const value = dataset.data[0];
                if (value == null) return;

                const y = yScale.getPixelForValue(value);
                const x = chartArea.right + xPadding;          

                ctx.save();
                ctx.fillStyle = 'black';
                ctx.font = font;
                ctx.fillText(formatValue(value),x,y);
                ctx.restore();
            });
        }
    };

    function timeToMinutes(timeStr) {
        if (!timeStr) return null;
        const [h, m, s] = timeStr.split(':').map(Number);
        return h * 60 + m + (s / 60);
    }
    
    const batchesData = JSON.parse(`<%- JSON.stringify(batches) %>`);
    const Standard = timeToMinutes("<%= productData.StdTime %>");
    const rows = (batchesData[0]?.rows || []).filter(r => r.TestResult === 'Complies');
    const DT_Time = rows.map(r => timeToMinutes(r.DT_Time));
    const labels = rows.map((_, i) => i + 1);

    function formatMinutesToTime(mins) {
      const totalSeconds = Math.floor(mins * 60);
      const h = Math.floor(totalSeconds / 3600);
      const m = Math.floor((totalSeconds % 3600) / 60);
      const s = totalSeconds % 60;
      return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
    }

    try {
        const ctx4 = document.getElementById('disintegrationBatch').getContext('2d');

        new Chart(ctx4, {
            type: "line",
            data: {
                labels: labels,
                datasets: [
                    {
                        label: "Max",
                        data: DT_Time,
                        borderColor: "green",
                        borderWidth: 2,
                        pointRadius: 2,
                    },
                    {
                        label: "Standard",
                        data: labels.map(() => Standard),
                        borderColor: "blue",
                        borderWidth: 2,
                        pointRadius: 2
                    },
                ]
            },
            options: {
                responsive: true,
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: 'X-Axis : Test No.',
                            color: 'black'
                        },
                        ticks: { color: 'black'},
                        grid: {
                            display: false,
                        },
                        border: {
                            display: true,
                            color: "black",
                            width: 1,
                        },
                        offset: true
                    },
                    y: {
                        title: {
                            display: true,
                            text: "Y-Axis: Disintegration Time",
                            color: "black"
                        },
                        ticks: {
                            color: "black",
                            callback: value => formatMinutesToTime(value),
                        },
                        grid: {
                            display: false,
                        },
                        border: {
                            display: true,
                            color: "black",
                            width: 1,
                        },
                        offset: true
                    }
                },
                plugins: {
                    legend: {
                        position: "bottom",
                        labels: {
                            color: 'black' 
                        }
                    },
                    limitValueLabels: {
                        xOffset: 450,
                        yOffset: 2,
                        font: 'bold 14px Arial',                        
                    }
                },
                layout: {
                    padding: {
                        right: 80,
                    }
                },
            },
            plugins: [limitValueLabels]
        });
    } catch (error) {
        console.error("Chart error:", error);
    }
</script>