<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-polishing">
  <div class="container-fluid p-4">
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-3 gap-2">
      <h4 class="mb-0">Polishing Jobs</h4>
      <div class="d-flex align-items-center gap-2 flex-wrap">
        <button id="pj_export" class="btn btn-sm btn-outline-success"><i class="bi bi-file-earmark-excel"></i> Export XLSX</button>
        <div class="input-group input-group-sm" style="max-width: 320px;">
          <input id="pjSearch" type="text" class="form-control" placeholder="Search slab no, quality, worker">
          <button id="btnPjSearch" class="btn btn-outline-secondary" type="button"><i class="bi bi-search"></i></button>
        </div>
        <div class="input-group input-group-sm" style="max-width: 260px;">
          <span class="input-group-text">From</span>
          <input id="pjFrom" type="date" class="form-control">
          <span class="input-group-text">To</span>
          <input id="pjTo" type="date" class="form-control">
        </div>
        <select id="pjWorker" class="form-select form-select-sm" style="width: 220px; max-width: 220px;">
          <option value="">All Workers</option>
        </select>
        <select id="pjColor" class="form-select form-select-sm" style="width: 180px; max-width: 180px;">
          <option value="">All Colors</option>
        </select>
        <div class="btn-group btn-group-sm ms-auto">
          <button class="btn btn-outline-secondary pj-filter active" data-status="in_progress">In Progress</button>
          <button class="btn btn-outline-secondary pj-filter" data-status="completed">Completed</button>
          <button class="btn btn-outline-secondary pj-filter" data-status="">All</button>
        </div>
      </div>
    </div>

    <!-- Color-wise SQFT Dashboard -->
    <div class="card shadow-sm mb-3"><div class="card-body">
      <h6 class="mb-2">Top Colors by SQFT (Pre)</h6>
      <div class="table-responsive" style="max-height: 200px; overflow-y: auto;">
        <table id="pjColorSummary" class="table table-sm table-striped align-middle mb-0">
          <thead class="sticky-top">
            <tr>
              <th>Color</th>
              <th class="text-end">Jobs</th>
              <th class="text-end">Pre SQFT</th>
            </tr>
          </thead>
          <tbody></tbody>
          <tfoot class="table-light fw-bold">
            <tr>
              <td>Total</td>
              <td class="text-end" id="pjColorTotalJobs">0</td>
              <td class="text-end" id="pjColorTotalSqft">0.000</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div></div>

    <div class="card shadow-sm"><div class="card-body">
      <div class="table-responsive">
        <table id="pj-table" class="table table-hover align-middle">
          <thead>
            <tr>
              <th>ID</th>
              <th>SLAB NO</th>
              <th>PO Number</th>
              <th>Color</th>
              <th>Worker</th>
              <th>Pre Size</th>
              <th>Pre SQF</th>
              <th>Final Size</th>
              <th>Final SQF</th>
              <th>Diff(SQF)</th>
              <th>Status</th>
              <th>Started</th>
              <th>Ended</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div></div>
  </div>
</div>

<!-- Complete Modal (re-use fields) -->
<div class="modal fade" id="pjCompleteModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Complete Polishing</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="pjCompleteForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="id" id="pj_job_id">
          <div class="row g-2">
            <div class="col-md-6">
              <label class="form-label">Slab No</label>
              <input type="text" class="form-control" id="pj_slab_no" readonly>
            </div>
            <div class="col-md-6">
              <label class="form-label">PO Number</label>
              <input type="text" class="form-control" id="pj_po" readonly>
            </div>
            <div class="col-md-6">
              <label class="form-label">Complete Date</label>
              <input type="date" class="form-control" name="complete_date" id="pj_complete_date">
            </div>
            <div class="col-md-6">
              <label class="form-label">Pre Height (inches)</label>
              <input type="number" class="form-control" id="pj_pre_h_view" readonly>
            </div>
            <div class="col-md-6">
              <label class="form-label">Pre Length (inches)</label>
              <input type="number" class="form-control" id="pj_pre_l_view" readonly>
            </div>
            <div class="col-md-6">
              <label class="form-label">Final Height (inches)</label>
              <input type="number" step="0.001" class="form-control" name="final_height" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Final Length (inches)</label>
              <input type="number" step="0.001" class="form-control" name="final_length" required>
            </div>
            <div class="col-12">
              <label class="form-label">Finish</label>
              <select class="form-select" name="finish_id" id="pj_finish"></select>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Complete</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Start Job Modal -->
