<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-finished-products">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Finished Products</h4>
      <div>
        <div class="btn-group me-2">
          <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="fpColumnsMenu"></div>
        </div>
        <button id="btnExportFPXlsx" class="btn btn-outline-success me-2"><i class="bi bi-file-earmark-excel"></i> Export</button>
        <button id="btnNewFP" class="btn btn-primary d-none"><i class="bi bi-plus-lg"></i></button>
      </div>
    </div>

    <ul class="nav nav-pills nav-fill small gap-2 mb-3 flex-wrap">
      <li class="nav-item">
        <span class="nav-link kpi-pill bg-primary text-white">Total: <strong id="kpiTotal">0</strong></span>
      </li>
      <li class="nav-item">
        <span class="nav-link kpi-pill bg-success text-white">Available: <strong id="kpiAvailable">0</strong></span>
      </li>
      <li class="nav-item">
        <span class="nav-link kpi-pill bg-warning text-dark">Reserved: <strong id="kpiReserved">0</strong></span>
      </li>
      <li class="nav-item">
        <span class="nav-link kpi-pill bg-danger text-white">Sold: <strong id="kpiSold">0</strong></span>
      </li>
      <li class="nav-item">
        <span class="nav-link kpi-pill bg-info text-dark">Total SQ.FT: <strong id="kpiSqFt">0.000</strong></span>
      </li>
      <li class="nav-item">
        <span class="nav-link kpi-pill bg-secondary text-white">Total SQ.M: <strong id="kpiSqM">0.000</strong></span>
      </li>
    </ul>

    <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">H</label>
          <div class="input-group">
            <input type="number" step="0.001" id="fltMinH" class="form-control" placeholder="Min">
            <span class="input-group-text">-</span>
            <input type="number" step="0.001" id="fltMaxH" class="form-control" placeholder="Max">
          </div>
        </div>
        <div class="col-md-3">
          <label class="form-label">L</label>
          <div class="input-group">
            <input type="number" step="0.001" id="fltMinL" class="form-control" placeholder="Min">
            <span class="input-group-text">-</span>
            <input type="number" step="0.001" id="fltMaxL" class="form-control" placeholder="Max">
          </div>
        </div>
        <div class="col-md-3">
          <label class="form-label">Sq.Ft</label>
          <div class="input-group">
            <input type="number" step="0.001" id="fltMinSqf" class="form-control" placeholder="Min">
            <span class="input-group-text">-</span>
            <input type="number" step="0.001" id="fltMaxSqf" class="form-control" placeholder="Max">
          </div>
        </div>
        <div class="col-md-2"><label class="form-label">Finish</label><select id="fltFinish" class="form-select"></select></div>
        <div class="col-md-2"><label class="form-label">Color</label><select id="fltColor" class="form-select"></select></div>
        <div class="col-md-2"><label class="form-label">PO Number</label><input type="text" id="fltPoNo" class="form-control" list="fpPoList"></div>
        <div class="col-md-2"><label class="form-label">Slab No</label><input type="text" id="fltSlabNo" class="form-control"></div>
        <div class="col-md-2"><label class="form-label">Branch</label><select id="fltBranch" class="form-select"></select></div>
        <div class="col-md-2"><label class="form-label">Store</label><select id="fltStore" class="form-select"></select></div>
        <div class="col-md-2"><label class="form-label">Status</label>
          <select id="fltStatus" class="form-select">
            <option value="available" selected>Available</option>
            <option value="reserved">Reserved</option>
            <option value="sold">Sold</option>
            <option value="cut">Cut</option>
            <option value="">All</option>
          </select>
        </div>
        <div class="col-md-2"><button id="btnSearch" class="btn btn-outline-secondary w-100"><i class="bi bi-search"></i></button></div>
      </div>
    </div></div>
    <datalist id="fpPoList"></datalist>

    <ul class="nav nav-tabs mb-2" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="tab-list-tab" data-bs-toggle="tab" data-bs-target="#tab-list" type="button" role="tab">List</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="tab-finish-tab" data-bs-toggle="tab" data-bs-target="#tab-finish" type="button" role="tab">By Finish</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="tab-color-tab" data-bs-toggle="tab" data-bs-target="#tab-color" type="button" role="tab">By Color</button>
      </li>
    </ul>
    <div class="tab-content">
      <div class="tab-pane fade show active" id="tab-list" role="tabpanel" aria-labelledby="tab-list-tab">
        <div class="card shadow-sm"><div class="card-body">
          <div class="table-responsive">
            <table id="fpList" class="table table-hover align-middle">
              <thead>
                <tr>
                  <th>Slab</th><th>PO Number</th><th>Color</th><th>Finish</th><th>Pre H</th><th>Pre L</th><th>Pre Sq.Ft</th><th>H</th><th>L</th><th>Sq.Ft</th><th>Type</th><th>Branch</th><th>Store</th><th>Completed</th><th>Remarks</th><th>Status</th><th>Actions</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
        </div></div>
      </div>
      <div class="tab-pane fade" id="tab-finish" role="tabpanel" aria-labelledby="tab-finish-tab">
        <div class="card shadow-sm"><div class="card-body">
          <div class="table-responsive">
            <table id="fpByFinish" class="table table-striped table-hover align-middle">
              <thead>
                <tr>
                  <th>Finish</th>
                  <th>Color</th>
                  <th>Count</th>
                  <th>Total SQ.FT</th>
                  <th>Total SQ.M</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
        </div></div>
      </div>
      <div class="tab-pane fade" id="tab-color" role="tabpanel" aria-labelledby="tab-color-tab">
        <div class="card shadow-sm"><div class="card-body">
          <div class="table-responsive">
            <table id="fpByColor" class="table table-striped table-hover align-middle">
              <thead>
                <tr>
                  <th>Color</th>
                  <th>Count</th>
                  <th>Total SQ.FT</th>
                  <th>Total SQ.M</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
        </div></div>
      </div>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="fpEditModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Edit Finished Product</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="fpEditForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="id" id="fp_id">
          <div class="row g-2">
            <div class="col-6"><label class="form-label">H</label><input type="number" step="0.001" class="form-control" name="final_height" id="fp_h"></div>
            <div class="col-6"><label class="form-label">L</label><input type="number" step="0.001" class="form-control" name="final_length" id="fp_l"></div>
            <div class="col-6"><label class="form-label">Sq.Ft</label><input type="number" step="0.001" class="form-control" name="final_sq_ft" id="fp_sqf"></div>
            <div class="col-6"><label class="form-label">Finish</label><select class="form-select" name="finish_id" id="fp_finish"></select></div>
            <div class="col-6"><label class="form-label">Type</label><select class="form-select" name="type_id" id="fp_type" ></select></div>
            <div class="col-6">
                <label class="form-label">Color</label>
                <!-- visible but not editable -->
                <select class="form-select" id="fp_color" disabled></select>
                <!-- hidden field actually submitted -->
                <input type="hidden" name="color_id" id="fp_color_hidden">
              </div>
            <div class="col-6"><label class="form-label">Branch</label><select class="form-select" name="branch_id" id="fp_branch"></select></div>
            <div class="col-6"><label class="form-label">Store</label><select class="form-select" name="store_location_id" id="fp_store"></select></div>
            <div class="col-12"><label class="form-label">Quality</label><input type="text" class="form-control" name="quality" id="fp_quality"></div>
            <div class="col-12"><label class="form-label">Remarks</label><textarea class="form-control" name="remarks" id="fp_remarks" rows="2"></textarea></div>
            <div class="col-12"><label class="form-label">Status</label><select class="form-select" name="sale_status" id="fp_status"><option value="available">Available</option><option value="reserved">Reserved</option><option value="sold">Sold</option><option value="cut">Cut</option></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">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- View Modal -->
