<?php include APP_PATH.'/views/partials/report_header.php'; ?>

<!-- Screen filters only -->
<div class="rpt-btn-bar no-print">
  <form method="GET" action="<?=APP_URL?>/reports/stock"
        class="d-flex gap-2 flex-wrap align-items-end filter-form">
    <div>
      <label class="form-label small mb-1">Category</label>
      <select name="category" class="form-select form-select-sm">
        <option value="">All Categories</option>
        <?php foreach($categories as$c):?>
        <option value="<?=$c['id']?>" <?=$catId==$c['id']?'selected':''?>>
          <?=e($c['category_name'])?>
        </option>
        <?php endforeach;?>
      </select>
    </div>
    <div>
      <label class="form-label small mb-1">Stock Status</label>
      <select name="stock" class="form-select form-select-sm">
        <option value="all" <?=$stockF==='all'?'selected':''?>>All Stock</option>
        <option value="ok"  <?=$stockF==='ok' ?'selected':''?>>OK Only</option>
        <option value="low" <?=$stockF==='low'?'selected':''?>>Low Stock</option>
        <option value="out" <?=$stockF==='out'?'selected':''?>>Out of Stock</option>
      </select>
    </div>
    <button class="btn btn-secondary btn-sm align-self-end">
      <i class="bi bi-funnel me-1"></i>Filter
    </button>
    <a href="<?=APP_URL?>/reports/stock"
       class="btn btn-outline-secondary btn-sm align-self-end">Clear</a>
  </form>
</div>

<!-- KPI Summary -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="card text-center py-3">
      <div class="fw-bold fs-4"><?=number_format(count($rows))?></div>
      <small class="text-muted">Total Products</small>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card text-center py-3 border-primary">
      <div class="fw-bold text-primary"><?=currency($total['cv'])?></div>
      <small class="text-muted">Cost Value</small>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card text-center py-3 border-success">
      <div class="fw-bold text-success"><?=currency($total['rv'])?></div>
      <small class="text-muted">Retail Value</small>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card text-center py-3 <?=($outCount+$lowCount)>0?'border-warning':''?>">
      <div class="fw-bold <?=$outCount>0?'text-danger':'text-warning'?>">
        <?=$outCount?> out &nbsp; <?=$lowCount?> low
      </div>
      <small class="text-muted">Stock Alerts</small>
    </div>
  </div>
</div>

<!-- Category Summary table -->
<?php if(!empty($byCategory)):?>
<div class="card mb-3">
  <div class="card-header fw-semibold small">
    Stock Value by Category
  </div>
  <table class="table table-sm mb-0">
    <thead class="table-dark">
      <tr>
        <th>#</th>
        <th>Category</th>
        <th class="text-end">Products</th>
        <th class="text-end">Cost Value</th>
        <th class="text-end">Retail Value</th>
        <th class="text-end">Potential Profit</th>
        <th>Alerts</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach($byCategory as$i=>$c):
        $pot=(float)$c['retail_value']-(float)$c['cost_value'];
      ?>
      <tr>
        <td class="text-muted"><?=$i+1?></td>
        <td class="fw-semibold"><?=e($c['category_name'])?></td>
        <td class="text-end"><?=number_format($c['product_count'])?></td>
        <td class="text-end"><?=currency($c['cost_value'])?></td>
        <td class="text-end"><?=currency($c['retail_value'])?></td>
        <td class="text-end text-success fw-semibold"><?=currency($pot)?></td>
        <td>
          <?php if($c['out_count']>0):?>
          <span class="badge bg-danger"><?=$c['out_count']?> Out</span>
          <?php endif;?>
          <?php if($c['low_count']>0):?>
          <span class="badge bg-warning text-dark"><?=$c['low_count']?> Low</span>
          <?php endif;?>
        </td>
      </tr>
      <?php endforeach;?>
    </tbody>
    <tfoot class="table-secondary fw-bold">
      <tr>
        <td colspan="3">TOTAL</td>
        <td class="text-end"><?=currency($total['cv'])?></td>
        <td class="text-end"><?=currency($total['rv'])?></td>
        <td class="text-end text-success"><?=currency($total['rv']-$total['cv'])?></td>
        <td></td>
      </tr>
    </tfoot>
  </table>
</div>
<?php endif;?>

<!-- Page break before detail table on print -->
<div class="page-break-before-print"></div>

