<%- include('../RepoAuditHeader') %>

<style>
  body {
    font-family: "Times New Roman", serif;
    font-size: 11px;
  }

  .title {
    text-align: center;
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 10px;
  }

  .table,
  .report-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
  }

  .table th,
  .table td {
    border: 1px solid #000;
    padding: 5px;
    word-break: break-word;
  }

  .table th {
    text-align: center;
  }

  .table td.label {
    font-weight: bold;
    width: 18%;
  }

  .section {
    margin-top: 10px;
  }

  .report-table {
    font-size: 10.5px;
  }

  .report-table th,
  .report-table td {
    border: 1px solid #666;
    padding: 3px 4px;
    text-align: center;
    vertical-align: middle;
    line-height: 1.2;
  }

  .report-table tr {
    page-break-inside: avoid;
  }
</style>

<%
/* -------------------------------------------------------
   INITIAL DATA SETUP
--------------------------------------------------------*/
const data = balCalData[0];
const baseDate = new Date(data.Daily_CalbDate);

const startDate = new Date(
  baseDate.getFullYear(),
  baseDate.getMonth(),
  1
);
// Last day of that month
const monthEndDate = new Date(
  baseDate.getFullYear(),
  baseDate.getMonth() + 1,
  0
);

const today = new Date();
today.setHours(0, 0, 0, 0);

// 👉 If selected month = current month → show till today
let endDate = monthEndDate;

if (
  baseDate.getFullYear() === today.getFullYear() &&
  baseDate.getMonth() === today.getMonth()
) {
  endDate = today;
}

const weights = masterWeights
  .filter(w => w.Bal_Daily == 1)
  .sort((a, b) => Number(a.Bal_StdWt) - Number(b.Bal_StdWt));

const toleranceArray = data.Tolerance.split(',');

/* -------------------------------------------------------
   DATE FORMAT FUNCTION
--------------------------------------------------------*/
const formatDate = (date) => {
  return date.getFullYear() + '-' +
    String(date.getMonth() + 1).padStart(2, '0') + '-' +
    String(date.getDate()).padStart(2, '0');
};

/* -------------------------------------------------------
   GROUP DATA BY DATE
--------------------------------------------------------*/
const dataByDate = {};

balCalData.forEach((row, index) => {
  const key = moment(row.Daily_CalbDate).format(date_Format);

  if (!dataByDate[key]) {
    dataByDate[key] = [];
  }
  
  dataByDate[key].push({
    cal: row,
    weight: balWeight[index]
  });
});
let validUpto = data.Daily_AllWeightboxValidUpto;
let formattedDate = '';

if (validUpto) {
    if (validUpto.includes(',')) {
        formattedDate = validUpto
            .split(',')
            .map(d => moment(d.trim()).format(date_Format))
            .join(', ');
    } else {
        formattedDate = moment(validUpto).format(date_Format);
    }
}
%>