<div class="modal fade" id="fpViewModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Product Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="card mb-3 shadow-sm">
          <div class="card-header bg-primary text-white"><i class="bi bi-info-circle me-1"></i> Product Information</div>
          <div class="card-body">
            <div class="row g-2">
              <div class="col-md-6"><div><span class="text-muted">Product ID:</span> <span id="vd_fp_id"></span></div></div>
              <div class="col-md-6"><div><span class="text-muted">Created:</span> <span id="vd_created"></span></div></div>
              <div class="col-md-6"><div><span class="text-muted">Raw Material ID:</span> <span id="vd_rmp_id"></span></div></div>
              <div class="col-md-6"><div><span class="text-muted">Polishing Job:</span> <span id="vd_pj_id"></span></div></div>
              <div class="col-md-6"><div><span class="text-muted">Material Type:</span> <span id="vd_type"></span></div></div>
              <div class="col-md-6"><div><span class="text-muted">Color:</span> <span id="vd_color"></span></div></div>
              <div class="col-md-6"><div><span class="text-muted">Finish:</span> <span id="vd_finish"></span></div></div>
              <div class="col-md-6"><div><span class="text-muted">Quality Grade:</span> <span id="vd_quality" class="badge bg-secondary"></span></div></div>
              <div class="col-md-6"><div><span class="text-muted">Stock Status:</span> <span id="vd_status" class="badge bg-secondary text-capitalize"></span></div></div>
              <div class="col-md-6"><div><span class="text-muted">Branch / Store:</span> <span id="vd_branch_store"></span></div></div>
              <div class="col-md-6 d-none" id="vd_invoice_row"><div><span class="text-muted">Invoice No:</span> <span id="vd_invoice_no" class="fw-semibold"></span></div></div>
            </div>
          </div>
        </div>

        <div class="card mb-3 shadow-sm">
          <div class="card-header bg-success text-white"><i class="bi bi-rulers me-1"></i> Dimensions & Timeline</div>
          <div class="card-body">
            <div class="row g-3">
              <div class="col-md-6">
                <div class="fw-semibold mb-2">Before Polishing</div>
                <div>Slab No: <span id="vd_slab"></span></div>
                <div>Raw Size: <span id="vd_raw_h"></span> x <span id="vd_raw_l"></span></div>
                <div>Raw Sq.Ft: <span id="vd_raw_sqft"></span></div>
                <div>Raw Quality: <span id="vd_raw_quality"></span></div>
                <div>PO: <span id="vd_po"></span></div>
              </div>
              <div class="col-md-6">
                <div class="fw-semibold mb-2">Polishing</div>
                <div>Worker: <span id="vd_worker"></span></div>
                <div>Start: <span id="vd_start"></span></div>
                <div>End: <span id="vd_end"></span></div>
                <div>Pre Size: <span id="vd_pre_h"></span> x <span id="vd_pre_l"></span></div>
                <div>Completed: <span id="vd_completed"></span></div>
              </div>
            </div>
          </div>
        </div>

        <div class="card mb-3 shadow-sm">
          <div class="card-header bg-info text-white"><i class="bi bi-truck me-1"></i> Purchase Order</div>
          <div class="card-body">
            <div class="row g-2">
              <div class="col-md-4">Order No: <span id="vd_po_no"></span></div>
              <div class="col-md-4">Order Date: <span id="vd_po_date"></span></div>
              <div class="col-md-4">Supplier: <span id="vd_supplier"></span></div>
              <div class="col-md-4">Ship Mode: <span id="vd_ship"></span></div>
              <div class="col-md-4">Delivery Term: <span id="vd_delivery"></span></div>
              <div class="col-md-4">Payment Term: <span id="vd_payment"></span></div>
            </div>
          </div>
        </div>

        <div class="card mb-2 shadow-sm">
          <div class="card-header bg-dark text-white"><i class="bi bi-box-seam me-1"></i> Final Product</div>
          <div class="card-body">
            <div class="row g-2">
              <div class="col-md-3">H: <span id="vd_final_h"></span></div>
              <div class="col-md-3">L: <span id="vd_final_l"></span></div>
              <div class="col-md-3">Sq.Ft: <span id="vd_final_sqft"></span></div>
              <div class="col-md-3">Finish: <span id="vd_final_finish"></span></div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
  </div>

