<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-cutting_inventory">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Cutting Slab Inventory</h4>
      <div class="d-flex gap-2">
        <div class="btn-group">
          <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Columns</button>
          <div class="dropdown-menu dropdown-menu-end p-3" style="min-width: 260px; max-height: 60vh; overflow:auto;" id="ciColumnsMenu"></div>
        </div>
        <button class="btn btn-outline-success" id="btnExportCIXlsx"><i class="bi bi-file-earmark-excel"></i> Export</button>
        <button class="btn btn-outline-secondary" id="btnRefreshCutInv"><i class="bi bi-arrow-clockwise"></i></button>
      </div>
    </div>

    <div class="card shadow-sm mb-3">
      <div class="card-body">
        <div class="row g-2 align-items-end">
          <div class="col-md-3">
            <label class="form-label">Search</label>
            <input type="text" id="ci_q" class="form-control" placeholder="ID / Job ID">
          </div>
          <div class="col-md-3">
            <label class="form-label">Status</label>
            <select id="ci_status" class="form-select">
              <option value="">All</option>
              <option value="usable">Usable</option>
              <option value="unusable">Unusable</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">Availability</label>
            <select id="ci_avail" class="form-select">
              <option value="">All</option>
              <option value="available">Available</option>
              <option value="reserved">Reserved</option>
              <option value="consumed">Consumed</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">Branch</label>
            <select id="ci_branch" class="form-select"></select>
          </div>
          <div class="col-md-3">
            <label class="form-label">Color</label>
            <select id="ci_color" class="form-select"></select>
          </div>
        </div>
        <div class="row g-2 align-items-end mt-2">
          <div class="col-md-3">
            <label class="form-label">Slab No</label>
            <input type="text" id="ci_slab" class="form-control" placeholder="Search slab no">
          </div>
          <div class="col-md-3">
            <label class="form-label">Length (mm)</label>
            <div class="input-group">
              <input type="number" id="ci_len_min" class="form-control" placeholder="Min">
              <span class="input-group-text">-</span>
              <input type="number" id="ci_len_max" class="form-control" placeholder="Max">
            </div>
          </div>
          <div class="col-md-3">
            <label class="form-label">Width (mm)</label>
            <div class="input-group">
              <input type="number" id="ci_wid_min" class="form-control" placeholder="Min">
              <span class="input-group-text">-</span>
              <input type="number" id="ci_wid_max" class="form-control" placeholder="Max">
            </div>
          </div>
          <div class="col-md-3">
            <label class="form-label">Location</label>
            <select id="ci_loc" class="form-select"></select>
          </div>
        </div>
      </div>
    </div>

    <!-- Summary Section -->
    <div class="card shadow-sm mb-3" id="ciSummaryCard" style="display:none;">
      <div class="card-body py-2">
        <div class="row">
          <div class="col-md-6">
            <strong>Total Pieces:</strong> <span id="ciTotalPieces" class="badge bg-primary fs-6">0</span>
          </div>
          <div class="col-md-6 text-md-end">
            <strong>Total Area:</strong> <span id="ciTotalArea" class="badge bg-success fs-6">0.000</span> sqft
          </div>
        </div>
      </div>
    </div>

    <div class="card shadow-sm">
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-sm align-middle" id="ci_table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Slab No</th>
                <th>PO No</th>
                <th>Color</th>
                <th>Cut Piece No</th>
                <th>Re-cut Piece No</th>
                <th>Job</th>
                <th>Piece</th>
                <th>Length (SQF)</th>
                <th>Width (SQF)</th>
                <th>Thick (mm)</th>
                <th>Area (sqft)</th>
                <th>Branch</th>
                <th>Status</th>
                <th>Avail</th>
                <th>Location</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Detail Modal -->
    <div class="modal fade" id="ciDetailModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header"><h6 class="modal-title">Cut Piece Detail</h6>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-1"><small class="text-muted">ID</small><div id="ci_d_id"></div></div>
            <div class="mb-1"><small class="text-muted">Slab No</small><div id="ci_d_slab"></div></div>
            <div class="mb-1"><small class="text-muted">Invoice No</small><div id="ci_d_invoice"></div></div>
            <div class="mb-1"><small class="text-muted">Invoice Status</small><div id="ci_d_invoice_status"></div></div>
            <div class="mb-1"><small class="text-muted">Job</small><div id="ci_d_job"></div></div>
            <div class="mb-1"><small class="text-muted">Size (mm)</small><div id="ci_d_size"></div></div>
            <div class="mb-1"><small class="text-muted">Area (sqft)</small><div id="ci_d_area"></div></div>
            <div class="mb-1"><small class="text-muted">Status</small><div id="ci_d_status"></div></div>
            <div class="mb-1"><small class="text-muted">Location</small><div id="ci_d_loc"></div></div>
          </div>
          <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button></div>
        </div>
      </div>
    </div>

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

