<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-stock-detail-report">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="mb-0">Stock Detail Report</h4>
      <div>
        <button id="stk_back" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-left"></i> Back to Summary</button>
        <button id="stk_export" class="btn btn-sm btn-outline-success"><i class="bi bi-file-earmark-excel"></i> Export XLSX</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-2"><label class="form-label">Category</label><select id="stk_category" class="form-select form-select-sm"><option value="">All</option><option value="Raw Material">Raw Material</option><option value="Finished Product">Finished Product</option><option value="Cut Piece">Cut Piece</option></select></div>
        <div class="col-md-2"><label class="form-label">Finish</label><select id="stk_finish" class="form-select form-select-sm"><option value="">All</option></select></div>
        <div class="col-md-2"><label class="form-label">Color</label><select id="stk_color" class="form-select form-select-sm"><option value="">All</option></select></div>
        <div class="col-md-3"><label class="form-label">Supplier</label><select id="stk_supplier" class="form-select form-select-sm"><option value="">All</option></select></div>
        <div class="col-md-3"><label class="form-label">PO Number</label><select id="stk_po" class="form-select form-select-sm"><option value="">All</option></select></div>
        <?php if (has_role(['admin','super_admin'])): ?>
        <div class="col-md-2"><label class="form-label">Branch</label><select id="stk_branch" class="form-select form-select-sm"><option value="">All</option></select></div>
        <?php endif; ?>
        <div class="col-md-2"><button id="stk_run" class="btn btn-sm btn-primary w-100">Run</button></div>
      </div>
    </div></div>

    <div class="table-responsive">
      <table class="table table-sm table-hover" id="stk_table">
        <thead>
          <tr>
            <th>Category</th>
            <th>ID</th>
            <th>Slab No</th>
            <th>PO Number</th>
            <th>Color</th>
            <th>Finish</th>
            <th class="text-end">Height</th>
            <th class="text-end">Length</th>
            <th class="text-end">Sq.Ft</th>
            <th>Quality</th>
            <th>Branch</th>
            <th>Store</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
  </div>
</div>

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

  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 headerCells = Array.from(thead.querySelectorAll('th'));
    const headers = headerCells.map(th => (th.innerText || '').trim());
    const rows = Array.from(tbody.querySelectorAll('tr'))
      .filter(tr => tr.querySelectorAll('td').length)
      .map(tr => Array.from(tr.querySelectorAll('td')).map(td => (td.innerText || '').trim()));

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

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

  function fillSelect($sel, items){
    $sel.empty();
    $sel.append('<option value="">All</option>');
    (items||[]).forEach(x=>{
      $sel.append(`<option value="${x.id}">${$('<div>').text(x.name||'').html()}</option>`);
    });
  }

  let allPOs = [];

  function loadLookups(callback){
    $.when(
      $.get('api/finishes.php', { action:'list' }, function(res){ fillSelect($('#stk_finish'), res.data||[]); }),
      $.get('api/colors.php', { action:'list' }, function(res){ fillSelect($('#stk_color'), res.data||[]); }),
      $.get('api/suppliers.php', { action:'list' }, function(res){
        const $sup=$('#stk_supplier');
        $sup.empty();
        $sup.append('<option value="">All</option>');
        (res.data||[]).forEach(s=> $sup.append(`<option value="${$('<div>').text(s.name||'').html()}">${$('<div>').text(s.name||'').html()}</option>`));
      }),
      $.get('api/purchase_orders.php', { action:'list' }, function(res){
        allPOs = res.data || [];
        updatePODropdown();
      })
      <?php if (has_role(['admin','super_admin'])): ?>
      ,
      $.get('api/branches.php',{ action:'list' }, function(res){
        const $b=$('#stk_branch');
        $b.empty();
        $b.append('<option value="">All</option>');
        (res.data||[]).forEach(b=> $b.append(`<option value="${b.id}">${$('<div>').text(b.name).html()}</option>`));
      })
      <?php endif; ?>
    ).done(function(){
      if (callback && typeof callback === 'function') callback();
    });
  }

  function updatePODropdown(){
    const selectedSupplier = $('#stk_supplier').val();
    const $po = $('#stk_po');
    const currentVal = $po.val();
    $po.empty();
    $po.append('<option value="">All</option>');

    const filteredPOs = selectedSupplier
      ? allPOs.filter(po => po.supplier_name === selectedSupplier)
      : allPOs;

    filteredPOs.forEach(po=> {
      $po.append(`<option value="${$('<div>').text(po.order_no||'').html()}">${$('<div>').text(po.order_no||'').html()}</option>`);
    });

    if (currentVal && filteredPOs.some(po => po.order_no === currentVal)) {
      $po.val(currentVal);
    }
  }

  function run(){
    const p = {
      category: $('#stk_category').val(),
      finish_id: $('#stk_finish').val(),
      color_id: $('#stk_color').val(),
      po_number: $('#stk_po').val(),
      supplier: $('#stk_supplier').val(),
      action: 'stock_available_detail'
    };
    <?php if (has_role(['admin','super_admin'])): ?>
    const bid = $('#stk_branch').val();
    if (bid) p.branch_id = bid;
    <?php endif; ?>

    $.get('api/reports.php', p, function(res){
      const $tb = $('#stk_table tbody');
      $tb.empty();
      const rows = res.data || [];
      if (!rows.length){
        $tb.append('<tr><td colspan="12" class="text-center text-muted">No data</td></tr>');
        return;
      }
      rows.forEach(r => {
        const finish = r.finish_name || '';
        $tb.append(
          `<tr>
            <td>${$('<div>').text(r.category||'').html()}</td>
            <td>${$('<div>').text(r.item_id||'').html()}</td>
            <td>${$('<div>').text(r.slab_no||'').html()}</td>
            <td>${$('<div>').text(r.po_number||'').html()}</td>
            <td>${$('<div>').text(r.color_name||'').html()}</td>
            <td>${$('<div>').text(finish).html()}</td>
            <td class="text-end">${Number(r.height||0).toFixed(2)}</td>
            <td class="text-end">${Number(r.length||0).toFixed(2)}</td>
            <td class="text-end">${Number(r.sq_ft||0).toFixed(3)}</td>
            <td>${$('<div>').text(r.quality||'').html()}</td>
            <td>${$('<div>').text(r.branch_name||'').html()}</td>
            <td>${$('<div>').text(r.store_name||'').html()}</td>
          </tr>`
        );
      });
    });
  }

  $('#stk_run').on('click', run);
  $('#stk_export').on('click', function(){
    exportTable('#stk_table', 'Stock_Available_Detail', 'StockDetail');
  });
  $('#stk_back').on('click', function(){
    window.location.href = '?page=stock_summary_report';
  });

  $('#stk_supplier').on('change', function(){
    updatePODropdown();
  });

  // Load dropdowns first, then set URL params, then run
  loadLookups(function(){
    // Load filters from URL params after dropdowns are loaded
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('category')) $('#stk_category').val(urlParams.get('category'));
    if (urlParams.get('color_id')) $('#stk_color').val(urlParams.get('color_id'));
    if (urlParams.get('finish_id')) $('#stk_finish').val(urlParams.get('finish_id'));
    run();
  });
})();
</script>

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