<script>
(function(){
  if (!$('.page-finished-products').length) return;
  // Role flag from server: only admins can edit/delete and change branch filter
  const CAN_EDIT_FP = <?php echo has_role(['admin','super_admin']) ? 'true' : 'false'; ?>;
  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 FP_COLS_KEY = 'fp_columns_v1';
  const FP_COLUMNS = [
    { idx: 0, key: 'slab', label: 'Slab' },
    { idx: 1, key: 'po', label: 'PO Number' },
    { idx: 2, key: 'color', label: 'Color' },
    { idx: 3, key: 'finish', label: 'Finish' },
    { idx: 4, key: 'preh', label: 'Pre H' },
    { idx: 5, key: 'prel', label: 'Pre L' },
    { idx: 6, key: 'presqf', label: 'Pre Sq.Ft' },
    { idx: 7, key: 'h', label: 'H' },
    { idx: 8, key: 'l', label: 'L' },
    { idx: 9, key: 'sqf', label: 'Sq.Ft' },
    { idx: 10, key: 'type', label: 'Type' },
    { idx: 11, key: 'branch', label: 'Branch' },
    { idx: 12, key: 'store', label: 'Store' },
    { idx: 13, key: 'completed', label: 'Completed' },
    { idx: 14, key: 'remarks', label: 'Remarks' },
    { idx: 15, key: 'status', label: 'Status' },
    { idx: 16, key: 'actions', label: 'Actions' }
  ];

  function loadColumnPrefs(){
    try {
      const raw = localStorage.getItem(FP_COLS_KEY);
      const parsed = raw ? JSON.parse(raw) : null;
      if (parsed && typeof parsed === 'object') return parsed;
    } catch(e) {}
    const def = {};
    FP_COLUMNS.forEach(c => { def[c.key] = true; });
    return def;
  }
  function saveColumnPrefs(prefs){
    try { localStorage.setItem(FP_COLS_KEY, JSON.stringify(prefs)); } catch(e) {}
  }
  function buildColumnsMenu(){
    const prefs = loadColumnPrefs();
    const $menu = $('#fpColumnsMenu');
    $menu.empty();
    FP_COLUMNS.forEach(col => {
      const id = 'fp_col_' + col.key;
      const checked = prefs[col.key] !== false;
      $menu.append(
        `<div class="form-check form-switch mb-2">
          <input class="form-check-input fp-col-toggle" type="checkbox" role="switch" id="${id}" data-colkey="${col.key}" ${checked ? 'checked' : ''}>
          <label class="form-check-label" for="${id}">${$('<div>').text(col.label).html()}</label>
        </div>`
      );
    });
  }
  function getDt(){
    if (!$.fn.DataTable || !$.fn.dataTable.isDataTable('#fpList')) return null;
    return $('#fpList').DataTable();
  }
  function applyColumnVisibility(){
    const dt = getDt();
    if (!dt) return;
    const prefs = loadColumnPrefs();
    FP_COLUMNS.forEach(col => {
      const vis = prefs[col.key] !== false;
      dt.column(col.idx).visible(vis, false);
    });
    dt.columns.adjust().draw(false);
  }

  // Cache for stores to filter by branch in edit modal
  let FP_STORES = [];
  function buildStoreOptions(stores){
    const sopts=['<option value="">Select</option>'];
    (stores||[]).forEach(x=> sopts.push(`<option value="${x.id}">${$('<div>').text(x.name).html()}</option>`));
    return sopts.join('');
  }
  function refreshEditStores(branchId, selectedStoreId){
    const bid = parseInt(branchId||0,10);
    const list = isNaN(bid) || !bid ? [] : (FP_STORES||[]).filter(s=> parseInt(s.branch_id||0,10)===bid);
    $('#fp_store').html(buildStoreOptions(list));
    if (selectedStoreId) {
      $('#fp_store').val(String(selectedStoreId));
    } else if (list.length) {
      $('#fp_store').val(String(list[0].id));
    }
  }
  // (deduped) cached lookups removed
  function loadOptions(){
    $.get('api/finished_products.php', { action:'options' }, function(res){
      const topts=['<option value="">All</option>']; (res.types||[]).forEach(x=>topts.push(`<option value="${x.id}">${$('<div>').text(x.name).html()}</option>`));
      const copts=['<option value="">All</option>']; (res.colors||[]).forEach(x=>copts.push(`<option value="${x.id}">${$('<div>').text(x.name).html()}</option>`));
      const bopts=['<option value="">All</option>']; (res.branches||[]).forEach(x=>bopts.push(`<option value="${x.id}">${$('<div>').text(x.name).html()}</option>`));
      const sopts=['<option value="">All</option>']; (res.stores||[]).forEach(x=>sopts.push(`<option value="${x.id}">${$('<div>').text(x.name).html()}</option>`));
      FP_STORES = res.stores || [];
      $('#fltColor').html(copts.join('')); $('#fltBranch').html(bopts.join('')); $('#fltStore').html(sopts.join(''));
      // edit selects (branch normal, store will be filtered on branch selection)
      $('#fp_type').html(topts.join('').replace('All','Select'));
      $('#fp_color').html(copts.join('').replace('All','Select'));
      $('#fp_branch').html(bopts.join('').replace('All','Select'));
      $('#fp_store').html('<option value="">Select</option>');

      // For non-admin users: auto-select their branch and disable the filter
      if (!IS_ADMIN && USER_BRANCH_ID) {
        $('#fltBranch').val(USER_BRANCH_ID).prop('disabled', true);
      }
    }).fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText || 'Error loading options'); });
    // finishes from existing materials API
    $.get('api/materials.php', { action:'list_finishes' }, function(res){
      const foptsFilter=['<option value="">All</option>'];
      const foptsEdit=['<option value="">Select</option>'];
      (res.data||[]).forEach(f=>{
        const opt = `<option value="${f.id}">${$('<div>').text(f.name).html()}</option>`;
        foptsFilter.push(opt);
        foptsEdit.push(opt);
      });
      $('#fltFinish').html(foptsFilter.join(''));
      $('#fp_finish').html(foptsEdit.join(''));
    }).fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText || 'Error loading finishes'); });
  }

  function refreshStats(){
    // For non-admin users, always use their assigned branch
    const branchId = IS_ADMIN ? $('#fltBranch').val() : (USER_BRANCH_ID || $('#fltBranch').val());
    const params = { action:'stats',
      min_h: $('#fltMinH').val(), max_h: $('#fltMaxH').val(),
      min_l: $('#fltMinL').val(), max_l: $('#fltMaxL').val(),
      min_sqf: $('#fltMinSqf').val(), max_sqf: $('#fltMaxSqf').val(),
      finish_id: $('#fltFinish').val(), color_id: $('#fltColor').val(),
      status: $('#fltStatus').val(),
      po_no: $('#fltPoNo').val(), slab_no: $('#fltSlabNo').val(),
      branch_id: branchId, store_location_id: $('#fltStore').val()
    };
    $.get('api/finished_products.php', params, function(s){
      const n = v => Number(v||0);
      $('#kpiTotal').text(n(s.total));
      $('#kpiAvailable').text(n(s.available));
      $('#kpiReserved').text(n(s.reserved));
      $('#kpiSold').text(n(s.sold));
      $('#kpiSqFt').text(n(s.total_sq_ft).toFixed(3));
      $('#kpiSqM').text(n(s.total_sq_m).toFixed(3));
    });
  }

  function query(){
    // For non-admin users, always use their assigned branch
    const branchId = IS_ADMIN ? $('#fltBranch').val() : (USER_BRANCH_ID || $('#fltBranch').val());
    const params={ action:'list',
      min_h: $('#fltMinH').val(), max_h: $('#fltMaxH').val(),
      min_l: $('#fltMinL').val(), max_l: $('#fltMaxL').val(),
      min_sqf: $('#fltMinSqf').val(), max_sqf: $('#fltMaxSqf').val(),
      finish_id: $('#fltFinish').val(), color_id: $('#fltColor').val(),
      status: $('#fltStatus').val(),
      po_no: $('#fltPoNo').val(), slab_no: $('#fltSlabNo').val(),
      branch_id: branchId, store_location_id: $('#fltStore').val()
    };
    // Destroy DT before rebuild
    if ($.fn.DataTable && $.fn.dataTable.isDataTable('#fpList')) { $('#fpList').DataTable().destroy(); }
    $.get('api/finished_products.php', params, function(res){
      const $tb=$('#fpList tbody'); $tb.empty(); const rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="17" class="text-center text-muted">No items</td></tr>'); return; }
      rows.forEach(r=>{
        const tr=$('<tr>');
        tr.append(`<td>${$('<div>').text(r.slab_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.order_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.color_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.finish_name||'').html()}</td>`);
        tr.append(`<td>${r.pre_height??''}</td>`);
        tr.append(`<td>${r.pre_length??''}</td>`);
        tr.append(`<td>${r.pre_sq_ft??''}</td>`);
        tr.append(`<td>${r.final_height??''}</td>`);
        tr.append(`<td>${r.final_length??''}</td>`);
        tr.append(`<td>${r.final_sq_ft??''}</td>`);
        tr.append(`<td>${$('<div>').text(r.type_name||'').html()}</td>`);
        
        tr.append(`<td>${$('<div>').text(r.branch_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.store_name||'').html()}</td>`);
        const comp = r.completed_at ? new Date(r.completed_at.replace(' ','T')).toLocaleDateString() : '';
        tr.append(`<td>${$('<div>').text(comp).html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.remarks||'').html()}</td>`);
        tr.append(`<td><span class="badge bg-secondary text-capitalize">${r.sale_status||''}</span></td>`);
        const act = [];
        act.push(`<button class=\"btn btn-sm btn-outline-secondary me-1 btn-fp-view\" data-id=\"${r.id}\" title=\"View\" aria-label=\"View\"><i class=\"bi bi-eye\"></i></button>`);
        if (CAN_EDIT_FP) {
          act.push(`<button class=\"btn btn-sm btn-outline-primary me-1 btn-fp-edit\" data-id=\"${r.id}\" title=\"Edit\" aria-label=\"Edit\"><i class=\"bi bi-pencil\"></i></button>`);
          act.push(`<button class=\"btn btn-sm btn-outline-danger btn-fp-delete\" data-id=\"${r.id}\" title=\"Delete\" aria-label=\"Delete\"><i class=\"bi bi-trash\"></i></button>`);
        }
        tr.append(`<td>${act.join('')}</td>`);
        $tb.append(tr);
      });
      if ($.fn.DataTable) {
        $('#fpList').DataTable({ dom:'lfrtip', pageLength:10, lengthMenu:[[10,25,50,100,-1],[10,25,50,100,'All']], order:[], autoWidth:false, responsive:true, columnDefs:[{ orderable:false, targets:-1 }] });
        applyColumnVisibility();
      }
    }).fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText || 'Error loading finished products'); });
  }

  function queryByFinish(){
    const params={ action:'by_finish', color_id: $('#fltColor').val(), branch_id: $('#fltBranch').val(), status: $('#fltStatus').val() };
    if ($.fn.DataTable && $.fn.dataTable.isDataTable('#fpByFinish')) { $('#fpByFinish').DataTable().destroy(); }
    $.get('api/finished_products.php', params, function(res){
      const $tb=$('#fpByFinish tbody'); $tb.empty(); const rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="5" class="text-center text-muted">No data</td></tr>'); return; }
      rows.forEach(r=>{
        const tr=$('<tr>');
        tr.append(`<td>${$('<div>').text(r.finish_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.color_name||'').html()}</td>`);
        tr.append(`<td>${r.item_count??0}</td>`);
        tr.append(`<td>${Number(r.total_sq_ft||0).toFixed(3)}</td>`);
        tr.append(`<td>${Number(r.total_sq_m||0).toFixed(3)}</td>`);
        $tb.append(tr);
      });
      if ($.fn.DataTable) { $('#fpByFinish').DataTable({ dom:'lfrtip', pageLength:10, order:[], autoWidth:false, responsive:true }); }
    });
  }

  function queryByColor(){
    const params={ action:'by_color', finish_id: $('#fltFinish').val(), branch_id: $('#fltBranch').val(), status: $('#fltStatus').val() };
    if ($.fn.DataTable && $.fn.dataTable.isDataTable('#fpByColor')) { $('#fpByColor').DataTable().destroy(); }
    $.get('api/finished_products.php', params, function(res){
      const $tb=$('#fpByColor tbody'); $tb.empty(); const rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="4" class="text-center text-muted">No data</td></tr>'); return; }
      rows.forEach(r=>{
        const tr=$('<tr>');
        tr.append(`<td>${$('<div>').text(r.color_name||'').html()}</td>`);
        tr.append(`<td>${r.item_count??0}</td>`);
        tr.append(`<td>${Number(r.total_sq_ft||0).toFixed(3)}</td>`);
        tr.append(`<td>${Number(r.total_sq_m||0).toFixed(3)}</td>`);
        $tb.append(tr);
      });
      if ($.fn.DataTable) { $('#fpByColor').DataTable({ dom:'lfrtip', pageLength:10, order:[], autoWidth:false, responsive:true }); }
    });
  }

  // View details
  $(document).on('click','.btn-fp-view', function(){
    const id=$(this).data('id');
    $.get('api/finished_products.php', { action:'detail', id }, function(resp){
      const d=resp.data||{};
      const fmtDT = v=> v? new Date(String(v).replace(' ','T')).toLocaleString():'';
      $('#vd_fp_id').text(d.id||'');
      $('#vd_created').text(fmtDT(d.created_at||d.ready_at));
      $('#vd_rmp_id').text(d.rmp_internal_id||d.rmp_id||'');
      $('#vd_pj_id').text(d.polishing_job_id||'');
      $('#vd_type').text(d.type_name||'');
      $('#vd_color').text(d.color_name||'');
      $('#vd_finish').text(d.finish_name||'');
      $('#vd_quality').text(d.quality||d.raw_quality||'');
      $('#vd_status').text(d.sale_status||'');
      $('#vd_branch_store').text([d.branch_name||'', d.store_name||''].filter(Boolean).join(' / '));
      // Show invoice number for sold/reserved items
      if ((d.sale_status==='sold' || d.sale_status==='reserved') && d.invoice_no) {
        $('#vd_invoice_no').text(d.invoice_no);
        $('#vd_invoice_row').removeClass('d-none');
      } else {
        $('#vd_invoice_row').addClass('d-none');
      }

      $('#vd_slab').text(d.slab_no||'');
      $('#vd_raw_h').text(d.raw_height??'');
      $('#vd_raw_l').text(d.raw_length??'');
      $('#vd_raw_sqft').text(d.raw_sq_ft??'');
      $('#vd_raw_quality').text(d.raw_quality||'');
      $('#vd_po').text(d.order_no||'');
      // PO section
      $('#vd_po_no').text(d.order_no||'');
      $('#vd_po_date').text(d.order_date||'');
      $('#vd_supplier').text(d.supplier_name||'');
      $('#vd_ship').text(d.ship_mode||'');
      $('#vd_delivery').text(d.delivery_term||'');
      $('#vd_payment').text(d.payment_term||'');

      $('#vd_worker').text(d.worker_name||'');
      $('#vd_start').text(fmtDT(d.start_at));
      $('#vd_end').text(fmtDT(d.end_at));
      $('#vd_pre_h').text(d.pre_height??'');
      $('#vd_pre_l').text(d.pre_length??'');
      $('#vd_completed').text(fmtDT(d.completed_at));

      $('#vd_final_h').text(d.final_height??'');
      $('#vd_final_l').text(d.final_length??'');
      $('#vd_final_sqft').text(d.final_sq_ft??'');
      $('#vd_final_finish').text(d.finish_name||'');

      $('#fpViewModal').modal('show');
    }).fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||xhr.responseText||'Error loading details'));
  });

  // open edit
