<?php require_once __DIR__ . '/../templates/header.php'; require_once __DIR__ . '/../templates/sidebar.php'; ?>
<div id="content" class="p-3">
  <style>
    /* Professional colorful stat cards for this page */
    .stat-card { border: 0; border-radius: 10px; color: #fff; overflow: hidden; position: relative; }
    .stat-card .stat-title { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; opacity: .9; }
    .stat-card .stat-value { font-size: 26px; font-weight: 700; }
    .stat-card .icon-wrap { position:absolute; right:10px; bottom:8px; font-size: 32px; opacity: .2; }
    .stat-gradient-primary { background: linear-gradient(135deg, #1f6feb 0%, #3b82f6 100%); }
    .stat-gradient-success { background: linear-gradient(135deg, #0d9488 0%, #10b981 100%); }
    .stat-gradient-warning { background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%); }
    .stat-gradient-info { background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%); }
    .stat-gradient-purple { background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%); }
    .stat-gradient-slate { background: linear-gradient(135deg, #334155 0%, #64748b 100%); }
  </style>
  <div class="container-fluid page-import_raw_materials">

    <div class="d-flex align-items-center justify-content-between mb-3">
      <h4 class="mb-0">Raw Materials Inventory</h4>
      <div class="d-flex gap-2">
        <button id="btnCsvOpen" class="btn btn-primary"><i class="bi bi-filetype-csv me-1"></i>Upload CSV</button>
        <a id="btnDownloadTpl" href="<?php echo url_for('api/raw_material_products.php?action=template'); ?>" class="btn btn-outline-secondary" target="_blank"><i class="bi bi-download me-1"></i>Download Template</a>
        <button id="btnImportOpen" class="btn btn-outline-primary"><i class="bi bi-upload me-1"></i>Manual Import</button>
        <button id="btnRmpBulkForward" class="btn btn-outline-primary"><i class="bi bi-arrow-right-circle me-1"></i>Bulk Forward to Polishing</button>
        <button id="btnRmpBulkDel" class="btn btn-outline-danger"><i class="bi bi-trash me-1"></i>Bulk Delete Selected</button>
        <button id="btnRmpDelByPO" class="btn btn-outline-danger"><i class="bi bi-x-circle me-1"></i>Delete by PO</button>
      </div>
    </div>

<!-- Edit Slab Modal -->
<div class="modal fade" id="rmpEditModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Edit Slab</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="rmpEditForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="id" id="rmp_edit_id">
          <div class="row g-2">
            <div class="col-md-6"><label class="form-label">Slab No</label><input type="text" class="form-control" name="slab_no" id="rmp_edit_slab"></div>
            <div class="col-md-6"><label class="form-label">PO Number</label><input type="text" class="form-control" id="rmp_edit_po" readonly></div>
            <div class="col-md-6"><label class="form-label">Quality</label><input type="text" class="form-control" name="quality" id="rmp_edit_quality"></div>
            <div class="col-md-4"><label class="form-label">Height</label><input type="number" step="0.001" class="form-control" name="height" id="rmp_edit_h"></div>
            <div class="col-md-4"><label class="form-label">Length</label><input type="number" step="0.001" class="form-control" name="length" id="rmp_edit_l"></div>
            <div class="col-md-4">
              <label class="form-label">Area (auto)</label>
              <div class="input-group">
                <input type="text" class="form-control" id="rmp_edit_sqft_view" placeholder="SQ.FT" readonly>
                <span class="input-group-text">/</span>
                <input type="text" class="form-control" id="rmp_edit_sqm_view" placeholder="SQ.M" readonly>
              </div>
              <input type="hidden" name="sq_ft" id="rmp_edit_sqft">
              <input type="hidden" name="sq_m2" id="rmp_edit_sqm">
            </div>
            <div class="col-md-6"><label class="form-label">Color</label><select class="form-select" name="color_id" id="rmp_edit_color"></select></div>
            <div class="col-md-6"><label class="form-label">Price (LKR)</label><input type="number" step="0.01" class="form-control" name="price" id="rmp_edit_price"></div>
            <div class="col-md-6"><label class="form-label">Value (LKR)</label><input type="number" step="0.01" class="form-control" name="value" id="rmp_edit_value"></div>
            <div class="col-12"><label class="form-label">Length Remark</label><input type="text" class="form-control" name="length_remark" id="rmp_edit_lenrem"></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>

<!-- Bulk Forward to Polishing Modal -->
<div class="modal fade" id="rmpBulkForwardModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Bulk Forward to Polishing</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="rmpBulkForwardForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="ids_json" id="rmp_bulk_forward_ids">
          <div class="alert alert-info py-2 mb-2">
            <div class="small">Selected slabs will be forwarded using the same polisher/date/notes. Pre Height/Length are optional; if blank, each slab's current Height/Length will be used.</div>
            <div class="small fw-semibold mt-1">Selected count: <span id="rmp_bulk_forward_count">0</span></div>
          </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="rmp_bulk_forward_date"></div>
            <div class="col-md-6">
              <label class="form-label">Polisher</label>
              <select class="form-select" id="rmp_bulk_forward_emp" required></select>
              <input type="hidden" name="worker_id" id="rmp_bulk_forward_emp_id">
              <input type="hidden" name="worker_name" id="rmp_bulk_forward_emp_name">
            </div>
            <div class="col-md-6"><label class="form-label">Pre Height (optional)</label><input type="number" step="0.001" class="form-control" name="pre_height" id="rmp_bulk_forward_h"></div>
            <div class="col-md-6"><label class="form-label">Pre Length (optional)</label><input type="number" step="0.001" class="form-control" name="pre_length" id="rmp_bulk_forward_l"></div>
            <div class="col-12"><label class="form-label">Notes</label><input type="text" class="form-control" name="notes" id="rmp_bulk_forward_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">Forward Selected</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Forward to Polishing Modal -->
<div class="modal fade" id="rmpForwardModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Forward to Polishing</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="rmpForwardForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="rmp_id" id="rmp_forward_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="rmp_forward_slab" readonly>
            </div>
            <div class="col-md-6">
              <label class="form-label">PO Number</label>
              <input type="text" class="form-control" id="rmp_forward_po" readonly>
            </div>
            <div class="col-md-6"><label class="form-label">Start Date</label><input type="date" class="form-control" name="start_date" id="rmp_forward_date"></div>
            <div class="col-md-6"><label class="form-label">Pre Height</label><input type="number" step="0.001" class="form-control" name="pre_height" id="rmp_forward_h"></div>
            <div class="col-md-6"><label class="form-label">Pre Length</label><input type="number" step="0.001" class="form-control" name="pre_length" id="rmp_forward_l"></div>
            <div class="col-md-6">
              <label class="form-label">Area (auto)</label>
              <div class="input-group">
                <input type="text" class="form-control" id="rmp_forward_sqft_view" placeholder="SQ.FT" readonly>
                <span class="input-group-text">/</span>
                <input type="text" class="form-control" id="rmp_forward_sqm_view" placeholder="SQ.M" readonly>
              </div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Polisher</label>
              <select class="form-select" id="rmp_forward_emp" required></select>
              <input type="hidden" name="worker_id" id="rmp_forward_emp_id">
              <input type="hidden" name="worker_name" id="rmp_forward_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">Forward</button>
        </div>
      </form>
    </div>
  </div>
</div>
    <div class="row g-3 mb-3">
      <div class="col-12 col-md-4 col-xl-3">
        <div class="card stat-card stat-gradient-primary shadow-sm">
          <div class="card-body">
            <div class="stat-title">Total Materials</div>
            <div id="statTotal" class="stat-value">0</div>
            <div class="icon-wrap"><i class="bi bi-box-seam"></i></div>
          </div>
        </div>
      </div>
      <div class="col-12 col-md-4 col-xl-3">
        <div class="card stat-card stat-gradient-success shadow-sm">
          <div class="card-body">
            <div class="stat-title">Available</div>
            <div id="statAvailable" class="stat-value">0</div>
            <div id="statAvailableSqFt" class="small opacity-75">SQF 0.000</div>
            <div class="icon-wrap"><i class="bi bi-check2-circle"></i></div>
          </div>
        </div>
      </div>
      <div class="col-12 col-md-4 col-xl-3">
        <div class="card stat-card stat-gradient-warning shadow-sm">
          <div class="card-body">
            <div class="stat-title">In Polishing</div>
            <div id="statInPolishing" class="stat-value">0</div>
            <div id="statInPolishingSqFt" class="small opacity-75">SQF 0.000</div>
            <div class="icon-wrap"><i class="bi bi-tools"></i></div>
          </div>
        </div>
      </div>
      <div class="col-12 col-md-4 col-xl-3">
        <div class="card stat-card stat-gradient-info shadow-sm">
          <div class="card-body">
            <div class="stat-title">Finished</div>
            <div id="statFinished" class="stat-value">0</div>
            <div id="statFinishedSqFt" class="small opacity-75">SQF 0.000</div>
            <div class="icon-wrap"><i class="bi bi-flag"></i></div>
          </div>
        </div>
      </div>
      <div class="col-12 col-md-4 col-xl-3">
        <div class="card stat-card stat-gradient-purple shadow-sm">
          <div class="card-body">
            <div class="stat-title">Total Value</div>
            <div id="statTotalValue" class="stat-value">LKR 0.00</div>
            <div class="icon-wrap"><i class="bi bi-currency-exchange"></i></div>
          </div>
        </div>
      </div>
      <div class="col-12 col-md-4 col-xl-3">
        <div class="card stat-card stat-gradient-slate shadow-sm">
          <div class="card-body">
            <div class="stat-title">Total SQ.FT</div>
            <div id="statSqFt" class="stat-value">0.000</div>
            <div class="icon-wrap"><i class="bi bi-bounding-box-circles"></i></div>
          </div>
        </div>
      </div>
      <div class="col-12 col-md-4 col-xl-3">
        <div class="card stat-card stat-gradient-slate shadow-sm">
          <div class="card-body">
            <div class="stat-title">Total SQ.M</div>
            <div id="statSqM" class="stat-value">0.000</div>
            <div class="icon-wrap"><i class="bi bi-grid-3x3-gap"></i></div>
          </div>
        </div>
      </div>
    </div>

    <div class="row g-2 mb-3">
      <div class="col-12 col-md-4 position-relative">
        <label class="form-label small mb-1">Find by PO Number</label>
        <input id="rmpPoSearch" type="text" class="form-control" placeholder="Type PO number...">
        <div id="rmpPoSuggest" class="list-group position-absolute w-100" style="z-index:1050;"></div>
      </div>
      <div class="col-12 col-md-4 position-relative">
        <label class="form-label small mb-1">Find by Slab No (within selected PO)</label>
        <input id="rmpSlabSearch" type="text" class="form-control" placeholder="Type slab no...">
        <div id="rmpSlabSuggest" class="list-group position-absolute w-100" style="z-index:1050;"></div>
      </div>
      <div class="col-12 col-md-4 position-relative">
        <label class="form-label small mb-1">Find by Color</label>
        <input id="rmpColorSearch" type="text" class="form-control" placeholder="Type color name...">
        <div id="rmpColorSuggest" class="list-group position-absolute w-100" style="z-index:1050;"></div>
      </div>
      <div class="col-12 d-flex align-items-end mt-1">
        <button class="btn btn-outline-secondary me-2" id="rmpClearSearch">Clear Filters</button>
      </div>
    </div>

    <div class="row align-items-center g-2 mb-3">
      <div class="col-12 text-md-end">
        <div class="d-flex gap-2 flex-wrap justify-content-md-end align-items-center">
          <div class="btn-group" role="group">
            <button class="btn btn-outline-secondary btn-sm filter-chip" data-status="received">Received</button>
            <button class="btn btn-outline-secondary btn-sm filter-chip" data-status="in_polishing">In Polishing</button>
            <button class="btn btn-outline-secondary btn-sm filter-chip" data-status="polished">Polished</button>
            <button class="btn btn-outline-secondary btn-sm filter-chip" data-status="finished">Finished</button>
            <button class="btn btn-outline-secondary btn-sm filter-chip active" data-status="all">All</button>
          </div>
        </div>
      </div>
    </div>

    <div class="row g-2 mb-3">
      <div class="col-12 col-md-6">
        <label class="form-label small mb-1">Height (min - max)</label>
        <div class="input-group">
          <input id="hMin" type="number" step="0.001" class="form-control" placeholder="Min">
          <span class="input-group-text">-</span>
          <input id="hMax" type="number" step="0.001" class="form-control" placeholder="Max">
        </div>
      </div>
      <div class="col-12 col-md-6">
        <label class="form-label small mb-1">Length (min - max)</label>
        <div class="input-group">
          <input id="lMin" type="number" step="0.001" class="form-control" placeholder="Min">
          <span class="input-group-text">-</span>
          <input id="lMax" type="number" step="0.001" class="form-control" placeholder="Max">
        </div>
      </div>
    </div>

    <div class="card shadow-sm">
      <div class="table-responsive small">
        <table id="rmp-table" class="table table-hover table-striped table-bordered table-sm align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th style="width:34px;"><input type="checkbox" id="rmp-check-all"></th>
              <th>SLAB NO</th>
              <th>PO Number</th>
              <th>HEIGHT</th>
              <th>LENGTH</th>
              <th>SQ. FT</th>
              <th>SQ. M</th>
              <th>Quality</th>
              <th>Color</th>
              <th>Price(LKR)</th>
              <th>Value(LKR)</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>

  </div>
</div>

<!-- Import Modal -->
<div class="modal fade" id="importModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Import Raw Materials</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="importForm" enctype="multipart/form-data">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <div class="row g-3 mb-2">
            <div class="col-md-3">
              <label class="form-label">Import Date</label>
              <input type="date" class="form-control" name="import_date" id="impDate" required>
            </div>
            <div class="col-md-5">
              <label class="form-label">Purchase Order (Received)</label>
              <select class="form-select" name="po_id" id="impPO" required></select>
            </div>
            <div class="col-md-4">
              <label class="form-label">Product Type</label>
              <select class="form-select" name="product_type_id" id="impType"></select>
            </div>
            <div class="col-md-4">
              <label class="form-label">Reference No</label>
              <input type="text" class="form-control" name="reference_no" id="impRef">
            </div>
            <div class="col-md-4">
              <label class="form-label">Transporter</label>
              <input type="text" class="form-control" name="transporter" id="impTransporter">
            </div>
            <div class="col-md-4">
              <label class="form-label">Vehicle No</label>
              <input type="text" class="form-control" name="vehicle_no" id="impVehicle">
            </div>
            <div class="col-md-4">
              <label class="form-label">Warehouse</label>
              <input type="text" class="form-control" name="warehouse" id="impWarehouse">
            </div>
            <div class="col-12">
              <label class="form-label">Notes</label>
              <input type="text" class="form-control" name="notes" id="impNotes">
            </div>
            <div class="col-12">
              <label class="form-label">Attachment</label>
              <input type="file" class="form-control" name="attachment" id="impAttachment" accept="image/*,application/pdf">
            </div>
          </div>

          <div class="table-responsive border rounded">
            <table class="table table-sm mb-0" id="impItemsTable">
              <thead class="table-light">
                <tr>
                  <th style="width: 42px;">#</th>
                  <th>Description</th>
                  <th class="text-end">Ordered Qty</th>
                  <th class="text-end">Qty Receive</th>
                  <th>Batch No</th>
                  <th>Remarks</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </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 Import</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- CSV Upload Modal -->
<div class="modal fade" id="csvModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Upload Supplier CSV (Per PO)</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="csvForm" enctype="multipart/form-data">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <div class="mb-3">
            <label class="form-label">Purchase Order (Received)</label>
            <select class="form-select" name="po_id" id="csvPO" required></select>
          </div>
          <div class="mb-3">
            <label class="form-label">Product Color</label>
            <select class="form-select" name="color_id" id="csvColor"></select>
          </div>
          <div class="mb-2">
            <label class="form-label">CSV File</label>
            <input type="file" class="form-control" name="csv" id="csvFile" accept=".csv" required>
          </div>
          <div class="small text-muted">Columns accepted: SL. NO, SLAB N, HEIGHT, LENGTH, SQ. FT, SQ.M2, Quality, Price, Value, length Rem</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">Upload</button>
        </div>
      </form>
    </div>
  </div>
  </div>

<!-- <?php require_once __DIR__ . '/../templates/footer.php'; ?> -->
<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>
(function(){
  const $rmpTable = $('#rmp-table tbody');
  const $po = $('#impPO');
  const $itemsTbody = $('#impItemsTable tbody');
  const $csvPO = $('#csvPO');
  const $csvColor = $('#csvColor');
  const $impType = $('#impType');
  const $editType = $('#rmp_edit_type');
  const $editColor = $('#rmp_edit_color');
  const $hMin = $('#hMin'), $hMax = $('#hMax'), $lMin=$('#lMin'), $lMax=$('#lMax');
  const $poSearch = $('#rmpPoSearch');
  const $poSuggest = $('#rmpPoSuggest');
  const $slabSearch = $('#rmpSlabSearch');
  const $slabSuggest = $('#rmpSlabSuggest');
  const $colorSearch = $('#rmpColorSearch');
  const $colorSuggest = $('#rmpColorSuggest');
  // guards to prevent duplicate prompts/requests
  let rmpBulkDeleting = false;
  let rmpPoDeleting = false;
  let currentPoId = null;
  let currentSlabTerm = '';
  let currentColorTerm = '';
  let currentPoRows = [];
  let poSearchTimer = null;
  let slabSearchTimer = null;
  let colorSearchTimer = null;

  function formatCurrency(n){ try{ n=parseFloat(n||0); }catch(e){ n=0; } return n.toLocaleString('en-LK',{ minimumFractionDigits: 2, maximumFractionDigits: 2 }); }

  function loadReceivedPOs(){
    if ($po.length) { $po.empty().append('<option value="">Loading...</option>'); }
    if ($csvPO.length) { $csvPO.empty().append('<option value="">Loading...</option>'); }
    $.get('api/purchase_orders.php', { action:'list', status:'received' }, function(res){
      const opts = ['<option value="">Select a Received PO</option>'];
      (res.data||[]).forEach(p=>{ opts.push(`<option value="${p.id}">${p.order_no} - ${p.supplier_name||''}</option>`); });
      if ($po.length) { $po.html(opts.join('')); }
      if ($csvPO.length) { $csvPO.html(opts.join('')); }

      // Load colors for CSV modal
      if ($csvColor.length) {
        $csvColor.html('<option value="">Loading colors...</option>');
        $.get('api/colors.php', { action:'list' }, function(res2){
          const rows = res2.data || [];
          const cOpts = ['<option value="">-- Select Color (optional) --</option>'];
          rows.forEach(c=> cOpts.push(`<option value="${c.id}">${$('<div>').text(c.name).html()}</option>`));
          $csvColor.html(cOpts.join(''));
        });
      }
    });
  }

  // Auto-calc SQ.FT and SQ.M from Height/Length on edit modal (inputs are INCHES)
  function recalcEditArea(){
    const hIn = parseFloat($('#rmp_edit_h').val()||'0');
    const lIn = parseFloat($('#rmp_edit_l').val()||'0');
    // convert inches to feet
    const hFt = (isNaN(hIn)?0:hIn) / 12.0;
    const lFt = (isNaN(lIn)?0:lIn) / 12.0;
    const sqft = (hFt * lFt) || 0;
    const sqm = sqft * 0.092903;
    $('#rmp_edit_sqft').val(sqft.toFixed(3));
    $('#rmp_edit_sqm').val(sqm.toFixed(3));
    $('#rmp_edit_sqft_view').val(sqft.toFixed(3));
    $('#rmp_edit_sqm_view').val(sqm.toFixed(3));
  }
  $('#rmp_edit_h, #rmp_edit_l').on('input', recalcEditArea);
    // Load product types into all relevant selects (filter, import modals, edit/forward modals)
    $.get('api/types.php', { action:'list' }, function(res){
      const rows = res.data || [];
      if ($impType.length) {
        const optI = ['<option value="">-- Select Type (optional) --</option>'];
        rows.forEach(t=> optI.push(`<option value="${t.id}">${$('<div>').text(t.name).html()}</option>`));
        $impType.html(optI.join(''));
      }
      // CSV modal uses colors; options are loaded in loadReceivedPOs()
      if ($editType.length) {
        const curE = $editType.val() || '';
        const optE = ['<option value="">-- Select Type (optional) --</option>'];
        rows.forEach(t=> optE.push(`<option value="${t.id}">${$('<div>').text(t.name).html()}</option>`));
        $editType.html(optE.join('')); if (curE) $editType.val(curE);
      }
    });

  // Edit slab
  $(document).on('click', '.btn-rmp-edit', function(){
    const id=$(this).data('id');
    $.get('api/raw_material_products.php', { action:'get', id }, function(res){
      const d=res.data||{}; $('#rmp_edit_id').val(d.id);
      $('#rmp_edit_slab').val(d.slab_no||'');
      // Load PO number into readonly field
      $('#rmp_edit_po').val('');
      if (d.po_id) {
        $.get('api/purchase_orders.php', { action:'get', id: d.po_id }, function(poRes){
          const po = poRes.data || {};
          $('#rmp_edit_po').val(po.order_no || '');
        });
      }
      $('#rmp_edit_quality').val(d.quality||'');
      $('#rmp_edit_h').val(d.height||'');
      $('#rmp_edit_l').val(d.length||'');
      $('#rmp_edit_sqft').val(d.sq_ft||'');
      $('#rmp_edit_sqm').val(d.sq_m2||'');
      $('#rmp_edit_sqft_view').val((Number(d.sq_ft||0)).toFixed(3));
      $('#rmp_edit_sqm_view').val((Number(d.sq_m2||0)).toFixed(3));
      $('#rmp_edit_price').val(d.price||'');
      $('#rmp_edit_value').val(d.value||'');
      $('#rmp_edit_lenrem').val(d.length_remark||'');
      if ($editColor.length) {
        const setColor = ()=> { $editColor.val(d.color_id || ''); };
        if ($editColor.find('option').length === 0) {
          $.get('api/colors.php', { action:'list' }, function(res2){
            const rows = res2.data || [];
            const opt = ['<option value="">-- Select Color (optional) --</option>'];
            rows.forEach(c=> opt.push(`<option value="${c.id}">${$('<div>').text(c.name).html()}</option>`));
            $editColor.html(opt.join(''));
            setColor();
          });
        } else { setColor(); }
      }
      $('#rmpEditModal').modal('show');
    });
  });
  $('#rmpEditForm').on('submit', function(e){
    e.preventDefault(); const fd=new FormData(this); fd.append('action','update');
    $.ajax({ url:'api/raw_material_products.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ $('#rmpEditModal').modal('hide'); fetchRmp(); fetchStats(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); });
  });

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

  // Persist selection across DataTables pagination
  const rmpSelectedIds = new Set();
  function rmpSelectedArray(){ return Array.from(rmpSelectedIds); }
  function syncRmpCheckboxesFromSet(){
    $('.rmp-chk').each(function(){
      const id = Number($(this).data('id'));
      $(this).prop('checked', rmpSelectedIds.has(id));
    });
    syncRmpCheckAllState();
  }
  function syncRmpCheckAllState(){
    const $boxes = $('.rmp-chk');
    if (!$boxes.length) { $('#rmp-check-all').prop('checked', false); return; }
    const allChecked = $boxes.filter(':checked').length === $boxes.length;
    $('#rmp-check-all').prop('checked', allChecked);
  }

  $(document).on('change', '.rmp-chk', function(){
    const id = Number($(this).data('id'));
    if (this.checked) rmpSelectedIds.add(id);
    else rmpSelectedIds.delete(id);
    syncRmpCheckAllState();
  });
  $('#rmp-check-all').off('change').on('change', function(){
    const c = this.checked;
    $('.rmp-chk').each(function(){
      const id = Number($(this).data('id'));
      $(this).prop('checked', c);
      if (c) rmpSelectedIds.add(id);
      else rmpSelectedIds.delete(id);
    });
    syncRmpCheckAllState();
  });

  $('#btnRmpBulkDel').off('click').on('click', function(){
    if (rmpBulkDeleting) return;
    const ids = rmpSelectedArray();
    if (!ids.length) { alert('No rows selected'); return; }
    if (!confirm('Delete selected slabs?')) return;
    rmpBulkDeleting = true;
    const $btn = $(this).prop('disabled', true).addClass('disabled');
    const fd=new FormData(); fd.append('csrf','<?php echo htmlspecialchars(csrf_token()); ?>'); fd.append('action','bulk_delete'); fd.append('ids_json', JSON.stringify(ids));
    $.ajax({ url:'api/raw_material_products.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ rmpSelectedIds.clear(); $('#rmp-check-all').prop('checked', false); fetchRmp(); fetchStats(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); })
      .always(function(){ rmpBulkDeleting = false; $btn.prop('disabled', false).removeClass('disabled'); });
  });
  $('#btnRmpDelByPO').off('click').on('click', function(){
    if (rmpPoDeleting) return;
    const po_no = prompt('Enter PO Number to delete all its slabs:'); if (!po_no) return;
    if (!confirm('Delete all slabs under PO '+po_no+'?')) return;
    rmpPoDeleting = true;
    const $btn = $(this).prop('disabled', true).addClass('disabled');
    const fd=new FormData(); fd.append('csrf','<?php echo htmlspecialchars(csrf_token()); ?>'); fd.append('action','delete_by_po'); fd.append('po_no', po_no);
    $.ajax({ url:'api/raw_material_products.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ $('#rmp-check-all').prop('checked', false); fetchRmp(); fetchStats(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); })
      .always(function(){ rmpPoDeleting = false; $btn.prop('disabled', false).removeClass('disabled'); });
  });

  // Forward to polishing
  function loadEmployeesInto(sel){ $.get('api/employees.php', { action:'list' }, function(res){ const opts=['<option value="">Select employee</option>']; (res.data||[]).filter(e=>e.is_active==1).forEach(e=>opts.push(`<option value="${e.id}" data-name="${$('<div>').text(e.full_name).html()}">${$('<div>').text(e.full_name).html()}</option>`)); $(sel).html(opts.join('')); }); }
  function loadPolishersInto(sel){
    $.get('api/employees.php', { action:'list' }, function(res){
      const opts=['<option value="">Select polisher</option>'];
      (res.data||[])
        .filter(e=>{
          if (!(e && (e.is_active==1 || String(e.is_active)==='1'))) return false;
          const did = e.designation_id;
          return (did===2 || String(did)==='2');
        })
        .forEach(e=>opts.push(`<option value="${e.id}" data-name="${$('<div>').text(e.full_name).html()}">${$('<div>').text(e.full_name).html()}</option>`));
      $(sel).html(opts.join(''));
    });
  }
  $('#rmp_forward_emp').on('change', function(){ const id=this.value; const name=$(this).find('option:selected').data('name')||''; $('#rmp_forward_emp_id').val(id||''); $('#rmp_forward_emp_name').val(name); });
  $('#rmp_bulk_forward_emp').on('change', function(){ const id=this.value; const name=$(this).find('option:selected').data('name')||''; $('#rmp_bulk_forward_emp_id').val(id||''); $('#rmp_bulk_forward_emp_name').val(name); });

  // Bulk forward to polishing
  let rmpBulkForwarding = false;
  $('#btnRmpBulkForward').off('click').on('click', function(){
    const ids = rmpSelectedArray();
    if (!ids.length) { alert('No rows selected'); return; }
    $('#rmpBulkForwardForm')[0].reset();
    $('#rmp_bulk_forward_ids').val(JSON.stringify(ids));
    $('#rmp_bulk_forward_count').text(ids.length);
    loadPolishersInto('#rmp_bulk_forward_emp');
    const today = new Date().toISOString().slice(0,10);
    $('#rmp_bulk_forward_date').val(today);
    $('#rmpBulkForwardModal').modal('show');
  });
  $('#rmpBulkForwardForm').on('submit', function(e){
    e.preventDefault();
    if (rmpBulkForwarding) return;
    if (!$('#rmp_bulk_forward_emp_id').val()) { alert('Please select a polisher'); return; }
    const idsRaw = $('#rmp_bulk_forward_ids').val() || '[]';
    let ids = [];
    try { ids = JSON.parse(idsRaw) || []; } catch(e) { ids = []; }
    if (!ids.length) { alert('No rows selected'); return; }
    if (!confirm('Forward selected slabs to polishing?')) return;

    rmpBulkForwarding = true;
    const $btn = $('#rmpBulkForwardForm button[type="submit"]').prop('disabled', true).text('Forwarding...');
    const fd = new FormData(this);
    fd.append('action', 'bulk_start');
    $.ajax({ url:'api/polishing.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(resp){
        const ok = resp && resp.ok ? resp.ok : 0;
        const fail = resp && resp.fail ? resp.fail : 0;
        if (fail) {
          const sample = (resp.failed_ids||[]).slice(0, 10).join(', ');
          alert('Bulk forward completed. Success: '+ok+' Failed: '+fail + (sample ? ('\nFailed IDs: '+sample) : ''));
        } else {
          alert('Bulk forward completed. Success: '+ok);
        }
        $('#rmpBulkForwardModal').modal('hide');
        rmpSelectedIds.clear();
        $('#rmp-check-all').prop('checked', false);
        fetchRmp(); fetchStats();
      })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || xhr.responseText || 'Error'); })
      .always(function(){ rmpBulkForwarding = false; $btn.prop('disabled', false).text('Forward Selected'); });
  });

  // Auto-calc forward area (inputs in inches)
  function recalcForwardArea(){
    const hIn = parseFloat($('#rmp_forward_h').val()||'0');
    const lIn = parseFloat($('#rmp_forward_l').val()||'0');
    const hFt = (isNaN(hIn)?0:hIn)/12.0;
    const lFt = (isNaN(lIn)?0:lIn)/12.0;
    const sqft = (hFt*lFt) || 0;
    const sqm = sqft * 0.092903;
    $('#rmp_forward_sqft_view').val(sqft.toFixed(3));
    $('#rmp_forward_sqm_view').val(sqm.toFixed(3));
  }
  $('#rmp_forward_h, #rmp_forward_l').on('input', recalcForwardArea);
  $(document).on('click', '.btn-rmp-forward', function(){
    const id=$(this).data('id');
    $('#rmpForwardForm')[0].reset();
    $('#rmp_forward_id').val(id);
    // Prefill sizes
    $.get('api/raw_material_products.php', { action:'get', id }, function(res){
      const d=res.data||{};
      $('#rmp_forward_slab').val(d.slab_no||'');
      $('#rmp_forward_h').val(d.height||'');
      $('#rmp_forward_l').val(d.length||'');
      // Load PO number
      $('#rmp_forward_po').val('');
      if (d.po_id) {
        $.get('api/purchase_orders.php', { action:'get', id: d.po_id }, function(poRes){
          const po = poRes.data || {};
          $('#rmp_forward_po').val(po.order_no || '');
        });
      }
      recalcForwardArea();
    });
    loadPolishersInto('#rmp_forward_emp');
    // set today date
    const today = new Date().toISOString().slice(0,10);
    $('#rmp_forward_date').val(today);
    $('#rmpForwardModal').modal('show');
  });
  $('#rmpForwardForm').on('submit', function(e){
    e.preventDefault();
    const $form = $(this);
    const $btn = $('#rmpForwardForm button[type="submit"]');
    if ($form.data('submitting')) { return; }
    if (!$('#rmp_forward_emp_id').val()) { alert('Please select a polisher'); return; }
    // Disable button immediately to prevent double-click
    $btn.prop('disabled', true).text('Forwarding...');
    $form.data('submitting', true);
    const fd=new FormData(this); fd.append('action','start');
    $.ajax({ url:'api/polishing.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ $('#rmpForwardModal').modal('hide'); fetchRmp(); fetchStats(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); })
      .always(function(){ $form.data('submitting', false); $btn.prop('disabled', false).text('Forward'); });
  });


  function fetchStats(){
    const status = ($('.filter-chip.active').data('status')||'all');
    const statParams = { action:'stats' };
    if (status && status !== 'all') statParams.status = status;
    // Include PO filter and other filters to match table data
    if (currentPoId) statParams.po_id = currentPoId;
    if (currentSlabTerm) statParams.slab_q = currentSlabTerm;
    if (currentColorTerm) statParams.color_q = currentColorTerm;
    const hvMin = $hMin.val(); const hvMax = $hMax.val();
    const lvMin = $lMin.val(); const lvMax = $lMax.val();
    if (hvMin !== '') statParams.h_min = hvMin;
    if (hvMax !== '') statParams.h_max = hvMax;
    if (lvMin !== '') statParams.l_min = lvMin;
    if (lvMax !== '') statParams.l_max = lvMax;
    $.get('api/raw_material_products.php', statParams, function(s){
      $('#statTotal').text(s.total ?? 0);
      $('#statAvailable').text(s.available ?? 0);
      $('#statInPolishing').text(s.in_polishing ?? 0);
      $('#statFinished').text(s.finished ?? 0);
      $('#statTotalValue').text((s.total_value||0).toLocaleString('en-LK',{style:'currency',currency:'LKR'}));
      $('#statSqFt').text((s.total_sq_ft||0).toFixed(3));
      $('#statSqM').text((s.total_sq_m2||0).toFixed(3));
      $('#statAvailableSqFt').text('SQF ' + (s.received_sq_ft||0).toFixed(3));
      $('#statInPolishingSqFt').text('SQF ' + (s.in_polishing_sq_ft||0).toFixed(3));
      $('#statFinishedSqFt').text('SQF ' + (s.finished_sq_ft||0).toFixed(3));
    });
  }

  function loadPOItems(poId){
    $itemsTbody.empty(); if(!poId) return;
    $.get('api/purchase_orders.php', { action:'get', id: poId }, function(res){
      const items = (res.data && res.data.items) ? res.data.items : [];
      if(!items.length){ $itemsTbody.append('<tr><td colspan="6" class="text-center text-muted">No items in this PO</td></tr>'); return; }
      items.forEach((it, idx)=>{
        const row = $(
          `<tr data-po-item-id="${it.id}">
            <td>${idx+1}</td>
            <td>${$('<div>').text(it.description||'').html()}</td>
            <td class="text-end">${(it.quantity||0)}</td>
            <td class="text-end" style="width:140px;"><input type="number" step="0.001" min="0" class="form-control form-control-sm qty-recv" value="0"></td>
            <td style="width:160px;"><input type="text" class="form-control form-control-sm batch-no" placeholder="Batch"></td>
            <td style="width:220px;"><input type="text" class="form-control form-control-sm remarks" placeholder="Remarks"></td>
          </tr>`);
        $itemsTbody.append(row);
      });
    });
  }

  function fetchRmp(){
    const status = ($('.filter-chip.active').data('status')||'all');
    const params = { action:'list' };
    if (status && status!=='all') params.status=status;
    if (currentPoId) params.po_id = currentPoId;
    if (currentSlabTerm) params.slab_q = currentSlabTerm;
    if (currentColorTerm) params.color_q = currentColorTerm;
    const hvMin = $hMin.val(); const hvMax = $hMax.val();
    const lvMin = $lMin.val(); const lvMax = $lMax.val();
    if (hvMin !== '') params.h_min = hvMin;
    if (hvMax !== '') params.h_max = hvMax;
    if (lvMin !== '') params.l_min = lvMin;
    if (lvMax !== '') params.l_max = lvMax;
    $.get('api/raw_material_products.php', params, function(res){
      // Destroy DT before rebuilding rows to avoid residual state
      if ($.fn.DataTable && $.fn.dataTable.isDataTable('#rmp-table')) { $('#rmp-table').DataTable().destroy(); }
      $rmpTable.empty();
      const rawRows = res.data||[];
      currentPoRows = rawRows;
      const rows = rawRows;
      if(!rows.length){
        $rmpTable.append('<tr><td colspan="13" class="text-center text-muted">No products</td></tr>');
        // keep rmpSelectedIds as-is so selection persists across filter changes
        $('#rmp-check-all').prop('checked', false);
        return;
      }
      rows.forEach(r=>{
        const tr = $('<tr>');
        tr.append(`<td><input type="checkbox" class="rmp-chk" data-id="${r.id}"></td>`);
        tr.append(`<td>${$('<div>').text(r.slab_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.order_no||'').html()}</td>`);
        tr.append(`<td>${r.height??''}</td>`);
        tr.append(`<td>${r.length??''}</td>`);
        tr.append(`<td>${r.sq_ft??''}</td>`);
        tr.append(`<td>${r.sq_m2??r.sq_m??r.sg_m2??''}</td>`);
        tr.append(`<td>${$('<div>').text(r.quality||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.color_name||'').html()}</td>`);
        tr.append(`<td>${r.price!=null?formatCurrency(r.price):''}</td>`);
        tr.append(`<td>${r.value!=null?formatCurrency(r.value):''}</td>`);
        const badge = r.status?`<span class="badge bg-secondary text-capitalize">${r.status.replace('_',' ')}</span>`:'';
        tr.append(`<td>${badge}</td>`);
        const editBtn = `<button class="btn btn-sm btn-outline-secondary me-1 btn-rmp-edit" data-id="${r.id}"><i class="bi bi-pencil"></i></button>`;
        const delBtn = `<button class="btn btn-sm btn-outline-danger me-1 btn-rmp-del" data-id="${r.id}"><i class="bi bi-trash"></i></button>`;
        const fwdBtn = (r.status==='received') ? `<button class="btn btn-sm btn-outline-primary me-1 btn-rmp-forward" data-id="${r.id}" title="Polishing"><i class="bi bi-arrow-right"></i></button>` : '';
        tr.append(`<td>${editBtn}${delBtn}${fwdBtn}</td>`);
        $rmpTable.append(tr);
      });
      // Re-init DataTable after rows are rendered
      if ($.fn.DataTable) {
        const existing = $.fn.dataTable.isDataTable('#rmp-table');
        if (existing) { $('#rmp-table').DataTable().destroy(); }
        const dt = $('#rmp-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 } ]
        });
        // Restore selection on pagination/sort/search redraws
        dt.on('draw', function(){ syncRmpCheckboxesFromSet(); });
      }
      syncRmpCheckboxesFromSet();
    });
  }

  function openModal(){
    const d = new Date();
    $('#impDate').val(d.toISOString().slice(0,10));
    $('#importForm')[0].reset();
    loadReceivedPOs();
    $('#importModal').modal('show');
  }

  $('#btnImportOpen').on('click', openModal);
  $('#btnCsvOpen').on('click', function(){ loadReceivedPOs(); $('#csvForm')[0].reset(); $('#csvModal').modal('show'); });
  // Status chip filter
  $(document).on('click', '.filter-chip', function(){
    $('.filter-chip').removeClass('active');
    $(this).addClass('active');
    fetchRmp(); fetchStats();
  });
  // Re-fetch on input/change with debounce so numeric filters work smoothly
  let dimTimer=null;
  $hMin.add($hMax).add($lMin).add($lMax).on('input change keypress', function(e){
    if(e.type==='keypress' && e.which!==13) return; // allow enter to trigger immediately
    clearTimeout(dimTimer);
    dimTimer = setTimeout(function(){ fetchRmp(); fetchStats(); }, 250);
  });
  $po.on('change', function(){ loadPOItems(this.value); });

  // ---------------- PO / Slab / Color quick find ----------------
  function hideList($el){ $el.empty().hide(); }

  function renderSuggest($wrap, itemsHtml){
    if (!itemsHtml || !itemsHtml.length){ hideList($wrap); return; }
    $wrap.html(itemsHtml.join('')).show();
  }

  // PO suggestions (received POs)
  function doPoSuggest(){
    const term = ($poSearch.val() || '').trim();
    hideList($poSuggest);
    if (!term){ currentPoId = null; fetchRmp(); return; }
    $.get('api/purchase_orders.php', { action:'list', status:'received', q: term }, function(res){
      const rows = res.data || [];
      const html = rows.slice(0, 8).map(p => {
        const label = `${p.order_no} - ${(p.supplier_name||'')}`;
        const safe = $('<div>').text(label).html();
        return `<button type="button" class="list-group-item list-group-item-action rmp-po-opt" data-id="${p.id}" data-label="${safe}">${safe}</button>`;
      });
      renderSuggest($poSuggest, html);
    });
  }

  $poSearch.on('input', function(){
    if (poSearchTimer) clearTimeout(poSearchTimer);
    poSearchTimer = setTimeout(doPoSuggest, 200);
  });

  $poSuggest.on('click', '.rmp-po-opt', function(){
    const id = $(this).data('id');
    const label = $(this).data('label') || '';
    currentPoId = id || null;
    $poSearch.val(label);
    hideList($poSuggest);
    // Reset slab/color when PO changes
    currentSlabTerm = '';
    currentColorTerm = '';
    $slabSearch.val('');
    $colorSearch.val('');
    hideList($slabSuggest);
    hideList($colorSuggest);
    fetchRmp();
  });

  // Slab suggestions (from currently loaded rows)
  function doSlabSuggest(){
    const term = ($slabSearch.val() || '').trim();
    currentSlabTerm = term;
    hideList($slabSuggest);
    if (!term){ fetchRmp(); return; }
    const lower = term.toLowerCase();
    const seen = {};
    const html = [];
    (currentPoRows||[]).forEach(r => {
      const s = String(r.slab_no||'').trim();
      if (!s) return;
      if (!s.toLowerCase().includes(lower)) return;
      const k = s.toLowerCase();
      if (seen[k]) return;
      seen[k] = true;
      const safe = $('<div>').text(s).html();
      html.push(`<button type="button" class="list-group-item list-group-item-action rmp-slab-opt" data-slab="${safe}">${safe}</button>`);
    });
    renderSuggest($slabSuggest, html.slice(0, 10));
    fetchRmp();
  }

  $slabSearch.on('input', function(){
    if (slabSearchTimer) clearTimeout(slabSearchTimer);
    slabSearchTimer = setTimeout(doSlabSuggest, 150);
  });

  $slabSuggest.on('click', '.rmp-slab-opt', function(){
    const slab = $(this).data('slab') || '';
    currentSlabTerm = slab;
    $slabSearch.val(slab);
    hideList($slabSuggest);
    fetchRmp();
  });

  // Color suggestions (from currently loaded rows)
  function doColorSuggest(){
    const term = ($colorSearch.val() || '').trim();
    currentColorTerm = term;
    hideList($colorSuggest);
    if (!term){ fetchRmp(); return; }
    const lower = term.toLowerCase();
    const seen = {};
    const html = [];
    (currentPoRows||[]).forEach(r => {
      const c = String(r.color_name||'').trim();
      if (!c) return;
      if (!c.toLowerCase().includes(lower)) return;
      const k = c.toLowerCase();
      if (seen[k]) return;
      seen[k] = true;
      const safe = $('<div>').text(c).html();
      html.push(`<button type="button" class="list-group-item list-group-item-action rmp-color-opt" data-color="${safe}">${safe}</button>`);
    });
    renderSuggest($colorSuggest, html.slice(0, 10));
    fetchRmp();
  }

  $colorSearch.on('input', function(){
    if (colorSearchTimer) clearTimeout(colorSearchTimer);
    colorSearchTimer = setTimeout(doColorSuggest, 150);
  });

  $colorSuggest.on('click', '.rmp-color-opt', function(){
    const c = $(this).data('color') || '';
    currentColorTerm = c;
    $colorSearch.val(c);
    hideList($colorSuggest);
    fetchRmp();
  });

  // Click outside closes suggestions
  $(document).on('click', function(e){
    if (!$(e.target).closest('#rmpPoSearch, #rmpPoSuggest').length) hideList($poSuggest);
    if (!$(e.target).closest('#rmpSlabSearch, #rmpSlabSuggest').length) hideList($slabSuggest);
    if (!$(e.target).closest('#rmpColorSearch, #rmpColorSuggest').length) hideList($colorSuggest);
  });

  $('#rmpClearSearch').on('click', function(){
    currentPoId = null;
    currentSlabTerm = '';
    currentColorTerm = '';
    $poSearch.val('');
    $slabSearch.val('');
    $colorSearch.val('');
    hideList($poSuggest);
    hideList($slabSuggest);
    hideList($colorSuggest);
    fetchRmp();
  });

  // Initial load: default to Received
  $('.filter-chip').removeClass('active');
  $('.filter-chip[data-status="all"]').addClass('active');
  fetchRmp(); fetchStats();

  $('#importForm').on('submit', function(e){
    e.preventDefault();
    const po_id = $po.val(); if(!po_id){ alert('Please select a PO'); return; }
    const items=[]; $('#impItemsTable tbody tr').each(function(){
      const $tr=$(this); const po_item_id=$tr.data('po-item-id');
      const qty=parseFloat($tr.find('.qty-recv').val()||0);
      const batch=$tr.find('.batch-no').val();
      const remarks=$tr.find('.remarks').val();
      if(po_item_id && qty>0){ items.push({ po_item_id, qty_received: qty, batch_no: batch, remarks }); }
    });
    if(items.length===0){ if(!confirm('No positive quantities entered. Continue?')) return; }
    const fd=new FormData(this);
    fd.append('action','create');
    fd.append('items_json', JSON.stringify(items));
    $.ajax({ url:'api/import_raw_materials.php', method:'POST', data: fd, contentType:false, processData:false })
      .done(function(){ $('#importModal').modal('hide'); fetchRmp(); fetchStats(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error'); });
  });

  $('#csvForm').on('submit', function(e){
    e.preventDefault();
    const fd=new FormData(this); fd.append('action','upload_csv');
    $.ajax({ url:'api/raw_material_products.php', method:'POST', data: fd, contentType:false, processData:false })
      .done(function(){ $('#csvModal').modal('hide'); fetchRmp(); fetchStats(); })
      .fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Upload failed'); });
  });

  // init
  fetchRmp();
  loadReceivedPOs();
  fetchStats();
})();
</script>
