<?php
// ============================================================
//  MediCore — Inventory Reports
//  File: accounting/reports-inventory.php
// ============================================================
$page  = 'accounting/reports-inventory';
$title = 'Inventory Reports';
require_once '../includes/header.php';

$cur = $settings['currency'];

// ── Summary KPIs ──────────────────────────────────────────────
$totalProducts  = (int)   db_val("SELECT COUNT(*) FROM products WHERE is_active=1");
$totalStockVal  = (float) db_val("SELECT COALESCE(SUM(stock_pcs*sale_price),0) FROM products WHERE is_active=1");
$outOfStock     = (int)   db_val("SELECT COUNT(*) FROM products WHERE is_active=1 AND stock_pcs<=0");
$lowStock       = (int)   db_val("SELECT COUNT(*) FROM products WHERE is_active=1 AND stock_pcs>0 AND low_stock_alert>0 AND stock_pcs<low_stock_alert");
$expiredBatches = (int)   db_val("SELECT COUNT(DISTINCT product_id) FROM purchase_items WHERE exp!='' AND exp < DATE_FORMAT(NOW(),'%Y-%m')");

// ── Tab 1: Stock Report data ───────────────────────────────────
$allProducts = db_rows(
    "SELECT p.*,
            g.name AS generic_name,
            c.name AS company_name
       FROM products p
  LEFT JOIN generics  g ON g.id = p.generic_id
  LEFT JOIN companies c ON c.id = p.company_id
      WHERE p.is_active = 1
      ORDER BY p.name"
);

// ── Tab 4: Category-wise Stock ──────────────────────────────────
// Products with no category assigned are grouped under
// "(Uncategorized)" so the total always reconciles with the overall
// Total Stock Value KPI above.
ensure_categories_schema();
$categoryStock = db_rows(
    "SELECT
        COALESCE(cat.name,'(Uncategorized)')  AS category_name,
        COUNT(p.id)                     AS product_count,
        SUM(p.stock_pcs)                AS total_stock,
        SUM(p.stock_pcs * p.sale_price) AS stock_value,
        SUM(CASE WHEN p.stock_pcs<=0 THEN 1 ELSE 0 END) AS out_count,
        SUM(CASE WHEN p.stock_pcs>0 AND p.low_stock_alert>0
                  AND p.stock_pcs<p.low_stock_alert THEN 1 ELSE 0 END) AS low_count
       FROM products p
  LEFT JOIN categories cat ON cat.id = p.category_id
      WHERE p.is_active = 1
      GROUP BY cat.id, cat.name
      ORDER BY stock_value DESC"
);

// ── Tab 3: Company-wise Stock ──────────────────────────────────
$companyStock = db_rows(
    "SELECT
        COALESCE(c.name,'(No Company)') AS company_name,
        COUNT(p.id)                     AS product_count,
        SUM(p.stock_pcs)                AS total_stock,
        SUM(p.stock_pcs * p.sale_price) AS stock_value,
        SUM(CASE WHEN p.stock_pcs<=0 THEN 1 ELSE 0 END) AS out_count,
        SUM(CASE WHEN p.stock_pcs>0 AND p.low_stock_alert>0
                  AND p.stock_pcs<p.low_stock_alert THEN 1 ELSE 0 END) AS low_count
       FROM products p
  LEFT JOIN companies c ON c.id = p.company_id
      WHERE p.is_active = 1
      GROUP BY c.id, c.name
      ORDER BY stock_value DESC"
);
?>

<!-- ── Summary cards ──────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(5,1fr);
            gap:10px;margin-bottom:14px">
  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Total Products</div>
    <div class="sval b"><?= $totalProducts ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--teal)">
    <div class="slabel">Total Stock Value</div>
    <div class="sval b" style="color:var(--teal)">
      <?= $cur . number_format($totalStockVal, 0) ?>
    </div>
  </div>
  <div class="sc" style="border-top:3px solid var(--danger)">
    <div class="slabel">Out of Stock</div>
    <div class="sval b" style="color:var(--danger)"><?= $outOfStock ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--warn)">
    <div class="slabel">Low Stock</div>
    <div class="sval b" style="color:var(--warn)"><?= $lowStock ?></div>
  </div>
  <div class="sc" style="border-top:3px solid #ea580c">
    <div class="slabel">Expired Batches</div>
    <div class="sval b" style="color:#ea580c"><?= $expiredBatches ?></div>
  </div>