<div style="padding: 0 30px;">

  <!-- ================= HEADER TABLE ================= -->
  <table class="table section">
    <tr>
      <td class="label">Unit</td>
      <td><%= data.Daily_Unit %></td>
    </tr>

    <tr>
      <td class="label">Balance Code No.</td>
      <td><%= data.Daily_BalID %></td>
      <td class="label">Department</td>
      <td><%= data.Daily_Dept %></td>
    </tr>

    <tr>
      <td class="label">Month / Year</td>
      <td>
        <%= new Date(data.Daily_CalbDate)
            .toLocaleString('en-IN', { month: 'short', year: 'numeric' })
            .replace(' ', ' / ') %>
      </td>
      <td class="label">Capacity (<%= data.Daily_Unit %>)</td>
      <td><%= data.Daily_MaxCap %></td>
    </tr>
    <tr>
      <% if (confi_tbl.CalibrationReport == 1) { %>
          <td class="label">Make</td>
          <td><%= data.Daly_Make %></td>
      <% } else { %>
          <td class="label">Operating Range (<%= data.Daily_Unit %>)</td>
          <td><%= data.Daily_Bal_MinoptRange %> - <%= data.Daily_Bal_MaxoptRange %></td>
      <% } %>      
      <td class="label">Least Count (<%= data.Daily_Unit %>)</td>
      <td><%= data.Daily_LeastCnt %></td>
    </tr>
    <% if(confi_tbl.CalibrationReport == 1) { %>
    <tr>
      <td class="label">Model</td>
      <td><%= data.Daily_Model %></td>
    </tr>
    <% } %>
    <tr>
      <td class="label">Std. Weight Box ID</td>
      <td colspan="3"><%= data.Daily_AllWeightboxID %></td>
    </tr>
    <% if(confi_tbl.CalibrationReport == 2) { %>
     <tr>
      <td class="label">Certificate Number / Validity</td>
      <td colspan="3"><%= data.Daily_AllWeightboxCert %> / <%- formattedDate %></td>
    </tr>
    <% } %>
  </table>

  <!-- ================= STANDARD WEIGHTS TABLE ================= -->
  <table class="table section">
    <tr>
      <th colspan="2">
        Standard Weights for Verification (<%= data.Daily_Unit %>)
      </th>
      <th>Tolerance (<%= data.Daily_Unit %>)</th>
      <th>Accuracy Limits (<%= data.Daily_Unit %>)</th>
    </tr>

    <% weights.forEach((w, i) => { %>
      <tr>
        <td style="text-align:left;">
          <b>
            <%= i === 0
                ? 'Lower Weight'
                : i === weights.length - 1
                ? 'Upper Weight'
                : `Middle ${i} Weight` %>
          </b>
        </td>
        <td><%= w.Bal_StdWt %></td>
        <td><%= toleranceArray[i] || '-' %></td>
        <td><%= w.Bal_NegTol %> - <%= w.Bal_PosTol %></td>
      </tr>
    <% }) %>
  </table>
  <br>
  <!-- ================= DAILY REPORT TABLE ================= -->
  <table class="report-table">

    <thead>
      <tr>
        <th rowspan="2">Date</th>
        <th rowspan="2">Time</th>
        <th rowspan="2">Cleanliness (Clean / Unclean)</th>
        <th rowspan="2">Spirit Level (Ok/Not OK)</th>
        <th rowspan="2">Zero Error</th>
        <th colspan="<%= weights.length %>">
          Standard Weights for Verification (<%= data.Daily_Unit %>)
        </th>
        <th rowspan="2">Calibration Status</th>
        <th rowspan="2"><%- confi_tbl.lbl_DoneBy %></th>
        <th rowspan="2">Checked By</th>
        <th rowspan="2">Remark</th>
      </tr>
      <% if(weights.length != 2) { %>
      <tr>
        <% weights.forEach(w => { %>
          <th><%= w.Bal_StdWt %></th>
        <% }) %>
      </tr>
      <% } else {%>
      <tr>
          <th>Lower Weight (<%= data.Daily_Unit %>)</th>
          <th>Upper Weight (<%= data.Daily_Unit %>)</th>
      </tr>
      <%} %>
    </thead>

    <tbody>
      <% 
      let current = new Date(startDate);
      current.setHours(0, 0, 0, 0);
      endDate.setHours(0, 0, 0, 0);
      while (current <= endDate) {
      const date = moment(current).format(date_Format);
      const records = dataByDate[date] || [];
      if (ReportType != "Failure") {
            let remarksForDate = Remark.filter(r => r.NDCR_DT === current.toLocaleDateString('en-CA')).map(r => r.NDCR_Reason);
            var remarkText = remarksForDate.length ? remarksForDate.join(', '): 'No Activity';
          }
          let configRemark = confi_tbl.lbl_Remark.split('/');   
      %>

        <% if (records.length) { %>
          <% records.forEach(record => { %>
            <tr>
              <td><%= moment(record.cal.Daily_CalbDate).format(date_Format) %></td>
              <td>
                <%= confi_tbl.TimeFormat === 'HH:mm'? record.cal.Daily_CalbTime.slice(0, 5) : confi_tbl.TimeFormat === 'HH:mm:ss'? record.cal.Daily_CalbTime.slice(0, 8) : record.cal.Daily_CalbTime %>
              </td>
              <td><%= record.cal.Daily_GeneralCare ? (confi_tbl.CalibrationReport == 2 ? 'Clean' : 'OK')  : 'NA' %></td>
              <td><%= record.cal.Daily_SpiritLevel ? 'OK' : 'NA' %></td>
              <td><%= record.cal.Daily_ZeroError ? (confi_tbl.CalibrationReport == 2 ? 'No Zero Error' : 'Nil') : 'NA' %></td>

              <% weights.forEach((_, index) => { %>
                <td>
                  <%= record.weight?.[`Daily_ActualWt${index + 1}`] || '-' %>
                </td>
              <% }) %>
              <td><%= record.cal.Daily_Remark == "Ok" ? configRemark[0] : configRemark[1]  %></td>
              <td><%= record.cal.Daily_UserID %></td>
              <td><%= record.cal.Daily_VerifyID %></td>
              <td>                
                <%= ReportType !== "Failure" &&
                    record.cal.Daily_Remark === "Ok"
                    ? 'Ok'
                    : record.cal.CalibrationStatus || 'No Activiy' %>
              </td>
            </tr>
          <% }) %>
        <% } else { %>
          <tr>
            <td><%= date %></td>
            <td>NA</td>
            <td>NA</td>
            <td>NA</td>
            <td>NA</td>
            <% weights.forEach((_, index) => { %>
            <td>NA</td>
            <% }) %>
            <td>NA</td>
            <td>NA</td>
            <td>NA</td>
            <td ><%= ReportType != "Failure"  ? remarkText : 'NA' %></td>
          </tr>
        <% } %>

      <% current.setDate(current.getDate() + 1);
      } %>
    </tbody>

  </table>

</div>