<div class="modal fade" id="pjStartModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Start Polishing Job</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="pjStartForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <div class="mb-2">
            <label class="form-label">Select Received Slab</label>
            <select class="form-select" name="rmp_id" id="pj_rmp" required></select>
          </div>
          <div class="row g-2">
            <div class="col-md-6">
              <label class="form-label">Start Date</label>
              <input type="date" class="form-control" name="start_date" id="pj_start_date">
            </div>
            <div class="col-md-6">
              <label class="form-label">Pre Height (inches)</label>
              <input type="number" step="0.001" class="form-control" name="pre_height" id="pj_pre_h">
            </div>
            <div class="col-md-6">
              <label class="form-label">Pre Length (inches)</label>
              <input type="number" step="0.001" class="form-control" name="pre_length" id="pj_pre_l">
            </div>
            <div class="col-md-6">
              <label class="form-label">Polisher</label>
              <select class="form-select" id="pj_emp"></select>
              <input type="hidden" name="worker_id" id="pj_emp_id">
              <input type="hidden" name="worker_name" id="pj_emp_name">
            </div>
            <div class="col-12">
              <label class="form-label">Notes</label>
              <input type="text" class="form-control" name="notes">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Start</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Job Modal -->
<div class="modal fade" id="pjEditModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Edit Polishing Job</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="pjEditForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="id" id="pje_id">
          <div class="row g-2">
            <div class="col-md-6"><label class="form-label">Slab No</label><input type="text" class="form-control" id="pje_slab_no" readonly></div>
            <div class="col-md-6"><label class="form-label">PO Number</label><input type="text" class="form-control" id="pje_po" readonly></div>
            <div class="col-md-6"><label class="form-label">Start Date</label><input type="date" class="form-control" id="pje_start_date"></div>
            <div class="col-md-6"><label class="form-label">Pre Height (inches)</label><input type="number" step="0.001" class="form-control" name="pre_height" id="pje_pre_h" readonly></div>
            <div class="col-md-6"><label class="form-label">Pre Length (inches)</label><input type="number" step="0.001" class="form-control" name="pre_length" id="pje_pre_l" readonly></div>
            <div class="col-md-6">
              <label class="form-label">Polisher</label>
              <select class="form-select" id="pje_emp"></select>
              <input type="hidden" name="worker_id" id="pje_emp_id">
              <input type="hidden" name="worker_name" id="pje_emp_name">
            </div>
            <div class="col-12"><label class="form-label">Notes</label><input type="text" class="form-control" name="notes" id="pje_notes"></div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