</div>

<!-- ── Tabs ───────────────────────────────────────── -->
<div style="display:flex;gap:0;margin-bottom:14px;
            border-bottom:2px solid var(--border)">
  <?php
  $tabs = [
    'stock'   => ['📋', 'Stock Report',     'var(--brand)'],
    'expiry'  => ['⏰', 'Expiry Report',    '#ea580c'],
    'company' => ['🏭', 'Company-wise',     'var(--teal)'],
    'category'=> ['🏷️', 'Category-wise',    'var(--purple,#7c3aed)'],
  ];
  foreach ($tabs as $id => [$icon, $label, $color]):
  ?>
  <button id="tab-<?= $id ?>" onclick="switchTab('<?= $id ?>')"
          data-color="<?= $color ?>"
    style="padding:9px 20px;font-size:12.5px;font-weight:600;border:none;
           cursor:pointer;background:transparent;color:var(--text2);
           border-bottom:2px solid transparent;margin-bottom:-2px;
           transition:all .15s">
    <?= $icon ?> <?= $label ?>
  </button>
  <?php endforeach; ?>

  <!-- Pagination toggle + Export, floated right -->
  <div style="margin-left:auto;align-self:center;padding-right:4px;
              display:flex;align-items:center;gap:12px">
    <label style="display:flex;align-items:center;gap:6px;font-size:12px;
                  color:var(--text2);cursor:pointer;user-select:none"
           title="ON = show one page of results at a time. OFF = load every row on this tab at once.">
      <input type="checkbox" id="pg-toggle" checked onchange="togglePagination(this.checked)">
      📄 Pagination
    </label>
    <button class="btn btn-sm" onclick="exportCurrentTab()">📤 Export CSV</button>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════
     TAB 1 — Stock Report
