<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-slab_cutting" data-slab-v2="1">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Slab Cutting</h4>
    </div>

    <div class="row g-3">
      <div class="col-lg-5">
        <div class="card shadow-sm mb-3">
          <div class="card-header">Create Cutting Job</div>
          <div class="card-body">
            <form id="cutJobForm">
              <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
              <div class="mb-2">
                <label class="form-label">Source Type</label>
                <select class="form-select" id="source_type" name="source_type">
                  <option value="raw">Raw Material (RMP)</option>
                  <option value="finished">Finished Product (FP)</option>
                  <option value="cut_piece">Cut Piece (Re-cut)</option>
                </select>
              </div>
              <div class="mb-2">
                <label class="form-label">Source</label>
                <div class="input-group mb-1">
                  <input type="text" class="form-control" id="source_search" placeholder="Search by slab no / code">
                  <button class="btn btn-outline-secondary" type="button" id="btnRefreshSources"><i class="bi bi-arrow-clockwise"></i></button>
                </div>
                <select class="form-select" id="source_id" name="source_id"></select>
                <div class="form-text">Pick slab to cut (from RM or Finished)</div>
              </div>
              <div class="mb-2 d-flex justify-content-between align-items-center">
                <label class="form-label mb-0">Pieces</label>
                <div class="d-flex gap-2">
                  <button type="button" id="btnAddPiece" class="btn btn-sm btn-outline-primary"><i class="bi bi-plus-circle"></i> Add Piece</button>
                  <button type="button" id="btnClearPieces" class="btn btn-sm btn-outline-secondary">Clear</button>
                </div>
              </div>
              <div class="table-responsive border rounded">
                <table class="table table-sm align-middle mb-0" id="piecesTable">
                  <thead><tr><th style="width:70px">#</th><th>Length (in)</th><th>Height (in)</th><th style="width:140px" class="text-end">Area (sqft)</th><th style="width:60px"></th></tr></thead>
                  <tbody></tbody>
                </table>
              </div>
              <div class="text-end small text-muted mt-1">Total Area: <span id="piecesTotal">0.000</span> sqft</div>
              <div class="mt-3">
                <label class="form-label">Operator</label>
                <select class="form-select" id="operator_id" name="operator_id">
                  <option value="">Loading operators...</option>
                </select>
                <div class="form-text">Sourced from Employees (designation = Operator)</div>
              </div>
              <div class="mt-2">
                <label class="form-label">Notes</label>
                <input type="text" class="form-control" id="notes" name="notes">
              </div>
              <div class="mt-3 d-flex gap-2">
                <button type="submit" class="btn btn-primary">Create Job</button>
                <button type="button" class="btn btn-outline-secondary" id="btnClearCutForm">Clear</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <div class="col-lg-7">
        <div class="card shadow-sm mb-3">
          <div class="card-header d-flex justify-content-between align-items-center">
            <span>Cut Pieces Inventory</span>
            <div class="d-flex gap-2 align-items-center flex-nowrap">
              <input type="text" class="form-control form-control-sm" id="cutPiecesSearch" placeholder="Search (slab/PO/job/piece)" style="max-width:220px;">
              <select class="form-select form-select-sm" id="cutPiecesLimit" style="max-width:120px;">
                <option value="10" selected>Last 10</option>
                <option value="20">Last 20</option>
                <option value="50">Last 50</option>
                <option value="100">Last 100</option>
                <option value="200">Last 200</option>
                <option value="500">Last 500</option>
              </select>
              <button class="btn btn-sm btn-outline-secondary" id="btnRefreshPieces"><i class="bi bi-arrow-clockwise"></i></button>
            </div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table id="cut-pieces-table" class="table table-hover align-middle">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>Job</th>
                    <th>PO No</th>
                    <th>Slab No</th>
                    <th>Cut Piece No</th>
                    <th>Re-cut Piece No</th>
                    <th>Size (in)</th>
                    <th>Area (sqft)</th>
                    <th>Available</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="card shadow-sm">
          <div class="card-header d-flex justify-content-between align-items-center">
            <span>Recent Cutting Jobs</span>
            <div class="d-flex gap-2 align-items-center flex-nowrap">
              <input type="text" class="form-control form-control-sm" id="cutJobsSearch" placeholder="Search (slab/PO/operator/id)" style="max-width:220px;">
              <select class="form-select form-select-sm" id="cutJobsLimit" style="max-width:120px;">
                <option value="10" selected>Last 10</option>
                <option value="20">Last 20</option>
                <option value="25">Last 25</option>
                <option value="50">Last 50</option>
                <option value="100">Last 100</option>
                <option value="200">Last 200</option>
              </select>
              <button class="btn btn-sm btn-outline-secondary" id="btnRefreshJobs"><i class="bi bi-arrow-clockwise"></i></button>
            </div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table id="cut-jobs-table" class="table table-sm table-striped">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>Date</th>
                    <th>Source</th>
                    <th>Operator</th>
                    <th>Status</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <input type="hidden" id="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>" />
  </div>