(function(){
  if (!$('.page-polishing').length) return;

  function loadFinishes(){
    $.get('api/materials.php', { action:'list_finishes' }, function(res){
      const opts = ['<option value="">Select</option>'];
      (res.data||[]).forEach(f=>opts.push(`<option value="${f.id}">${$('<div>').text(f.name).html()}</option>`));
      $('#pj_finish').html(opts.join(''));
    });
  }

  function loadColors(){
    $.get('api/materials.php', { action:'list_colors' }, function(res){
      const opts = ['<option value="">All Colors</option>'];
      (res.data||[]).forEach(c=>opts.push(`<option value="${c.id}">${$('<div>').text(c.name).html()}</option>`));
      $('#pjColor').html(opts.join(''));
    });
  }

  function fetchJobs(){
    const status = $('.pj-filter.active').data('status') || '';
    const q = ($('#pjSearch').val()||'').trim();
    const from = $('#pjFrom').val()||'';
    const to = $('#pjTo').val()||'';
    const worker_id = $('#pjWorker').val()||'';
    const color_id = $('#pjColor').val()||'';
    const params = { action:'list' };
    if (status) params.status = status; if (q) params.q = q;
    if (from) params.from = from; if (to) params.to = to; if (worker_id) params.worker_id = worker_id;
    if (color_id) params.color_id = color_id;
    $.get('api/polishing.php', params, function(res){
      const $tb=$('#pj-table tbody');
      // Destroy DT before rebuilding rows to avoid residual state
      if ($.fn.DataTable && $.fn.dataTable.isDataTable('#pj-table')) { $('#pj-table').DataTable().destroy(); }
      $tb.empty();
      const rows=res.data||[]; if(!rows.length){ $tb.append('<tr><td colspan="14" class="text-center text-muted">No jobs</td></tr>'); return; }
      rows.forEach(j=>{
        const tr=$('<tr>');
        tr.append(`<td>${j.id}</td>`);
        tr.append(`<td>${$('<div>').text(j.slab_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(j.order_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(j.material_color||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(j.worker_name||'').html()}</td>`);
        tr.append(`<td>${(j.pre_height||'') + ' x ' + (j.pre_length||'')}</td>`);
        tr.append(`<td class="text-end">${(j.pre_sq_ft!==null && j.pre_sq_ft!==undefined && j.pre_sq_ft!=='') ? Number(j.pre_sq_ft||0).toFixed(3) : ''}</td>`);
        // Final size (inches) visible when completed (joined from final_products)
        const fsize = (j.final_height && j.final_length) ? `${j.final_height} x ${j.final_length}` : '';
        tr.append(`<td>${fsize}</td>`);
        tr.append(`<td class="text-end">${(j.final_sq_ft!==null && j.final_sq_ft!==undefined && j.final_sq_ft!=='') ? Number(j.final_sq_ft||0).toFixed(3) : ''}</td>`);
        // Extra area: show signed difference vs raw (increase + / wastage -)
        let extraCol = '';
        if (j.diff_sq_ft !== null && j.diff_sq_ft !== undefined) {
          const d = Number(j.diff_sq_ft||0);
          const p = (j.diff_pct!==null && j.diff_pct!==undefined) ? Number(j.diff_pct||0) : null;
          const sign = d>0?'+':(d<0?'-':'');
          const abs = Math.abs(d).toFixed(2);
          const pctStr = (p===null)? '' : ` (${p>0?'+':''}${p.toFixed(2)}%)`;
          const cls = d>0? 'text-success' : (d<0? 'text-danger' : 'text-muted');
          extraCol = `<span class="${cls}" title="${d>=0?'Increase over raw':'Wastage vs raw'}">${sign}${abs} ${pctStr}</span>`;
        }
        tr.append(`<td>${extraCol}</td>`);
        tr.append(`<td><span class="badge bg-secondary text-capitalize">${j.status||''}</span></td>`);
        tr.append(`<td>${j.start_at||''}</td>`);
        tr.append(`<td>${j.end_at||''}</td>`);
        const act=[];
        if (j.status==='in_progress') act.push(`<button class=\"btn btn-sm btn-outline-secondary me-1 btn-pj-edit\" data-id=\"${j.id}\" title=\"Edit\" aria-label=\"Edit\"><i class=\"bi bi-pencil\"></i></button>`);
        if (j.status==='in_progress') act.push(`<button class=\"btn btn-sm btn-success me-1 btn-pj-complete\" data-id=\"${j.id}\" data-slab=\"${$('<div>').text(j.slab_no||'').html()}\" title=\"Complete\" aria-label=\"Complete\"><i class=\"bi bi-check2-circle\"></i></button>`);
        if (j.status!=='completed') act.push(`<button class=\"btn btn-sm btn-outline-danger btn-pj-delete\" data-id=\"${j.id}\" title=\"Delete\" aria-label=\"Delete\"><i class=\"bi bi-trash\"></i></button>`);
        tr.append(`<td>${act.join('')}</td>`);
        $tb.append(tr);
      });
      // Re-init DataTable after rows are rendered
      if ($.fn.DataTable) {
        const existing = $.fn.dataTable.isDataTable('#pj-table');
        if (existing) { $('#pj-table').DataTable().destroy(); }
        $('#pj-table').DataTable({
          dom: 'lfrtip',
          pageLength: 10,
          lengthMenu: [[10,25,50,100,-1],[10,25,50,100,'All']],
          order: [],
          autoWidth: false,
          responsive: true,
          language: { search: 'Filter:' },
          columnDefs: [ { orderable: false, targets: -1 } ]
        });
      }
    });
  }

  function safeFilePart(s){
    return String(s||'')
      .replace(/\s+/g,'_')
      .replace(/[^a-zA-Z0-9_\-\.]/g,'')
      .slice(0, 80);
  }
  function exportTable(tableSel, filenameBase, sheetName){
    if (typeof XLSX === 'undefined') { alert('XLSX library not loaded'); return; }
    const table = document.querySelector(tableSel);
    if (!table) { alert('No table to export'); return; }

    const headerCells = Array.from(table.querySelectorAll('thead th'));
    const headers = headerCells.map(th => (th.innerText || '').trim());
    if (!headers.length) { alert('No headers to export'); return; }

    let rows = [];
    if ($.fn.DataTable && $.fn.dataTable.isDataTable(tableSel)) {
      // Export ALL rows that match current filters/search (not just current page)
      const dt = $(tableSel).DataTable();
      rows = dt.rows({ search: 'applied' }).data().toArray().map(r => {
        // r can be an array of columns or an object depending on how DataTable is configured
        if (Array.isArray(r)) return r.map(x => String(x ?? '').replace(/<[^>]*>/g, '').trim());
        if (r && typeof r === 'object') return headers.map(h => String(r[h] ?? '').trim());
        return [];
      }).filter(r => r.length);
    } else {
      // Fallback: export whatever is currently in the DOM
      rows = Array.from(table.querySelectorAll('tbody tr'))
        .filter(tr => tr.querySelectorAll('td').length)
        .map(tr => Array.from(tr.querySelectorAll('td')).map(td => (td.innerText || '').trim()));
    }

    if (!rows.length) { alert('No data to export'); return; }

    const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, (sheetName || 'Polishing').slice(0,31));
    const fname = safeFilePart(filenameBase || 'polishing_inventory') + '.xlsx';
    XLSX.writeFile(wb, fname);
  }

  function loadReceivedSlabs(){
    const $sel = $('#pj_rmp');
    $sel.empty().append('<option value="">Loading...</option>');
    $.get('api/raw_material_products.php', { action:'list', status:'received' }, function(res){
      const opts = ['<option value="">Select slab</option>'];
      (res.data||[]).forEach(r=>{
        const label = `Slab ${r.slab_no||''} (${r.height||''}x${r.length||''}) - PO ${r.order_no||''}`;
        opts.push(`<option value="${r.id}">${$('<div>').text(label).html()}</option>`);
      });
      $sel.html(opts.join(''));
    });
  }

  function loadEmployees(){
    $.get('api/employees.php', { action:'list' }, function(res){
      const opts=['<option value="">Select employee</option>'];
      (res.data||[]).forEach(e=>opts.push(`<option value="${e.id}" data-name="${$('<div>').text(e.full_name).html()}">${$('<div>').text(e.full_name).html()}</option>`));
      $('#pj_emp').html(opts.join(''));
    });
  }
  $('#pj_emp').on('change', function(){ const id=this.value; const name=$(this).find('option:selected').data('name')||''; $('#pj_emp_id').val(id||''); $('#pj_emp_name').val(name); });
  $('#pj_rmp').on('change', function(){ const id=this.value; if(!id) return; $.get('api/raw_material_products.php', { action:'get', id }, function(res){ const d=res.data||{}; $('#pj_pre_h').val(d.height||''); $('#pj_pre_l').val(d.length||''); }); });

  $('.pj-filter').on('click', function(){ $('.pj-filter').removeClass('active'); $(this).addClass('active'); refreshAll(); });
  // Search handlers
  $('#btnPjSearch').on('click', refreshAll);
  $('#pjSearch').on('keypress', function(e){ if(e.which===13){ refreshAll(); } });
  // Debounce typing
  let pjTimer=null; $('#pjSearch').on('input', function(){ clearTimeout(pjTimer); pjTimer=setTimeout(refreshAll, 400); });
  $('#pjFrom, #pjTo, #pjWorker, #pjColor').on('change', refreshAll);

  // Load workers into filter (only Polisher/Cutter)
  function loadWorkerFilter(){
    $.get('api/employees.php', { action:'list' }, function(res){
      const $w=$('#pjWorker');
      $w.empty().append('<option value="">All Polishers/Cutters</option>');
      (res.data||[])
        .filter(e=>{
          if (!(e && (e.is_active==1 || String(e.is_active)==='1'))) return false;
          const dn = (e.designation_name || e.designation || '').toString().toLowerCase();
          return dn==='polisher' || dn==='cutter';
        })
        .forEach(e=>{
          $w.append(`<option value="${e.id}">${$('<div>').text(e.full_name).html()}</option>`);
        });
    });
  }
  $(document).on('click', '.btn-pj-complete', function(){
    const id=$(this).data('id'); $('#pj_job_id').val(id); loadFinishes(); $('#pjCompleteForm')[0].reset();
    const slab = $(this).data('slab') || '';
    $('#pj_slab_no').val(slab);
    const today = new Date().toISOString().slice(0,10); $('#pj_complete_date').val(today);
    // Load pre-size from job (fallback to raw material size)
    $.get('api/polishing.php', { action:'get', id }, function(res){
      const d=res.data||{};
      const preH = (d.pre_height!=null && d.pre_height!=='') ? d.pre_height : d.height;
      const preL = (d.pre_length!=null && d.pre_length!=='') ? d.pre_length : d.length;
      $('#pj_pre_h_view').val(preH||'');
      $('#pj_pre_l_view').val(preL||'');
      $('#pj_po').val(d.order_no||'');
    });
    $('#pjCompleteModal').modal('show');
  });
  $('#pjCompleteForm').on('submit', function(e){
    e.preventDefault();
    const $form = $(this);
    if ($form.data('submitting')) { return; }
    $form.data('submitting', true);
    const $btn = $('#pjCompleteForm button[type="submit"]');
    $btn.prop('disabled', true).text('Completing...');
    const fd=new FormData(this); fd.append('action','complete');
    $.ajax({ url:'api/polishing.php', method:'POST', data: fd, contentType:false, processData:false })
      .done(function(res){
        $('#pjCompleteModal').modal('hide');
        if (typeof window.showToast === 'function') { window.showToast('Polishing job completed successfully.', 'success'); }
        fetchJobs();
      })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); })
      .always(function(){ $form.data('submitting', false); $btn.prop('disabled', false).text('Complete'); });
  });

  // Start job open + submit
  $('#btnStartJobOpen').on('click', function(){ loadReceivedSlabs(); loadEmployees(); $('#pjStartForm')[0].reset(); const today=new Date().toISOString().slice(0,10); $('#pj_start_date').val(today); $('#pjStartModal').modal('show'); });
  $('#pjStartForm').on('submit', function(e){
    e.preventDefault();
    const fd=new FormData(this); fd.append('action','start');
    $.ajax({ url:'api/polishing.php', method:'POST', data: fd, contentType:false, processData:false })
      .done(function(){ $('#pjStartModal').modal('hide'); fetchJobs(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); });
  });

  // Edit polishing job
  function loadEmployeesEdit(){
    $.get('api/employees.php', { action:'list' }, function(res){
      const opts=['<option value="">Select employee</option>'];
      (res.data||[]).forEach(e=>opts.push(`<option value="${e.id}" data-name="${$('<div>').text(e.full_name).html()}">${$('<div>').text(e.full_name).html()}</option>`));
      $('#pje_emp').html(opts.join(''));
    });
  }
  $('#pje_emp').on('change', function(){ const id=this.value; const name=$(this).find('option:selected').data('name')||''; $('#pje_emp_id').val(id||''); $('#pje_emp_name').val(name); });
  $(document).on('click', '.btn-pj-edit', function(){
    const id=$(this).data('id'); loadEmployeesEdit();
    $.get('api/polishing.php', { action:'get', id }, function(res){
      const d=res.data||{}; $('#pje_id').val(d.id);
      $('#pje_slab_no').val(d.slab_no||'');
      $('#pje_po').val(d.order_no||'');
      $('#pje_pre_h').val(d.pre_height||d.height||''); $('#pje_pre_l').val(d.pre_length||d.length||'');
      $('#pje_notes').val(d.notes||'');
      if (d.start_at) { $('#pje_start_date').val(String(d.start_at).slice(0,10)); }
      setTimeout(()=>{ if (d.worker_id){ $('#pje_emp').val(d.worker_id).trigger('change'); } else if (d.worker_name){ const $opt=$('#pje_emp option').filter(function(){ return $(this).text()===d.worker_name; }); if($opt.length){ $('#pje_emp').val($opt.val()).trigger('change'); } } }, 200);
      $('#pjEditModal').modal('show');
    });
  });
  $('#pjEditForm').on('submit', function(e){
    e.preventDefault(); const fd=new FormData(this); fd.append('action','update');
    // manually add start_date to update
    const s=$('#pje_start_date').val(); if (s) fd.append('start_date', s);
    $.ajax({ url:'api/polishing.php', method:'POST', data: fd, contentType:false, processData:false })
      .done(function(){ $('#pjEditModal').modal('hide'); fetchJobs(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); });
  });

  // Delete job
  $(document).on('click', '.btn-pj-delete', function(){
    if (!confirm('Delete this polishing job?')) return; const id=$(this).data('id');
    const fd=new FormData(); fd.append('csrf','<?php echo htmlspecialchars(csrf_token()); ?>'); fd.append('id', id); fd.append('action','delete');
    $.ajax({ url:'api/polishing.php', method:'POST', data: fd, contentType:false, processData:false })
      .done(function(){ fetchJobs(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); });
  });

  // init: default to In Progress and no date filter
  (function initDefaultInProgressAllDates(){
    // Clear date filters so API lists all dates
    $('#pjFrom').val('');
    $('#pjTo').val('');
    // Ensure In Progress is active
    $('.pj-filter').removeClass('active');
    $('.pj-filter[data-status="in_progress"]').addClass('active');
  })();
  function fetchColorSummary(){
    const status = $('.pj-filter.active').data('status') || '';
    const from = $('#pjFrom').val()||'';
    const to = $('#pjTo').val()||'';
    const params = { action:'by_color' };
    if (status) params.status = status;
    if (from) params.from = from;
    if (to) params.to = to;
    $.get('api/polishing.php', params, function(res){
      const $tb=$('#pjColorSummary tbody');
      $tb.empty();
      let rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="3" class="text-center text-muted">No data</td></tr>'); $('#pjColorTotalJobs').text('0'); $('#pjColorTotalSqft').text('0.000'); return; }
      // Limit to top 8 colors
      rows = rows.slice(0, 8);
      let totalJobs = 0;
      let totalSqft = 0;
      rows.forEach(r=>{
        const tr=$('<tr>');
        tr.append(`<td>${$('<div>').text(r.color_name||'').html()}</td>`);
        tr.append(`<td class="text-end">${r.job_count||0}</td>`);
        tr.append(`<td class="text-end">${Number(r.total_pre_sq_ft||0).toFixed(3)}</td>`);
        $tb.append(tr);
        totalJobs += (r.job_count||0);
        totalSqft += Number(r.total_pre_sq_ft||0);
      });
      $('#pjColorTotalJobs').text(totalJobs);
      $('#pjColorTotalSqft').text(totalSqft.toFixed(3));
    });
  }

  function refreshAll(){ fetchJobs(); fetchColorSummary(); }

  fetchJobs();
  loadWorkerFilter();
  loadColors();
  fetchColorSummary();

  $('#pj_export').on('click', function(){
    const today = new Date().toISOString().slice(0,10);
    exportTable('#pj-table', 'Polishing_Inventory_' + today, 'Polishing');
  });
})();
</script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