═══════════════════════════════════════════════════ -->
<div id="pane-stock">

  <!-- Filters -->
  <div style="display:flex;gap:9px;align-items:center;
              flex-wrap:wrap;margin-bottom:10px">
    <input type="text" id="st-search" placeholder="🔍 Search product…"
           oninput="filterStock()"
      style="padding:5px 10px;border:1px solid var(--border);
             border-radius:var(--rsm);font-family:inherit;
             font-size:12px;outline:none;width:180px">
    <select id="st-status" onchange="filterStock()"
      style="padding:5px 9px;border:1px solid var(--border);
             border-radius:var(--rsm);font-family:inherit;
             font-size:12px;outline:none">
      <option value="">All Status</option>
      <option value="out">🔴 Out of Stock</option>
      <option value="low">🟠 Low Stock</option>
      <option value="ok">🟢 Sufficient</option>
    </select>
    <select id="st-company" onchange="filterStock()"
      style="padding:5px 9px;border:1px solid var(--border);
             border-radius:var(--rsm);font-family:inherit;
             font-size:12px;outline:none">
      <option value="">All Companies</option>
      <?php
      $companies = array_unique(array_column($allProducts, 'company_name'));
      sort($companies);
      foreach ($companies as $co): if (!$co) continue; ?>
      <option value="<?= htmlspecialchars($co) ?>">
        <?= htmlspecialchars($co) ?>
      </option>
      <?php endforeach; ?>
    </select>
    <button class="btn btn-sm" onclick="
      document.getElementById('st-search').value='';
      document.getElementById('st-status').value='';
      document.getElementById('st-company').value='';
      filterStock()">✕ Clear</button>
    <span id="st-count"
          style="font-size:11px;color:var(--text3);margin-left:4px"></span>
    <select id="st-pagesize" onchange="stockPager.setPerPage(this.value)"
      style="margin-left:auto;padding:5px 9px;border:1px solid var(--border);
             border-radius:var(--rsm);font-family:inherit;
             font-size:12px;outline:none">
      <option value="100">100 / page</option>
      <option value="200">200 / page</option>
      <option value="500">500 / page</option>
      <option value="1000">1000 / page</option>
    </select>
  </div>

  <div class="card" style="padding:0">
    <div class="tw">
      <table id="stock-table">
        <thead>
          <tr>
            <th>#</th>
            <th>Product Name</th>
            <th>Generic</th>
            <th>Company</th>
            <th style="text-align:center">Stock (pcs)</th>
            <th style="text-align:center">Alert Qty</th>
            <th style="text-align:right">Sale Price</th>
            <th style="text-align:right">Stock Value</th>
            <th style="text-align:center">Status</th>
          </tr>
        </thead>
        <tbody id="stock-body">
          <?php
          $totalVal = 0;
          foreach ($allProducts as $i => $p):
            $stock  = (int)$p['stock_pcs'];
            $alert  = (int)($p['low_stock_alert'] ?? 0);
            $price  = (float)$p['sale_price'];
            $val    = $stock * $price;
            $totalVal += $val;

            if ($stock <= 0)
              { $stBg='#fde8e8'; $stCl='var(--danger)'; $stL='🔴 Out'; $stKey='out'; }
            elseif ($alert > 0 && $stock < $alert)
              { $stBg='#ffedd5'; $stCl='#ea580c'; $stL='🟠 Low'; $stKey='low'; }
            else
              { $stBg='#d4f0e6'; $stCl='var(--accent)'; $stL='🟢 OK'; $stKey='ok'; }
          ?>
          <tr class="stock-row"
              data-name="<?= htmlspecialchars(strtolower($p['name'])) ?>"
              data-company="<?= htmlspecialchars($p['company_name'] ?? '') ?>"
              data-status="<?= $stKey ?>"
              data-value="<?= $val ?>">
            <td style="color:var(--text3)"><?= $i + 1 ?></td>
            <td>
              <div style="font-weight:600;font-size:12px">
                <?= form_icon_name($p['form'] ?? '', $p['name']) ?>
              </div>
              <div style="font-size:10px;color:var(--text3)">
                <?= htmlspecialchars($p['strength'] ?? '') ?>
                <?= $p['form'] ? ' · ' . htmlspecialchars($p['form']) : '' ?>
              </div>
            </td>
            <td style="font-size:11.5px;color:var(--text2)">
              <?= htmlspecialchars($p['generic_name'] ?? '—') ?>
            </td>
            <td style="font-size:11.5px">
              <?= htmlspecialchars($p['company_name'] ?? '—') ?>
            </td>
            <td class="mono" style="text-align:center;font-weight:700;color:<?= $stCl ?>">
              <?= number_format($stock) ?>
            </td>
            <td class="mono" style="text-align:center;color:var(--text3)">
              <?= $alert > 0 ? number_format($alert) : '—' ?>
            </td>
            <td class="mono" style="text-align:right">
              <?= $cur . number_format($price, 2) ?>
            </td>
            <td class="mono" style="text-align:right;font-weight:700;
                                     color:<?= $val > 0 ? 'var(--brand)' : 'var(--text3)' ?>">
              <?= $val > 0 ? $cur . number_format($val, 2) : '—' ?>
            </td>
            <td style="text-align:center">
              <span class="badge"
                    style="background:<?= $stBg ?>;color:<?= $stCl ?>;font-weight:700">
                <?= $stL ?>
              </span>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
        <tfoot>
          <tr id="stock-foot"
              style="background:var(--brand-xlight);font-weight:700">
            <td colspan="7" style="text-align:right;color:var(--brand)">
              Total Stock Value:
            </td>
            <td class="mono" style="text-align:right;color:var(--brand);font-size:14px">
              <?= $cur . number_format($totalVal, 2) ?>
            </td>
            <td></td>
          </tr>
        </tfoot>
      </table>
    </div>
    <div id="stock-pager" style="display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border)"></div>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════
     TAB 2 — Expiry Report