// open edit
$(document).on('click','.btn-fp-edit', function(){
  const id = $(this).data('id');
  $.get('api/finished_products.php', { action:'get', id }, function(res){
    const d = res.data || {};
    $('#fp_id').val(d.id);
    $('#fp_h').val(d.final_height || '');
    $('#fp_l').val(d.final_length || '');
    $('#fp_sqf').val(d.final_sq_ft || '');
    $('#fp_finish').val(d.finish_id || '');
    $('#fp_color').val(d.color_id || '');
    $('#fp_color_hidden').val(d.color_id || '');
    $('#fp_branch').val(d.branch_id || '');
    refreshEditStores(d.branch_id, d.store_location_id);
    $('#fp_quality').val(d.quality || '');
    $('#fp_remarks').val(d.remarks || '');
    $('#fp_status').val(d.sale_status || 'available');

    // Type: use existing type if present, otherwise default to Granite
    const $typeSel = $('#fp_type');
    if (d.type_id) {
      // keep saved type
      $typeSel.val(d.type_id);
    } else {
      // fallback to Granite
      const graniteOpt = $typeSel.find('option').filter(function () {
        return $(this).text().trim().toLowerCase() === 'granite';
      }).first();
      if (graniteOpt.length) {
        $typeSel.val(graniteOpt.val());
      } else {
        // if Granite option not found, leave blank
        $typeSel.val('');
      }
    }

    $('#fpEditModal').modal('show');
  });
});

  // when branch changes in edit modal, auto-filter stores and select first store of that branch
  $(document).on('change', '#fp_branch', function(){
    const bid = this.value;
    refreshEditStores(bid, null);
  });

  // (duplicate refreshEditStores removed)
  // save edit
  // Save edit (only if allowed)
  $('#fpEditForm').on('submit', function(e){ e.preventDefault(); if(!CAN_EDIT_FP){ return; } const fd=new FormData(this); fd.append('action','update');
    $.ajax({ url:'api/finished_products.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ $('#fpEditModal').modal('hide'); query(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); });
  });

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

  function refreshAll(){ refreshStats(); query(); queryByFinish(); queryByColor(); }

  $('#btnSearch').on('click', function(){ refreshAll(); });
  $('#fltMinH, #fltMaxH, #fltMinL, #fltMaxL, #fltMinSqf, #fltMaxSqf, #fltFinish, #fltColor, #fltStatus, #fltPoNo, #fltSlabNo, #fltBranch, #fltStore')
    .on('keydown', function(e){ if(e.key==='Enter'){ refreshAll(); } });

  let fpPoSuggestTimer = null;
  $('#fltPoNo').on('input', function(){
    const q = ($(this).val()||'').trim();
    clearTimeout(fpPoSuggestTimer);
    if (!q){ $('#fpPoList').empty(); return; }
    fpPoSuggestTimer = setTimeout(function(){
      $.get('api/purchase_orders.php', { action:'list', q }, function(res){
        const list = $('#fpPoList').empty();
        const rows = res.data || [];
        const seen = new Set();
        rows.forEach(r => {
          const no = r.order_no || '';
          if (!no || seen.has(no)) return;
          seen.add(no);
          list.append(`<option value="${$('<div>').text(no).html()}"></option>`);
        });
      });
    }, 250);
  });
  loadOptions(); refreshAll();

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

  $('#btnExportFPXlsx').on('click', function(){
    const dt = getDt();
    if (!dt) { alert('Table not ready'); return; }
    if (typeof XLSX === 'undefined') { alert('XLSX library not loaded'); return; }

    const prefs = loadColumnPrefs();
    const visibleCols = FP_COLUMNS.filter(c => prefs[c.key] !== false);
    const header = visibleCols.map(c => c.label);
    const rows = [];

    dt.rows({ search: 'applied' }).nodes().each(function(tr){
      const $tds = $(tr).find('td');
      const row = [];
      visibleCols.forEach(c => {
        const td = $tds.get(c.idx);
        row.push(td ? $(td).text().trim() : '');
      });
      rows.push(row);
    });

    const ws = XLSX.utils.aoa_to_sheet([header, ...rows]);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'FinishedProducts');
    XLSX.writeFile(wb, 'finished_products.xlsx');
  });
})();
</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.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
