<%
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;
}

function getDP(config, key) {
    const dp = Number(config?.[`Friability_${key}_DP`]);
    return Number.isFinite(dp) && dp >= 0 ? dp : null;
}

function format(val, dp) {
    const v = forNullValue(val);
    if (v === "" || v == null) return "";

    const num = Number(v);
    if (!Number.isFinite(num)) return "";

    return dp !== null ? num.toFixed(dp) : num;
}
%>

<%
let dpSampleVal, dpResult;

if (config?.FromFriabilator === 1) {
    dpSampleVal = getDP(config, "SV_String");
    dpResult = getDP(config, "Result_String");

} else if (config?.FromBalance === 1){
    dpSampleVal = getDP(config, "SV_Bal");
    dpResult = getDP(config, "Result_Bal");
}
%>

<%
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%;">Std. Limit NMT <%= productData.Unit ? ` (${productData.Unit})` : '' %></th>
        <td style="width: 25%;"><%= nv(productData.Nom) || 'NA' %></td>
    </tr>
</table>

<table class="data-table">
    <tr>
        <th colspan="5">Batch Summary</th>
    </tr>

    <tr>
        <th>Minimum <%= reportOption %> <%= productData.Unit ? ` (${productData.Unit}w/w)` : '' %></th>
        <th>Maximum <%= reportOption %> <%= productData.Unit ? ` (${productData.Unit}w/w)` : '' %></th>
        <th>Average <%= reportOption %> <%= productData.Unit ? ` (${productData.Unit}w/w)` : '' %></th>
    </tr>

    <% if (productData && Object.keys(productData).length) { %>
    <tr>
        <td><%= nv(productData.MinValue) || 'NA' %></td>
        <td><%= nv(productData.MaxValue) || 'NA' %></td>
        <td><%= nv(productData.AvgValue) || 'NA' %></td>
    </tr>
    <% } else { %>
        <tr>
        <% for (let j=0; j < 5; j++) { %>
            <td>&nbsp;</td>
        <% } %>
        </tr>
    <% } %>
</table>

<canvas id="friabilityBatch" 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</th>
        <th style="width: 15%;">Friabilator Code No.</th>
        <th style="width: 15%;">Side</th>
        <th style="width: 15%;">Friability <%= productData.Unit ? ` (${productData.Unit})` : '' %></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.Friability) %></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',
            } = 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.textAlign = 'left';
                ctx.textBaseline = 'middle';
                ctx.fillText(value.toFixed(dpResult), x, y);
                ctx.restore();
            });
        }
    };

    const dpResult = Number("<%= dpResult %>");

    const batchesData = JSON.parse(`<%- JSON.stringify(batches) %>`);

    const Standard = Number("<%= productData.Nom %>");

    const rows = (batchesData[0]?.rows || []).filter(r => r.TestResult === 'Complies');
    const friability = rows.map(r => Number(r.Friability));
    const labels = rows.map((_, i) => i + 1);

    try {
        const ctx4 = document.getElementById('friabilityBatch').getContext('2d');

        new Chart(ctx4, {
            type: "line",
            data: {
                labels: labels,
                datasets: [
                    {
                        label: "Standard",
                        data: labels.map(() => Standard),
                        borderColor: "blue",
                        borderWidth: 2,
                        pointRadius: 2
                    },
                    {
                        label: "Friability",
                        data: friability,
                        borderColor: "green",
                        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: <%= reportOption %> <%= productData.Unit ? `(${productData.Unit})` : '' %>",
                            color: "black"
                        },
                        ticks: {
                            color: "black",
                            callback: function (value) {
                                return value.toFixed(dpResult);
                            }
                        },
                        grid: {
                            display: false,
                        },
                        border: {
                            display: true,
                            color: "black",
                            width: 1,
                        },
                        offset: true
                    }
                },
                plugins: {
                    legend: {
                        position: "bottom",
                        labels: {
                            color: 'black' 
                        }
                    },
                    limitValueLabels: {
                        xOffset: 500,
                        yOffset: 2,
                        font: 'bold 14px Arial',                        
                    }
                },
                layout: {
                    padding: {
                        right: 80
                    }
                },
            },
            plugins: [limitValueLabels]
        });
    } catch (error) {
        console.error("Chart error:", error);
    }
</script>