═══════════════════════════════════════════════════ -->
<div id="pane-expiry" style="display:none">

  <?php
  $thisMonth = date('Y-m');
  $next1     = date('Y-m', strtotime('+1 month'));
  $next2     = date('Y-m', strtotime('+2 months'));

  $expired  = db_rows(
      "SELECT pi.*, p.name AS product_name, p.form, p.strength, p.rack,
              po.invoice AS po_invoice, po.date AS po_date,
              s.name AS supplier_name, s.phone AS supplier_phone
         FROM purchase_items pi
         JOIN products  p  ON p.id  = pi.product_id
         JOIN purchases po ON po.id = pi.purchase_id
    LEFT JOIN suppliers s  ON s.id  = po.supplier_id
        WHERE pi.exp != '' AND pi.exp < ?
        ORDER BY pi.exp ASC, p.name ASC", [$thisMonth]
  );
  $expiring = db_rows(
      "SELECT pi.*, p.name AS product_name, p.form, p.strength, p.rack,
              po.invoice AS po_invoice, po.date AS po_date,
              s.name AS supplier_name
         FROM purchase_items pi
         JOIN products  p  ON p.id  = pi.product_id
         JOIN purchases po ON po.id = pi.purchase_id
    LEFT JOIN suppliers s  ON s.id  = po.supplier_id
        WHERE pi.exp >= ? AND pi.exp <= ?
        ORDER BY pi.exp ASC", [$thisMonth, $next1]
  );
  $soon = db_rows(
      "SELECT pi.*, p.name AS product_name, p.form, p.strength, p.rack,
              po.invoice AS po_invoice, po.date AS po_date,
              s.name AS supplier_name
         FROM purchase_items pi
         JOIN products  p  ON p.id  = pi.product_id
         JOIN purchases po ON po.id = pi.purchase_id
    LEFT JOIN suppliers s  ON s.id  = po.supplier_id
        WHERE pi.exp > ? AND pi.exp <= ?
        ORDER BY pi.exp ASC", [$next1, $next2]
  );
  ?>

  <?php if (!$expired && !$expiring && !$soon): ?>
  <div class="al al-s" style="font-size:13px">
    ✅ No expired or expiring products in the next 2 months.
  </div>
  <?php endif; ?>

  <?php
  function renderExpTable(array $rows, string $label, string $hint, string $bg, string $cl, string $border): void {
    if (!$rows) return;
    echo <<<HTML
    <div class="card" style="padding:0;margin-bottom:14px;border-left:4px solid $border">
      <div class="ch" style="padding:10px 14px;background:$bg">
        <div class="ct" style="color:$border">$label
          <span class="badge" style="background:{$border}33;color:$border;margin-left:6px">
    HTML;
    echo count($rows);
    echo <<<HTML
          </span>
        </div>
        <span style="font-size:11px;color:$border">$hint</span>
      </div>
      <div class="tw">
        <table>
          <thead><tr>
            <th>Product</th><th style="text-align:center">Expiry</th>
            <th style="text-align:center">Qty (pcs)</th>
            <th>Supplier</th><th>PO Invoice</th>
          </tr></thead>
          <tbody>
    HTML;
    foreach ($rows as $b) {
        $qty = ((int)$b['qty_pcs']) + ((int)$b['free']);
        echo "<tr>
          <td>
            <div style='font-weight:600'>" . form_icon_name($b['form'] ?? '', $b['product_name']) . "</div>
            <div style='font-size:10px;color:#888'>
              " . htmlspecialchars($b['strength'] ?? '') .
              ($b['form'] ? ' · ' . htmlspecialchars($b['form']) : '') . "
            </div>
          </td>
          <td style='text-align:center'>
            <span class='badge' style='background:{$bg};color:{$border};font-weight:700'>
              " . htmlspecialchars($b['exp']) . "
            </span>
          </td>
          <td class='mono' style='text-align:center;font-weight:700;color:{$border}'>$qty</td>
          <td style='font-size:11.5px'>" . htmlspecialchars($b['supplier_name'] ?? '—') . "</td>
          <td class='mono' style='font-size:11px;color:var(--text3)'>" . htmlspecialchars($b['po_invoice']) . "</td>
        </tr>";
    }
    echo "</tbody></table></div></div>";
  }

  renderExpTable($expired,  '🚫 Expired',           'Remove from shelf immediately',         '#fde8e8', 'var(--danger)', 'var(--danger)');
  renderExpTable($expiring, '⚠ Expiring This Month','Sell or return before end of '.date('M Y'), '#fff3dc', 'var(--warn)',   'var(--warn)');
  renderExpTable($soon,     '📅 Expiring Next Month','Plan ahead for '.date('M Y', strtotime('+2 months')), 'var(--surface2)', 'var(--text2)', 'var(--text3)');
  ?>

  <div style="margin-top:8px">
    <a href="../product/expired.php" class="btn btn-sm btn-primary">
      🔗 View Full Expiry Page →
    </a>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════
     TAB 3 — Company-wise Stock