<script>
(function(){
  if (!$('.page-cutting_inventory').length) return;
  const CAN_EDIT = true;
  const IS_ADMIN = <?php echo has_role(['admin','super_admin']) ? 'true' : 'false'; ?>;
  const USER_BRANCH_ID = <?php echo json_encode($_SESSION['branch_id'] ?? null); ?>;
  const $tbl = $('#ci_table tbody');
  const $csrf = $('#csrf');
  let BRANCHES = [];
  let LOCATIONS = [];
  let COLORS = [];
  let CI_QUERY_SEQ = 0;

  const CI_COLUMNS = [
    { key:'id', label:'ID', idx:0 },
    { key:'slab_no', label:'Slab No', idx:1 },
    { key:'po_no', label:'PO No', idx:2 },
    { key:'color', label:'Color', idx:3 },
    { key:'cut_piece_no', label:'Cut Piece No', idx:4 },
    { key:'recut_piece_no', label:'Re-cut Piece No', idx:5 },
    { key:'job', label:'Job', idx:6 },
    { key:'piece', label:'Piece', idx:7 },
    { key:'length', label:'Length', idx:8 },
    { key:'width', label:'Width', idx:9 },
    { key:'thickness', label:'Thick (mm)', idx:10 },
    { key:'area', label:'Area (sqft)', idx:11 },
    { key:'branch', label:'Branch', idx:12 },
    { key:'status', label:'Status', idx:13 },
    { key:'avail', label:'Avail', idx:14 },
    { key:'location', label:'Location', idx:15 },
    { key:'actions', label:'Actions', idx:16 }
  ];

  function loadColumnPrefs(){
    try {
      const raw = localStorage.getItem('ci_columns');
      return raw ? JSON.parse(raw) : {};
    } catch(e){
      return {};
    }
  }
  function saveColumnPrefs(p){
    try { localStorage.setItem('ci_columns', JSON.stringify(p||{})); } catch(e){}
  }
  function applyColumnVisibility(){
    const prefs = loadColumnPrefs();
    const $table = $('#ci_table');
    CI_COLUMNS.forEach(c=>{
      const visible = prefs[c.key] !== false;
      const disp = visible ? '' : 'none';
      $table.find('thead tr th').eq(c.idx).css('display', disp);
      $table.find('tbody tr').each(function(){
        $(this).find('td').eq(c.idx).css('display', disp);
      });
    });
  }
  function buildColumnsMenu(){
    const prefs = loadColumnPrefs();
    const html=[];
    CI_COLUMNS.forEach(c=>{
      const checked = prefs[c.key] !== false;
      html.push(
        `<div class="form-check">
          <input class="form-check-input ci-col-toggle" type="checkbox" id="ci_col_${c.key}" data-key="${c.key}" ${checked?'checked':''}>
          <label class="form-check-label" for="ci_col_${c.key}">${$('<div>').text(c.label).html()}</label>
        </div>`
      );
    });
    $('#ciColumnsMenu').html(html.join(''));
  }

  function loadBranches(cb){
    $.get('api/branches.php', { action:'list' }, function(res){
      BRANCHES = (res.data||[]).filter(b=>parseInt(b.is_active));
      const opts=['<option value="">All</option>'];
      BRANCHES.forEach(b=>opts.push(`<option value="${b.id}">${$('<div>').text(b.name||'').html()}</option>`));
      $('#ci_branch').html(opts.join(''));

      // For non-admin users: auto-select their branch and disable the filter
      if (!IS_ADMIN && USER_BRANCH_ID) {
        $('#ci_branch').val(USER_BRANCH_ID).prop('disabled', true);
      }

      if (typeof cb === 'function') cb();
    });
  }

  function loadColors(cb){
    $.get('api/colors.php', { action:'list' }, function(res){
      COLORS = (res.data||[]);
      const opts=['<option value="">All</option>'];
      COLORS.forEach(c=>opts.push(`<option value="${c.id}">${$('<div>').text(c.name||'').html()}</option>`));
      $('#ci_color').html(opts.join(''));
      if (typeof cb === 'function') cb();
    });
  }

  function renderBranchCell(row){
    const currentId = row.branch_id || '';
    if (!CAN_EDIT){
      const found = BRANCHES.find(b=>String(b.id)===String(currentId));
      return $('<td>').text(found? (found.name||('Branch #'+found.id)) : '');
    }
    const sel = $('<select class="form-select form-select-sm ci-branch">');
    sel.append('<option value="">Select</option>');
    BRANCHES.forEach(b=> sel.append(`<option value="${b.id}">${$('<div>').text(b.name||'').html()}</option>`));
    sel.val(String(currentId||''));
    sel.data('id', row.id);
    return $('<td>').append(sel);
  }

  function renderLocationCell(row){
    const currentLocId = row.store_location_id || '';
    if (!CAN_EDIT){
      return $('<td>').text(row.location_name || '');
    }
    const sel = $('<select class="form-select form-select-sm ci-loc">');
    sel.append('<option value="">(none)</option>');
    LOCATIONS.forEach(l=> sel.append(`<option value="${l.id}">${$('<div>').text(l.name||'').html()}</option>`));
    sel.val(String(currentLocId||''));
    sel.data('id', row.id);
    return $('<td>').append(sel);
  }

  function renderStatusCell(row){
    const currentStatus = row.status || '';
    if (!CAN_EDIT){
      return $('<td>').text(currentStatus);
    }
    const sel = $('<select class="form-select form-select-sm ci-status">');
    sel.append('<option value="usable">Usable</option>');
    sel.append('<option value="unusable">Unusable</option>');
    sel.val(currentStatus || 'usable');
    sel.data('id', row.id);
    return $('<td>').append(sel);
  }

  function loadLocationsForBranch(branchId, cb){
    const params = { action:'list' };
    if (branchId) params.branch_id = branchId;
    $.get('api/store_locations.php', params, function(res){
      LOCATIONS = res.data || [];
      const opts=['<option value="">All</option>'];
      LOCATIONS.forEach(l=>opts.push(`<option value="${l.id}">${$('<div>').text(l.name||'').html()}</option>`));
      $('#ci_loc').html(opts.join(''));
      if (typeof cb === 'function') cb();
    });
  }

  function query(){
    const seq = ++CI_QUERY_SEQ;
    // For non-admin users, always use their assigned branch
    const branchId = IS_ADMIN ? $('#ci_branch').val() : (USER_BRANCH_ID || $('#ci_branch').val());
    const params = {
      action:'list',
      q: $('#ci_q').val(),
      status: $('#ci_status').val(),
      avail: $('#ci_avail').val(),
      branch_id: branchId,
      color_id: $('#ci_color').val(),
      location_id: $('#ci_loc').val(),
      slab_q: $('#ci_slab').val(),
      len_min: $('#ci_len_min').val(), len_max: $('#ci_len_max').val(),
      wid_min: $('#ci_wid_min').val(), wid_max: $('#ci_wid_max').val()
    };
    $.get('api/cut_pieces.php', params, function(res){
      if (seq !== CI_QUERY_SEQ) return; // ignore stale responses
      $tbl.empty(); const rows = res.data||[];
      
      // Calculate summary totals
      let totalPieces = rows.length;
      let totalArea = rows.reduce((sum, r) => sum + Number(r.area_sq_ft || 0), 0);
      
      // Update summary display
      $('#ciTotalPieces').text(totalPieces.toLocaleString());
      $('#ciTotalArea').text(totalArea.toFixed(3));
      $('#ciSummaryCard').toggle(totalPieces > 0);
      
      if (!rows.length){ $tbl.append('<tr><td colspan="17" class="text-center text-muted">No pieces found</td></tr>'); return; }
      rows.forEach(r=>{
        const tr = $('<tr>');
        tr.append(`<td>${r.id}</td>`);
        tr.append(`<td>${$('<div>').text(r.slab_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.po_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.color_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.cut_piece_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.recut_piece_no||'').html()}</td>`);
        tr.append(`<td>${r.job_id??''}</td>`);
        tr.append(`<td>${r.piece_no??''}</td>`);
        tr.append(`<td>${Math.round(r.length_mm||0)}</td>`);
        tr.append(`<td>${Math.round(r.width_mm||0)}</td>`);
        tr.append(`<td>${r.thickness_mm??''}</td>`);
        tr.append(`<td>${Number(r.area_sq_ft||0).toFixed(3)}</td>`);
        tr.append(renderBranchCell(r));
        tr.append(renderStatusCell(r));
        const isAvail = parseInt(r.is_available) ? true : false;
        const invSt = String(r.invoice_status || '');
        const hasRes = !!(r.reserved_invoice_item_id);
        let availHtml = '';
        if (isAvail) availHtml = '<span class="badge bg-success">Available</span>';
        else if (hasRes && invSt === 'draft') availHtml = '<span class="badge bg-warning text-dark">Reserved</span>';
        else availHtml = '<span class="badge bg-secondary">Consumed</span>';
        tr.append(`<td>${availHtml}</td>`);
        tr.append(renderLocationCell(r));
        tr.append(`<td><button class="btn btn-sm btn-outline-secondary ci-view" data-id="${r.id}"><i class="bi bi-eye"></i></button></td>`);
        $tbl.append(tr);
      });
      applyColumnVisibility();
    }).fail(xhr=> alert((xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText || 'Error loading pieces'));
  }

  // Change branch/status/location inline (admin-only for branch, everyone allowed for status as per API rules)
  $(document).on('change', 'select.ci-branch, select.ci-status, select.ci-loc', function(){
    if (!CAN_EDIT) return;
    const id = $(this).data('id');
    const $row = $(this).closest('tr');
    const branch_id = $row.find('select.ci-branch').val();
    const status = $row.find('select.ci-status').val();
    const store_location_id = $row.find('select.ci-loc').val();
    const fd = new FormData();
    fd.append('csrf', $csrf.val());
    fd.append('action','update');
    fd.append('id', id);
    if (branch_id !== undefined) fd.append('branch_id', branch_id);
    if (status !== undefined) fd.append('status', status);
    if (store_location_id !== undefined) fd.append('store_location_id', store_location_id);
    $.ajax({ url:'api/cut_pieces.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(()=>{ window.showToast && window.showToast('Updated','success'); })
      .fail(xhr=> alert((xhr.responseJSON && xhr.responseJSON.message) || 'Update failed'));
  });

  // View detail
  $(document).on('click', '.ci-view', function(){
    const id=$(this).data('id');
    $.get('api/cut_pieces.php', { action:'get', id }, function(res){
      const d=res.data||{};
      $('#ci_d_id').text(d.id||'');
      $('#ci_d_slab').text(d.slab_no||'');
      $('#ci_d_invoice').text(d.invoice_no || '');
      $('#ci_d_invoice_status').text(d.invoice_status || '');
      $('#ci_d_job').text(d.job_id||'');
      const size = [Math.round(d.length_mm||0), Math.round(d.width_mm||0), Math.round(d.thickness_mm||0)].join(' x ');
      $('#ci_d_size').text(size);
      $('#ci_d_area').text(Number(d.area_sq_ft||0).toFixed(3));
      $('#ci_d_status').text(d.status||'');
      $('#ci_d_loc').text(d.location_name||'');
      $('#ciDetailModal').modal('show');
    });
  });

  // Bind filter actions
  $('#btnRefreshCutInv').on('click', query);
  $('#ci_q, #ci_slab, #ci_len_min, #ci_len_max, #ci_wid_min, #ci_wid_max').on('keydown', function(e){ if(e.key==='Enter') query(); });
  $('#ci_status, #ci_avail, #ci_color').on('change', query);
  $('#ci_branch').on('change', function(){
    const bid = $(this).val();
    loadLocationsForBranch(bid, query);
  });
  $('#ci_loc').on('change', query);

  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 thead = table.querySelector('thead');
    const tbody = table.querySelector('tbody');
    if (!thead || !tbody) { alert('No data to export'); return; }
    const prefs = loadColumnPrefs();
    const visibleIdx = CI_COLUMNS.filter(c=> prefs[c.key] !== false).map(c=>c.idx);
    const headerCells = Array.from(thead.querySelectorAll('th'));
    const headers = visibleIdx.map(i => ((headerCells[i] && headerCells[i].innerText) || '').trim());
    const rows = Array.from(tbody.querySelectorAll('tr'))
      .filter(tr => tr.querySelectorAll('td').length)
      .map(tr => {
        const tds = Array.from(tr.querySelectorAll('td'));
        return visibleIdx.map(i => ((tds[i] && tds[i].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 || 'Inventory').slice(0,31));
    XLSX.writeFile(wb, safeFilePart(filenameBase || 'cutting_inventory') + '.xlsx');
  }
  $('#btnExportCIXlsx').on('click', function(){
    const d = new Date();
    const stamp = [d.getFullYear(), String(d.getMonth()+1).padStart(2,'0'), String(d.getDate()).padStart(2,'0')].join('-');
    exportTable('#ci_table', 'cutting_inventory_' + stamp, 'CuttingInventory');
  });

  // Initial load: branches then locations (for selected/all branch), then query
  loadBranches(function(){
    loadColors(function(){
      const bid = $('#ci_branch').val();
      loadLocationsForBranch(bid, query);
    });
  });

  buildColumnsMenu();
  applyColumnVisibility();
  $(document).on('change', '.ci-col-toggle', function(){
    const key = $(this).data('key');
    const prefs = loadColumnPrefs();
    prefs[key] = $(this).is(':checked');
    saveColumnPrefs(prefs);
    applyColumnVisibility();
  });
})();
</script>

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