<!-- Product Detail table — NO table-responsive wrapper (prevents print scrollbar) -->
<div class="card">
  <div class="card-header fw-semibold small d-flex justify-content-between align-items-center">
    <span>Product Stock Detail</span>
    <small class="text-muted fw-normal"><?=number_format(count($rows))?> products</small>
  </div>

  <table class="table table-sm table-hover mb-0 stock-detail-table">
    <thead class="table-dark">
      <tr>
        <th>#</th>
        <th>Code</th>
        <th>Product Name</th>
        <th>Category</th>
        <th>Unit</th>
        <th class="text-end">Stock</th>
        <th class="text-end">Reorder</th>
        <th class="text-end">Cost</th>
        <th class="text-end">Sell</th>
        <th class="text-end">Cost Value</th>
        <th class="text-end">Retail Value</th>
        <th>Status</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach($rows as$i=>$r):
        $isOut  = (float)$r['current_stock'] <= 0;
        $isLow  = (float)$r['reorder_level'] > 0
               && (float)$r['current_stock'] <= (float)$r['reorder_level']
               && !$isOut;
        $rowCls = $isOut ? 'table-danger bg-opacity-5'
                : ($isLow ? 'table-warning bg-opacity-5' : '');
      ?>
      <tr class="<?=$rowCls?>">
        <td class="text-muted"><?=$i+1?></td>
        <td><code style="font-size:.72rem"><?=e($r['product_code'])?></code></td>
        <td class="fw-semibold"><?=e($r['product_name'])?></td>
        <td class="text-muted"><?=e($r['category_name'])?></td>
        <td class="text-muted"><?=e($r['unit']??'')?></td>
        <td class="text-end fw-bold <?=$isOut?'text-danger':($isLow?'text-warning':'text-success')?>">
          <?=number_format((float)$r['current_stock'],2)?>
        </td>
        <td class="text-end text-muted"><?=number_format((float)$r['reorder_level'],2)?></td>
        <td class="text-end"><?=currency($r['cost_price'])?></td>
        <td class="text-end"><?=currency($r['selling_price'])?></td>
        <td class="text-end"><?=currency($r['cost_value'])?></td>
        <td class="text-end text-success"><?=currency($r['retail_value'])?></td>
        <td>
          <?php if($isOut):?>
          <span class="badge bg-danger">Out</span>
          <?php elseif($isLow):?>
          <span class="badge bg-warning text-dark">Low</span>
          <?php else:?>
          <span class="badge bg-success">OK</span>
          <?php endif;?>
        </td>
      </tr>
      <?php endforeach;?>
      <?php if(empty($rows)):?>
      <tr><td colspan="12" class="text-center text-muted py-4">No products found.</td></tr>
      <?php endif;?>
    </tbody>
    <tfoot class="table-secondary fw-bold">
      <tr>
        <td colspan="9">TOTAL &nbsp;<small class="fw-normal text-muted">(<?=number_format(count($rows))?> products)</small></td>
        <td class="text-end"><?=currency($total['cv'])?></td>
        <td class="text-end text-success"><?=currency($total['rv'])?></td>
        <td></td>
      </tr>
    </tfoot>
  </table>
</div>

<style>
/* ── Screen: make detail table horizontally scrollable ─── */
.stock-detail-table { min-width: 900px; }
.card:last-child .card-header + * { overflow-x: auto; }

/* ── Print specific overrides ──────────────────────────── */
@media print {
  /* CRITICAL: remove all overflow/scrollbars */
  * {
    overflow: visible !important;
    max-height: none !important;
  }
  ::-webkit-scrollbar { display: none !important; width: 0 !important; }

  /* Detail table: smaller font to fit A4 landscape */
  .stock-detail-table {
    min-width: 0 !important;
    width: 100% !important;
    font-size: 7pt !important;
    table-layout: fixed !important;
  }
  .stock-detail-table th,
  .stock-detail-table td {
    padding: 2px 3px !important;
    font-size: 7pt !important;
    overflow: hidden !important;
    white-space: nowrap !important;
  }
  /* Column widths for A4 landscape */
  .stock-detail-table th:nth-child(1) { width: 3% }   /* # */
  .stock-detail-table th:nth-child(2) { width: 7% }   /* Code */
  .stock-detail-table th:nth-child(3) { width: 22% }  /* Name */
  .stock-detail-table th:nth-child(4) { width: 11% }  /* Category */
  .stock-detail-table th:nth-child(5) { width: 4% }   /* Unit */
  .stock-detail-table th:nth-child(6) { width: 6% }   /* Stock */
  .stock-detail-table th:nth-child(7) { width: 6% }   /* Reorder */
  .stock-detail-table th:nth-child(8) { width: 8% }   /* Cost */
  .stock-detail-table th:nth-child(9) { width: 8% }   /* Sell */
  .stock-detail-table th:nth-child(10){ width: 9% }   /* Cost Val */
  .stock-detail-table th:nth-child(11){ width: 9% }   /* Retail Val */
  .stock-detail-table th:nth-child(12){ width: 7% }   /* Status */

  /* Category table stays on first page */
  .card:first-of-type { break-after: avoid !important; }

  /* Force landscape for stock detail */
  @page { size: A4 landscape; margin: 10mm 8mm 12mm 8mm; }

  .page-break-before-print { display: block !important; break-before: page !important; }
}
</style>