═══════════════════════════════════════════════════ -->
<div id="pane-company" style="display:none">

  <div style="display:flex;gap:8px;margin-bottom:10px">
    <input type="text" id="co-search" placeholder="🔍 Search company…"
           oninput="filterCompanies()"
      style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
             font-size:12px;outline:none;width:220px">
    <button class="btn btn-sm" onclick="document.getElementById('co-search').value='';filterCompanies()">
      ✕ Clear
    </button>
    <span id="co-count" style="font-size:11px;color:var(--text3);align-self:center"></span>
    <select id="co-pagesize" onchange="companyPager.setPerPage(this.value)"
      style="margin-left:auto;padding:5px 9px;border:1px solid var(--border);
             border-radius:var(--rsm);font-family:inherit;
             font-size:12px;outline:none">
      <option value="100">100 / page</option>
      <option value="200">200 / page</option>
      <option value="500">500 / page</option>
      <option value="1000">1000 / page</option>
    </select>
  </div>

  <div class="card" style="padding:0">
    <div class="tw">
      <table id="company-table">
        <thead>
          <tr>
            <th>#</th>
            <th>Company</th>
            <th style="text-align:center">Products</th>
            <th style="text-align:center">Total Stock (pcs)</th>
            <th style="text-align:right">Stock Value</th>
            <th style="text-align:center">Out of Stock</th>
            <th style="text-align:center">Low Stock</th>
            <th style="text-align:center;width:80px">% of Total</th>
          </tr>
        </thead>
        <tbody id="company-body">
          <?php
          $grandVal = max(1, array_sum(array_column($companyStock, 'stock_value')));
          foreach ($companyStock as $i => $co):
            $val = (float)$co['stock_value'];
            $pct = ($val / $grandVal) * 100;
          ?>
          <tr class="company-row" data-name="<?= htmlspecialchars(strtolower($co['company_name'])) ?>">
            <td style="color:var(--text3)"><?= $i + 1 ?></td>
            <td style="font-weight:700"><?= htmlspecialchars($co['company_name']) ?></td>
            <td style="text-align:center">
              <span class="badge"><?= $co['product_count'] ?></span>
            </td>
            <td class="mono" style="text-align:center;font-weight:700">
              <?= number_format($co['total_stock']) ?>
            </td>
            <td class="mono" style="text-align:right;font-weight:700;color:var(--brand)">
              <?= $cur . number_format($val, 2) ?>
            </td>
            <td style="text-align:center">
              <?= (int)$co['out_count'] > 0
                ? "<span class='badge' style='background:#fde8e8;color:var(--danger)'>{$co['out_count']}</span>"
                : '<span style="color:var(--text3)">—</span>' ?>
            </td>
            <td style="text-align:center">
              <?= (int)$co['low_count'] > 0
                ? "<span class='badge' style='background:#ffedd5;color:#ea580c'>{$co['low_count']}</span>"
                : '<span style="color:var(--text3)">—</span>' ?>
            </td>
            <td style="text-align:center">
              <div style="display:flex;align-items:center;gap:5px">
                <div style="flex:1;height:6px;background:var(--border);
                            border-radius:3px;overflow:hidden">
                  <div style="height:100%;width:<?= min(100,$pct) ?>%;
                              background:var(--brand);border-radius:3px"></div>
                </div>
                <span style="font-size:10.5px;color:var(--text3);white-space:nowrap">
                  <?= number_format($pct,1) ?>%
                </span>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
        <tfoot>
          <?php
          $totProds  = array_sum(array_column($companyStock,'product_count'));
          $totStock  = array_sum(array_column($companyStock,'total_stock'));
          $totVal    = array_sum(array_column($companyStock,'stock_value'));
          $totOut    = array_sum(array_column($companyStock,'out_count'));
          $totLow    = array_sum(array_column($companyStock,'low_count'));
          ?>
          <tr style="background:var(--brand-xlight);font-weight:700">
            <td colspan="2" style="color:var(--brand)">Total</td>
            <td style="text-align:center"><?= $totProds ?></td>
            <td class="mono" style="text-align:center"><?= number_format($totStock) ?></td>
            <td class="mono" style="text-align:right;color:var(--brand)">
              <?= $cur . number_format($totVal, 2) ?>
            </td>
            <td style="text-align:center;color:var(--danger)"><?= $totOut ?></td>
            <td style="text-align:center;color:#ea580c"><?= $totLow ?></td>
            <td></td>
          </tr>
        </tfoot>
      </table>
    </div>
    <div id="company-pager" style="display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border)"></div>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════
     TAB 4 — Category-wise Stock
