<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-stock-summary-report">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="mb-0">Stock Summary Report</h4>
      <button id="stk_export" class="btn btn-sm btn-outline-success"><i class="bi bi-file-earmark-excel"></i> Export XLSX</button>
    </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">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" id="stk_table">
        <thead>
          <tr>
            <th>Category</th>
            <th>Color</th>
            <th>Finish</th>
            <th class="text-end">Count</th>
            <th class="text-end">Total SQ.FT</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
  </div>
</div>

<script>
(function(){
  if (!$('.page-stock-summary-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 = []; // Store all POs for filtering

  function loadLookups(){
    $.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||[]); });
    // Load suppliers dropdown
    $.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>`));
    });
    // Load all POs for later filtering by supplier
    $.get('api/purchase_orders.php', { action:'list' }, function(res){
      allPOs = res.data || [];
      updatePODropdown(); // Initially show all POs
    });
    <?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; ?>
  }

  // Update PO dropdown based on selected supplier
  function updatePODropdown(){
    const selectedSupplier = $('#stk_supplier').val();
    const $po = $('#stk_po');
    const currentVal = $po.val();
    $po.empty();
    $po.append('<option value="">All</option>');

    // Filter POs by supplier if one is selected
    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>`);
    });

    // Restore selection if still valid
    if (currentVal && filteredPOs.some(po => po.order_no === currentVal)) {
      $po.val(currentVal);
    }
  }

  function run(){
    const p = {
      finish_id: $('#stk_finish').val(),
      color_id: $('#stk_color').val(),
      po_number: $('#stk_po').val(),
      supplier: $('#stk_supplier').val(),
      action: 'stock_available_summary'
    };
    <?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="5" class="text-center text-muted">No data</td></tr>');
        return;
      }
      rows.forEach(r => {
        const finish = r.finish_name || '';
        const count = Number(r.item_count||0).toFixed(0);
        const countHtml = count > 0
          ? `<a href="?page=stock_detail_report&category=${encodeURIComponent(r.category||'')}&color_id=${r.color_id||''}&finish_id=${r.finish_id||''}" target="_blank" style="text-decoration:none; color:inherit;">${count}</a>`
          : count;
        $tb.append(
          `<tr>
            <td>${$('<div>').text(r.category||'').html()}</td>
            <td>${$('<div>').text(r.color_name||'').html()}</td>
            <td>${$('<div>').text(finish).html()}</td>
            <td class="text-end">${countHtml}</td>
            <td class="text-end">${Number(r.total_sq_ft||0).toFixed(3)}</td>
          </tr>`
        );
      });
    });
  }

  $('#stk_run').on('click', run);
  $('#stk_export').on('click', function(){
    exportTable('#stk_table', 'Stock_Available_Summary', 'StockAvailable');
  });

  // When supplier changes, update PO dropdown
  $('#stk_supplier').on('change', function(){
    updatePODropdown();
  });

  loadLookups();
  run();
})();
</script>

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