</div>

<script>
// Mark this page as using the v2 inch-based slab cutting UI so legacy global JS skips rebinding
window.SLAB_CUT_V2 = true;
(function(){
  if (!$('.page-slab_cutting').length) return;

  const $type = $('#source_type');
  const $search = $('#source_search');
  const $src = $('#source_id');
  const $op = $('#operator_id');

  function buildLabel(r, type){
    const safe = v => $('<div>').text(v||'').html();
    const mmToIn = v => {
      const n = Number(v);
      return isNaN(n) ? null : (n/25.4);
    };
    if (type === 'finished'){
      // Prefer inches if provided by API; else convert from mm. Order: Length x Height, 3 decimals
      let L = null, H = null;
      if (r.length_in != null && r.length_in !== '') L = Number(r.length_in);
      else if (r.length_mm != null && r.length_mm !== '') L = mmToIn(r.length_mm);
      if (r.width_in != null && r.width_in !== '') H = Number(r.width_in);
      else if (r.width_mm != null && r.width_mm !== '') H = mmToIn(r.width_mm);
      const l_in = (L!=null && !isNaN(L)) ? L.toFixed(3) : '';
      const h_in = (H!=null && !isNaN(H)) ? H.toFixed(3) : '';
      const size = [l_in, 'x', h_in].join(' ');
      const color = r.color_name ? ` / ${safe(r.color_name)}` : '';
      const fin = r.finish_name ? ` / ${safe(r.finish_name)}` : '';
      return `${safe(r.code)} - PO ${safe(r.po_no)} / Slab ${safe(r.slab_no)}${color}${fin} (${size} in)`;
    } else if (type === 'raw'){
      // Display raw material size using stored inches without rounding; fallback to mm->in if inches missing
      let lTxt = '', wTxt = '';
      if (r.length_in != null && r.length_in !== '') lTxt = String(r.length_in);
      else if (r.length_mm != null && r.length_mm !== '') lTxt = String(Number(r.length_mm)/25.4);
      if (r.width_in != null && r.width_in !== '') wTxt = String(r.width_in);
      else if (r.width_mm != null && r.width_mm !== '') wTxt = String(Number(r.width_mm)/25.4);
      const size = [lTxt, 'x', wTxt].join(' ');
      const color = r.color_name ? ` / ${safe(r.color_name)}` : '';
      return `${safe(r.code)} - PO ${safe(r.po_no)} / Slab ${safe(r.slab_no)}${color} (${size} in)`;
    } else { // cut_piece
      // Prefer inches if provided by API; else convert from mm
      let lTxt = '', wTxt = '';
      if (r.length_in != null && r.length_in !== '') lTxt = String(r.length_in);
      else if (r.length_mm != null && r.length_mm !== '') { const l = mmToIn(r.length_mm); lTxt = (l!=null)? l.toFixed(2) : ''; }
      if (r.width_in != null && r.width_in !== '') wTxt = String(r.width_in);
      else if (r.width_mm != null && r.width_mm !== '') { const w = mmToIn(r.width_mm); wTxt = (w!=null)? w.toFixed(2) : ''; }
      const size = [lTxt, 'x', wTxt].join(' ');
      const color = r.color_name ? ` / ${safe(r.color_name)}` : '';
      const fin = r.finish_name ? ` / ${safe(r.finish_name)}` : '';
      const slab = (r.slab_no!=null && String(r.slab_no).trim()!=='') ? String(r.slab_no).trim() : '';
      const pcNo = (r.piece_no!=null && r.piece_no!=='') ? String(r.piece_no).padStart(3,'0') : '';
      const recutTag = (r.parent_piece_id!=null && String(r.parent_piece_id).trim()!=='') ? ' (Re-cut)' : '';
      const masterSlab = (slab!=='') ? ` / Master Slab ${safe(slab)}` : '';
      const pieceTxt = (pcNo!=='') ? ` / Piece ${safe(pcNo)}` : '';
      return `${safe(r.code)}${recutTag} - PO ${safe(r.po_no)}${masterSlab}${pieceTxt}${color}${fin} (${size} in)`;
    }
  }

  function loadSources(){
    const type = $type.val();
    const q = ($search.val()||'').trim();
    $src.empty().append('<option value="">Loading...</option>');
    $.get('api/slab_cutting.php', { action:'list_sources', type, q }, function(res){
      const rows = res.data || [];
      const opts = ['<option value="">Select source</option>'];
      rows.forEach(r=>{
        // Derive inches for data attributes
        let Lin=null, Win=null;
        if (type==='raw') {
          Lin = (r.length_in!==undefined && r.length_in!=='') ? Number(r.length_in) : (r.length_mm!=null? Number(r.length_mm)/25.4 : null);
          Win = (r.width_in!==undefined && r.width_in!=='') ? Number(r.width_in) : (r.width_mm!=null? Number(r.width_mm)/25.4 : null);
        } else if (type==='finished') {
          Lin = (r.length_in!==undefined && r.length_in!=='') ? Number(r.length_in) : ((r.length_mm!=null) ? Number(r.length_mm)/25.4 : null);
          Win = (r.width_in!==undefined && r.width_in!=='') ? Number(r.width_in) : ((r.width_mm!=null) ? Number(r.width_mm)/25.4 : null);
        } else { // cut_piece
          Lin = (r.length_in!==undefined && r.length_in!=='') ? Number(r.length_in) : (r.length_mm!=null? Number(r.length_mm)/25.4 : null);
          Win = (r.width_in!==undefined && r.width_in!=='') ? Number(r.width_in) : (r.width_mm!=null? Number(r.width_mm)/25.4 : null);
        }
        const areaSqft = (Lin>0 && Win>0) ? (Lin/12.0)*(Win/12.0) : '';
        opts.push(`<option value="${r.id}" data-l-in="${Lin??''}" data-w-in="${Win??''}" data-area-sqft="${areaSqft}">${buildLabel(r, type)}</option>`);
      });
      $src.html(opts.join(''));
    }).fail(function(xhr){
      const msg = (xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText || 'Error loading sources';
      if (window.showToast) window.showToast(msg, 'danger'); else alert(msg);
      $src.html('<option value="">Error</option>');
    });
  }

  function loadOperators(){
    $op.empty().append('<option value="">Loading operators...</option>');
    $.get('api/slab_cutting.php', { action:'list_operators' }, function(res){
      const rows = res.data || [];
      const opts = ['<option value="">Select operator</option>'];
      rows.forEach(r=>{ opts.push(`<option value="${r.id}">${$('<div>').text(r.full_name||'').html()}</option>`); });
      $op.html(opts.join(''));
    }).fail(function(xhr){
      const msg = (xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText || 'Error loading operators';
      if (window.showToast) window.showToast(msg, 'danger'); else alert(msg);
      $op.html('<option value="">Error</option>');
    });
  }

  // Piece rows helpers (inches UI, area in sqft)
  function parseNumInches(v){
    const n = Number(String(v||'').replace(',', '.'));
    return isNaN(n) ? 0 : n;
  }
  function recalcRow($tr){
    const L = parseNumInches($tr.find('.pc-l-in').val());
    const H = parseNumInches($tr.find('.pc-h-in').val());
    const area = (L>0 && H>0) ? ((L*H)/144.0) : 0; // inches^2 to sq.ft
    $tr.find('.pc-area-in').text(area.toFixed(3));
    recalcTotal();
  }
  function recalcTotal(){
    let sum=0; $('#piecesTable tbody tr').each(function(){ const a = Number(String($(this).find('.pc-area-in').text()||'').replace(',', '.'))||0; sum += a; });
    $('#piecesTotal').text(sum.toFixed(3));
  }
  function addPieceRow(){
    const idx = $('#piecesTable tbody tr').length + 1;
    const tr = $(
      `<tr>
        <td>${idx}</td>
        <td><input type="number" step="0.001" min="0" class="form-control form-control-sm pc-l-in" placeholder="Length in"></td>
        <td><input type="number" step="0.001" min="0" class="form-control form-control-sm pc-h-in" placeholder="Height in"></td>
        <td class="text-end"><span class="pc-area-in">0.000</span></td>
        <td><button type="button" class="btn btn-sm btn-outline-danger pc-del" title="Remove"><i class="bi bi-x"></i></button></td>
      </tr>`);
    tr.on('click', '.pc-del', function(){ tr.remove(); // reindex rows
      $('#piecesTable tbody tr').each(function(i){ $(this).find('td:first').text(i+1); });
      recalcTotal();
    });
    $('#piecesTable tbody').append(tr);
    recalcRow(tr);
  }
  function clearPieces(){ $('#piecesTable tbody').empty(); recalcTotal(); }

  function fetchCutPiecesLocal(){
    const q = ($('#cutPiecesSearch').val()||'').trim();
    const limit = parseInt($('#cutPiecesLimit').val()||'10',10) || 10;
    const params = { action:'list_pieces', limit };
    if (q) params.q = q;
    $.get('api/slab_cutting.php', params, function(res){
      const tbody = $('#cut-pieces-table tbody').empty();
      const rows = res.data || [];
      if (!rows.length) { tbody.append('<tr><td colspan="9" class="text-center text-muted">No cut pieces</td></tr>'); return; }
      rows.forEach(p => {
        // API returns inches as length_in/width_in on v2; fallback to mm conversion if not present
        let Lin = (p.length_in != null && p.length_in !== '') ? Number(p.length_in) : (Number(p.length_mm||0)/25.4);
        let Win = (p.width_in != null && p.width_in !== '') ? Number(p.width_in) : (Number(p.width_mm||0)/25.4);
        const tr = $('<tr>');
        tr.append(`<td>${p.id}</td>`);
        tr.append(`<td>${p.job_id}</td>`);
        tr.append(`<td>${$('<div>').text(p.po_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(p.slab_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(p.cut_piece_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(p.recut_piece_no||'').html()}</td>`);
        tr.append(`<td>${isFinite(Lin)?Lin.toFixed(2):''} x ${isFinite(Win)?Win.toFixed(2):''}</td>`);
        tr.append(`<td>${Number(p.area_sq_ft||0).toFixed(3)}</td>`);
        tr.append(`<td>${parseInt(p.is_available)?'Yes':'No'}</td>`);
        tbody.append(tr);
      });
    });
  }
  function fetchCutJobsLocal(){
    const q = ($('#cutJobsSearch').val()||'').trim();
    const limit = parseInt($('#cutJobsLimit').val()||'10',10) || 10;
    const params = { action:'list_jobs', limit };
    if (q) params.q = q;
    $.get('api/slab_cutting.php', params, function(res){
      const tbody = $('#cut-jobs-table tbody').empty();
      const rows = res.data || [];
      if (!rows.length) { tbody.append('<tr><td colspan="6" 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.job_date||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(j.source_label || ((j.source_type||'')+'-'+(j.source_id||''))).html()}</td>`);
        tr.append(`<td>${$('<div>').text(j.operator_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(j.status||'').html()}</td>`);
        tr.append(`<td><button class="btn btn-sm btn-outline-danger sc-job-del" data-id="${j.id}"><i class="bi bi-trash"></i></button></td>`);
        tbody.append(tr);
      });
    });
  }
  // delete job handler
  $(document).on('click','.sc-job-del', function(){
    if(!confirm('Delete this cutting job? This will delete its pieces as well.')) return;
    const id = $(this).data('id');
    const csrf = $('#csrf').val();
    $.post('api/slab_cutting.php?action=delete_job', { id, csrf }, function(){
      if (window.showToast) window.showToast('Cutting job deleted', 'success');
      // refresh sources so a restored raw slab shows again
      loadSources();
      if (typeof fetchCutPiecesLocal==='function') fetchCutPiecesLocal();
      if (typeof fetchCutJobsLocal==='function') fetchCutJobsLocal();
    }).fail(function(xhr){
      const msg = (xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText || 'Error';
      if (window.showToast) window.showToast(msg, 'danger'); else alert(msg);
    });
  });

  // events
  $('#btnRefreshSources').on('click', loadSources);
  $type.on('change', function(){ $search.val(''); loadSources(); });
  let t=null; $search.on('input', function(){ clearTimeout(t); t=setTimeout(loadSources, 400); });
  $('#btnAddPiece').on('click', addPieceRow);
  $('#btnClearPieces').on('click', clearPieces);
  // Also hook inventory refresh button to global fetchers if present
  // Prefer local fetchers on v2 page to ensure inches rendering
  $('#btnRefreshPieces').on('click', function(){ if (typeof fetchCutPiecesLocal==='function') fetchCutPiecesLocal(); else if (typeof fetchCutPieces==='function') fetchCutPieces(); });
  $('#btnRefreshJobs').on('click', function(){ if (typeof fetchCutJobsLocal==='function') fetchCutJobsLocal(); else if (typeof fetchCutJobs==='function') fetchCutJobs(); });

  let tp=null;
  $('#cutPiecesSearch').on('input', function(){ clearTimeout(tp); tp=setTimeout(fetchCutPiecesLocal, 300); });
  $('#cutPiecesLimit').on('change', fetchCutPiecesLocal);
  let tj=null;
  $('#cutJobsSearch').on('input', function(){ clearTimeout(tj); tj=setTimeout(fetchCutJobsLocal, 300); });
  $('#cutJobsLimit').on('change', fetchCutJobsLocal);
  // Delegated handler to ensure inch-based calc always applies
  $('#piecesTable').off('input change keyup', '.pc-l-in, .pc-w-in');
  $('#piecesTable').on('input change keyup', '.pc-l-in, .pc-h-in', function(e){
    if (e && e.stopImmediatePropagation) e.stopImmediatePropagation();
    recalcRow($(this).closest('tr'));
    return false;
  });

  // Submit create job: send inches directly; API converts to mm and computes area
  $('#cutJobForm').on('submit', function(e){
    e.preventDefault();
    // Operator required
    if (!($('#operator_id').val()||'').trim()) { if (window.showToast) window.showToast('Operator is required.', 'warning'); else alert('Operator is required.'); return; }
    // Collect pieces
    const pieces=[]; let totalSqft=0;
    $('#piecesTable tbody tr').each(function(i){
      const L_in = Number($(this).find('.pc-l-in').val()||0);
      const H_in = Number($(this).find('.pc-h-in').val()||0);
      if (L_in>0 && H_in>0){ pieces.push({ piece_no: i+1, length_in: L_in, width_in: H_in }); totalSqft += (L_in/12.0)*(H_in/12.0); }
    });
    if (!pieces.length){ if (window.showToast) window.showToast('Please add at least one piece with valid Length and Width (in).', 'warning'); else alert('Please add at least one piece with valid Length and Width (in).'); return; }
    // Validate against parent slab size: total area must match selected source area
    const $opt = $('#source_id option:selected');
    const parentArea = Number($opt.attr('data-area-sqft')||'0');
    if (parentArea>0){
      const diff = Math.abs(totalSqft - parentArea);
      if (diff > 0.01){ // allow small tolerance
        const msg = `Total pieces area (${totalSqft.toFixed(3)} sqft) must match parent slab area (${parentArea.toFixed(3)} sqft).`;
        if (window.showToast) window.showToast(msg, 'warning'); else alert(msg);
        return;
      }
    }
    const fd = new FormData(this);
    fd.append('action','create_job');
    fd.append('pieces_json', JSON.stringify(pieces));
    const $btn = $(this).find("button[type='submit']");
    const prevTxt = $btn.html();
    $btn.prop('disabled', true).html('Saving...');
    $.ajax({ url:'api/slab_cutting.php', method:'POST', data: fd, contentType:false, processData:false })
      .done(function(){
        if (window.showToast) window.showToast('Cutting job created', 'success');
        loadSources();
        if (typeof fetchCutPiecesLocal==='function') fetchCutPiecesLocal();
        if (typeof fetchCutJobsLocal==='function') fetchCutJobsLocal();
        clearPieces(); $('#operator_name').val(''); $('#notes').val('');
      })
      .fail(function(xhr){
        const msg = (xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText || 'Error creating job';
        if (window.showToast) window.showToast(msg, 'danger'); else alert(msg);
      })
      .always(function(){ $btn.prop('disabled', false).html(prevTxt); });
  });

  // initial load
  loadSources();
  loadOperators();
  // Prefer local fetchers on v2 page to ensure inches rendering
  if (typeof fetchCutPiecesLocal==='function') fetchCutPiecesLocal(); else if (typeof fetchCutPieces==='function') fetchCutPieces();
  if (typeof fetchCutJobsLocal==='function') fetchCutJobsLocal(); else if (typeof fetchCutJobs==='function') fetchCutJobs();
})();
</script>