═══════════════════════════════════════════════════ -->
<div id="pane-category" style="display:none">

  <div style="display:flex;gap:8px;margin-bottom:10px">
    <input type="text" id="catv-search" placeholder="🔍 Search category…"
           oninput="filterCategoriesStock()"
      style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
             font-size:12px;outline:none;width:220px">
    <button class="btn btn-sm" onclick="document.getElementById('catv-search').value='';filterCategoriesStock()">
      ✕ Clear
    </button>
    <span id="catv-count" style="font-size:11px;color:var(--text3);align-self:center"></span>
    <select id="catv-pagesize" onchange="categoryPager.setPerPage(this.value)"
      style="margin-left:auto;padding:5px 9px;border:1px solid var(--border);
             border-radius:var(--rsm);font-family:inherit;
             font-size:12px;outline:none">
      <option value="100">100 / page</option>
      <option value="200">200 / page</option>
      <option value="500">500 / page</option>
      <option value="1000">1000 / page</option>
    </select>
  </div>

  <div class="card" style="padding:0">
    <div class="tw">
      <table id="category-table">
        <thead>
          <tr>
            <th>#</th>
            <th>Category</th>
            <th style="text-align:center">Products</th>
            <th style="text-align:center">Total Stock (pcs)</th>
            <th style="text-align:right">Stock Value</th>
            <th style="text-align:center">Out of Stock</th>
            <th style="text-align:center">Low Stock</th>
            <th style="text-align:center;width:80px">% of Total</th>
          </tr>
        </thead>
        <tbody id="category-body">
          <?php
          $grandCatVal = max(1, array_sum(array_column($categoryStock, 'stock_value')));
          foreach ($categoryStock as $i => $cs):
            $cval = (float)$cs['stock_value'];
            $cpct = ($cval / $grandCatVal) * 100;
          ?>
          <tr class="catv-row" data-name="<?= htmlspecialchars(strtolower($cs['category_name'])) ?>">
            <td style="color:var(--text3)"><?= $i + 1 ?></td>
            <td style="font-weight:700">
              <span class="badge" style="background:var(--teal-light);color:var(--teal)">
                <?= htmlspecialchars($cs['category_name']) ?>
              </span>
            </td>
            <td style="text-align:center">
              <span class="badge"><?= $cs['product_count'] ?></span>
            </td>
            <td class="mono" style="text-align:center;font-weight:700">
              <?= number_format($cs['total_stock']) ?>
            </td>
            <td class="mono" style="text-align:right;font-weight:700;color:var(--brand)">
              <?= $cur . number_format($cval, 2) ?>
            </td>
            <td style="text-align:center">
              <?= (int)$cs['out_count'] > 0
                ? "<span class='badge' style='background:#fde8e8;color:var(--danger)'>{$cs['out_count']}</span>"
                : '<span style="color:var(--text3)">—</span>' ?>
            </td>
            <td style="text-align:center">
              <?= (int)$cs['low_count'] > 0
                ? "<span class='badge' style='background:#ffedd5;color:#ea580c'>{$cs['low_count']}</span>"
                : '<span style="color:var(--text3)">—</span>' ?>
            </td>
            <td style="text-align:center">
              <div style="display:flex;align-items:center;gap:5px">
                <div style="flex:1;height:6px;background:var(--border);
                            border-radius:3px;overflow:hidden">
                  <div style="height:100%;width:<?= min(100,$cpct) ?>%;
                              background:var(--purple,#7c3aed);border-radius:3px"></div>
                </div>
                <span style="font-size:10.5px;color:var(--text3);white-space:nowrap">
                  <?= number_format($cpct,1) ?>%
                </span>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
        <tfoot>
          <?php
          $totCatProds = array_sum(array_column($categoryStock,'product_count'));
          $totCatStock = array_sum(array_column($categoryStock,'total_stock'));
          $totCatVal   = array_sum(array_column($categoryStock,'stock_value'));
          $totCatOut   = array_sum(array_column($categoryStock,'out_count'));
          $totCatLow   = array_sum(array_column($categoryStock,'low_count'));
          ?>
          <tr style="background:var(--brand-xlight);font-weight:700">
            <td colspan="2" style="color:var(--brand)">Total</td>
            <td style="text-align:center"><?= $totCatProds ?></td>
            <td class="mono" style="text-align:center"><?= number_format($totCatStock) ?></td>
            <td class="mono" style="text-align:right;color:var(--brand)">
              <?= $cur . number_format($totCatVal, 2) ?>
            </td>
            <td style="text-align:center;color:var(--danger)"><?= $totCatOut ?></td>
            <td style="text-align:center;color:#ea580c"><?= $totCatLow ?></td>
            <td></td>
          </tr>
        </tfoot>
      </table>
    </div>
    <div id="category-pager" style="display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border)"></div>
  </div>
</div>

<script>
let activeTab = 'stock';

function switchTab(id) {
  activeTab = id;
  document.querySelectorAll('[id^="pane-"]').forEach(p => p.style.display = 'none');
  document.querySelectorAll('[id^="tab-"]').forEach(b => {
    b.style.borderBottomColor = 'transparent';
    b.style.color = 'var(--text2)';
  });
  document.getElementById('pane-' + id).style.display = 'block';
  const btn = document.getElementById('tab-' + id);
  btn.style.borderBottomColor = btn.dataset.color;
  btn.style.color = btn.dataset.color;
}

// ── Pagination — see mediPaginate() in includes/footer.php.
// Every row stays in the DOM (tfoot totals reflect the FULL dataset,
// not just one page); pagination only ever hides/shows a slice of
// whatever currently matches each tab's own filter controls.
let stockPager, companyPager, categoryPager;

// ── Stock tab filter ──────────────────────────────────────────
function filterStock() {
  stockPager.refresh();
}

function filterCompanies() {
  companyPager.refresh();
}

function filterCategoriesStock() {
  categoryPager.refresh();
}

function initReportPagers() {
  stockPager = mediPaginate({
    rows: Array.from(document.querySelectorAll('.stock-row')),
    predicate: row => {
      const q       = document.getElementById('st-search').value.toLowerCase();
      const status   = document.getElementById('st-status').value;
      const company  = document.getElementById('st-company').value.toLowerCase();
      const matchQ = !q       || row.dataset.name.includes(q);
      const matchS = !status  || row.dataset.status === status;
      const matchC = !company || row.dataset.company.toLowerCase() === company;
      return matchQ && matchS && matchC;
    },
    pagerEl: document.getElementById('stock-pager'),
    countEl: document.getElementById('st-count'),
    countLabel: 'product',
    perPage: 100, renumber: false,
  });
  companyPager = mediPaginate({
    rows: Array.from(document.querySelectorAll('.company-row')),
    predicate: row => {
      const q = document.getElementById('co-search').value.toLowerCase();
      return !q || row.dataset.name.includes(q);
    },
    pagerEl: document.getElementById('company-pager'),
    countEl: document.getElementById('co-count'),
    countLabel: 'company',
    perPage: 100, renumber: false,
  });
  categoryPager = mediPaginate({
    rows: Array.from(document.querySelectorAll('.catv-row')),
    predicate: row => {
      const q = document.getElementById('catv-search').value.toLowerCase();
      return !q || row.dataset.name.includes(q);
    },
    pagerEl: document.getElementById('category-pager'),
    countEl: document.getElementById('catv-count'),
    countLabel: 'category',
    perPage: 100, renumber: false,
  });

  // Restore the user's last pagination ON/OFF choice for this report
  const storedOn = localStorage.getItem('inv_report_pagination') !== 'off';
  const pgToggle = document.getElementById('pg-toggle');
  if (pgToggle) pgToggle.checked = storedOn;
  togglePagination(storedOn);
}

// ── Pagination ON/OFF toggle ────────────────────────────────────
// Applies to all three paginated tabs at once (Stock, Company-wise,
// Category-wise) — OFF loads every row on the currently-open tab
// immediately, ON goes back to whatever page size is selected.
function togglePagination(on) {
  [stockPager, companyPager, categoryPager].forEach(p => p && p.setShowAll(!on));
  document.querySelectorAll('#st-pagesize, #co-pagesize, #catv-pagesize')
    .forEach(el => { el.disabled = !on; });
  localStorage.setItem('inv_report_pagination', on ? 'on' : 'off');
}

// ── Export CSV ────────────────────────────────────────────────
function exportCurrentTab() {
  const urls = {
    stock:    '../api/products.php?action=export_stock_csv',
    expiry:   '../api/products.php?action=export_expiry_csv',
    company:  '../api/products.php?action=export_company_csv',
    category: '../api/products.php?action=export_category_csv',
  };
  window.open(urls[activeTab] || urls.stock, '_blank');
}

document.addEventListener('DOMContentLoaded', () => {
  switchTab('stock');
  initReportPagers();
});
</script>

<?php require_once '../includes/footer.php'; ?>
