<?php /* stock/index.php */
$sym      = setting('currency_symbol','Rs.');
$data     = $pagination['data'];
$lastPage = $pagination['pages'];
$curPage  = $pagination['current'];
$perPage  = $pagination['perPage'];
$potential = $totalSellValue - $totalValue; // potential profit
?>

<style>
.st-hero{background:linear-gradient(135deg,#134e4a,#0f766e 55%,#0d9488);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.kpi-pill{border-radius:10px;padding:12px 14px;text-align:center;height:100%}
.kpi-pill .val{font-size:1.2rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.62rem;text-transform:uppercase;letter-spacing:.05em;margin-top:3px}
.st-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.st-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.st-table tr:hover td{background:#f0fdfa}
.stock-gauge{height:8px;border-radius:4px;background:#f1f5f9;overflow:hidden}
.stock-gauge-fill{height:8px;border-radius:4px;transition:width .4s ease}
.st-badge{padding:2px 8px;border-radius:12px;font-size:.62rem;font-weight:700;
  display:inline-flex;align-items:center;gap:3px}
.filter-tabs .btn{border-radius:20px;font-size:.75rem;font-weight:600;padding:4px 14px}
</style>

<!-- Hero -->
<div class="st-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1"><i class="bi bi-layers me-2"></i>Stock Management</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?=$totalProducts?> products &nbsp;·&nbsp;
        Cost value: <strong><?=$sym?><?=number_format($totalValue,0)?></strong>
        &nbsp;·&nbsp;
        Sell value: <strong><?=$sym?><?=number_format($totalSellValue,0)?></strong>
        &nbsp;·&nbsp;
        Potential profit: <strong class="text-warning"><?=$sym?><?=number_format($potential,0)?></strong>
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?=APP_URL?>/stock/movements"
         class="btn btn-outline-light btn-sm fw-semibold">
        <i class="bi bi-arrow-left-right me-1"></i>Movements
      </a>
      <?php if(Auth::can('stock.manage')):?>
      <a href="<?=APP_URL?>/stock/adjust"
         class="btn btn-light btn-sm fw-semibold" style="color:#0f766e">
        <i class="bi bi-sliders me-1"></i>Adjust Stock
      </a>
      <?php endif;?>
      <button onclick="window.print()" class="btn btn-outline-light btn-sm">
        <i class="bi bi-printer me-1"></i>Print
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- KPI Pills -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-2">
    <div class="kpi-pill" style="background:#f0fdfa;border:2px solid #0d9488">
      <div class="val" style="color:#0d9488"><?=$totalProducts?></div>
      <div class="lbl" style="color:#0d9488">Total Products</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="kpi-pill" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val" style="color:#dc2626"><?=$outStockCount?></div>
      <div class="lbl" style="color:#dc2626">Out of Stock</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="kpi-pill" style="background:#fff7ed;border:2px solid #f97316">
      <div class="val" style="color:#f97316"><?=$lowStockCount?></div>
      <div class="lbl" style="color:#f97316">Low Stock</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val" style="color:#16a34a"><?=$totalProducts-$outStockCount-$lowStockCount?></div>
      <div class="lbl" style="color:#16a34a">In Stock OK</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <a href="?expiry=expired" class="text-decoration-none">
    <div class="kpi-pill" style="background:<?=$expiredCount>0?'#fef2f2':'#f8fafc'?>;
                                  border:2px solid <?=$expiredCount>0?'#dc2626':'#e2e8f0'?>">
      <div class="val" style="color:<?=$expiredCount>0?'#dc2626':'#94a3b8'?>"><?=$expiredCount?></div>
      <div class="lbl" style="color:<?=$expiredCount>0?'#dc2626':'#94a3b8'?>">Expired</div>
    </div>
    </a>
  </div>
  <div class="col-6 col-md-2">
    <a href="?expiry=soon" class="text-decoration-none">
    <div class="kpi-pill" style="background:<?=$expiringSoon>0?'#fffbeb':'#f8fafc'?>;
                                  border:2px solid <?=$expiringSoon>0?'#d97706':'#e2e8f0'?>">
      <div class="val" style="color:<?=$expiringSoon>0?'#d97706':'#94a3b8'?>"><?=$expiringSoon?></div>
      <div class="lbl" style="color:<?=$expiringSoon>0?'#d97706':'#94a3b8'?>">Expiring ≤30d</div>
    </div>
    </a>
  </div>
  <div class="col-6 col-md-2">
    <div class="kpi-pill" style="background:#f0fdfa;border:2px solid #0d9488">
      <div class="val" style="color:#0d9488"><?=$sym?><?=number_format($totalValue,0)?></div>
      <div class="lbl" style="color:#0d9488">Cost Value</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="kpi-pill" style="background:#fef9c3;border:2px solid #d97706">
      <div class="val" style="color:#d97706"><?=$sym?><?=number_format($potential,0)?></div>
      <div class="lbl" style="color:#d97706">Potential Profit</div>
    </div>
  </div>
</div>

<!-- Alert buttons -->
<?php if($outStockCount > 0 || $lowStockCount > 0 || $expiredCount > 0 || $expiringSoon > 0):?>
<div class="d-flex gap-2 mb-3 flex-wrap">
  <?php if($expiredCount > 0):?>
  <a href="?expiry=expired" class="btn btn-danger btn-sm fw-semibold">
    <i class="bi bi-calendar-x-fill me-1"></i>
    <?=$expiredCount?> Expired — Remove from stock!
  </a>
  <?php endif;?>
  <?php if($expiringSoon > 0):?>
  <a href="?expiry=soon" class="btn btn-warning btn-sm fw-semibold text-dark">
    <i class="bi bi-clock-fill me-1"></i>
    <?=$expiringSoon?> Expiring within 30 days
  </a>
  <?php endif;?>
  <?php if($outStockCount > 0):?>
  <a href="?stock=out" class="btn btn-danger btn-sm fw-semibold">
    <i class="bi bi-exclamation-octagon-fill me-1"></i>
    <?=$outStockCount?> Out of Stock
  </a>
  <?php endif;?>
  <?php if($lowStockCount > 0):?>
  <a href="?stock=low" class="btn btn-warning btn-sm fw-semibold text-dark">
    <i class="bi bi-exclamation-triangle-fill me-1"></i>
    <?=$lowStockCount?> Low Stock
  </a>
  <?php endif;?>
</div>
<?php endif;?>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/stock"
          class="d-flex gap-2 flex-wrap align-items-end">
      <div class="input-group input-group-sm" style="max-width:220px">
        <span class="input-group-text"><i class="bi bi-search"></i></span>
        <input type="text" name="search" class="form-control"
               placeholder="Name, code, barcode…"
               value="<?=e($search)?>">
      </div>
      <select name="category" class="form-select form-select-sm" style="max-width:150px">
        <option value="0">All Categories</option>
        <?php foreach($categories as $cat):?>
        <option value="<?=$cat['id']?>" <?=$catId==$cat['id']?'selected':''?>>
          <?=e($cat['category_name'])?>
        </option>
        <?php endforeach;?>
      </select>
      <!-- Stock status tabs -->
      <div class="filter-tabs d-flex gap-1">
        <?php foreach([
          ['all','All','bg-secondary'],
          ['ok','✅ OK','btn-outline-success'],
          ['low','⚠ Low','btn-outline-warning'],
          ['out','🔴 Out','btn-outline-danger'],
        ] as[$val,$lbl,$cls]):
          $active = $stockF===$val;
        ?>
        <a href="?search=<?=urlencode($search)?>&category=<?=$catId?>&stock=<?=$val?>&expiry=<?=$expiryF?>"
           class="btn <?=$active?'btn-'.($val==='all'?'secondary':($val==='ok'?'success':($val==='low'?'warning':'danger'))):$cls?>">
          <?=$lbl?>
        </a>
        <?php endforeach;?>
      </div>
      <!-- Expiry filter tabs -->
      <div class="filter-tabs d-flex gap-1">
        <?php foreach([
          ['all','All Expiry','btn-outline-secondary'],
          ['expired','❌ Expired','btn-outline-danger'],
          ['soon','⏰ ≤30d','btn-outline-warning'],
          ['ok','✅ Safe','btn-outline-success'],
        ] as[$val,$lbl,$cls]):
          $active = ($expiryF??'all')===$val;
        ?>
        <a href="?search=<?=urlencode($search)?>&category=<?=$catId?>&stock=<?=$stockF?>&expiry=<?=$val?>"
           class="btn <?=$active?'btn-'.($val==='all'?'secondary':($val==='expired'||$val==='soon'?'danger':($val==='soon'?'warning':'success'))):$cls?>">
          <?=$lbl?>
        </a>
        <?php endforeach;?>
      </div>
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <a href="<?=APP_URL?>/stock" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
    </form>
  </div>
</div>

<!-- Stock Table -->
<div class="card">
  <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
    <span class="fw-semibold small">
      <i class="bi bi-layers me-1"></i>Stock Register
    </span>
    <span class="badge bg-secondary">
      <?=number_format($pagination['total'])?> products · Page <?=$curPage?>/<?=$lastPage?>
    </span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 st-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3">#</th>
          <th>Product</th>
          <th>Category</th>
          <th class="text-center">Unit</th>
          <th class="text-center">Stock Level</th>
          <th class="text-center">Reorder</th>
          <th class="text-center">Expiry Date</th>
          <th class="text-end">Cost Price</th>
          <th class="text-end">Sell Price</th>
          <th class="text-end">Stock Value</th>
          <th class="text-center">Status</th>
          <th class="text-center">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($data)):?>
        <tr>
          <td colspan="12" class="text-center text-muted py-5">
            <i class="bi bi-layers d-block fs-2 mb-2 opacity-25"></i>
            No products found for selected filter.
          </td>
        </tr>
        <?php endif;?>

        <?php
        $rowNum = ($curPage-1)*$perPage;
        foreach($data as $p):
          $rowNum++;
          $stock   = (float)$p['current_stock'];
          $reorder = (float)($p['reorder_level'] ?? 0);
          $cost    = (float)$p['cost_price'];
          $sell    = (float)$p['selling_price'];
          $val     = round($stock * $cost, 2);

          $isOut   = $stock <= 0;
          $isLow   = !$isOut && $reorder > 0 && $stock <= $reorder;
          $isOk    = !$isOut && !$isLow;

          $stColor = $isOut ? '#dc2626' : ($isLow ? '#f97316' : '#16a34a');
          $stBg    = $isOut ? '#fef2f2' : ($isLow ? '#fff7ed' : '#f0fdf4');

          // Stock gauge percent (100% = 2x reorder level)
          $gaugeMax = max($reorder * 2, $stock, 1);
          $gaugePct = min(100, round($stock / $gaugeMax * 100));
        ?>
        <tr style="<?=$isOut?'background:#fef2f2':($isLow?'background:#fffbeb':'')?>">
          <td class="ps-3 text-muted small"><?=$rowNum?></td>

          <!-- Product -->
          <td>
            <div class="fw-semibold"><?=e($p['product_name'])?></div>
            <div style="font-size:.64rem;color:#94a3b8">
              <code><?=e($p['product_code'])?></code>
              <?php if($p['barcode']&&$p['barcode']!=$p['product_code']):?>
              &nbsp;·&nbsp;<i class="bi bi-upc"></i><?=e($p['barcode'])?>
              <?php endif;?>
            </div>
          </td>

          <!-- Category -->
          <td class="text-muted small"><?=e($p['category_name']??'—')?></td>

          <!-- Unit -->
          <td class="text-center">
            <span style="background:#f1f5f9;border-radius:4px;padding:2px 7px;
                         font-size:.65rem;font-weight:700;color:#475569">
              <?=e($p['unit']??'—')?>
            </span>
          </td>

          <!-- Stock Level -->
          <td class="text-center" style="min-width:120px">
            <div class="d-flex align-items-center gap-2 justify-content-center">
              <div style="min-width:60px">
                <div class="fw-bold" style="color:<?=$stColor?>;font-size:.88rem">
                  <?=number_format($stock,2)?>
                </div>
                <div class="stock-gauge" style="width:70px">
                  <div class="stock-gauge-fill"
                       style="width:<?=$gaugePct?>%;background:<?=$stColor?>"></div>
                </div>
              </div>
              <?php if($isOut):?>
              <span class="st-badge" style="background:#fef2f2;color:#dc2626">
                <i class="bi bi-exclamation-octagon-fill"></i>OUT
              </span>
              <?php elseif($isLow):?>
              <span class="st-badge" style="background:#fff7ed;color:#f97316">
                <i class="bi bi-exclamation-triangle-fill"></i>LOW
              </span>
              <?php endif;?>
            </div>
          </td>

          <!-- Reorder Level -->
          <td class="text-center text-muted small">
            <?=$reorder > 0 ? number_format($reorder,0) : '—'?>
          </td>

          <!-- Expiry Date -->
          <td class="text-center">
            <?php if(!empty($p['has_expiry']) && !empty($p['expiry_date'])):
              $dl = (int)ceil((strtotime($p['expiry_date'])-time())/86400);
              if($dl < 0):?>
              <span class="st-badge bg-danger text-white">
                <i class="bi bi-calendar-x"></i>EXPIRED
              </span>
              <div style="font-size:.6rem;color:#dc2626;margin-top:2px">
                <?=date('d M Y',strtotime($p['expiry_date']))?>
              </div>
            <?php elseif($dl===0):?>
              <span class="st-badge bg-danger text-white">
                <i class="bi bi-exclamation-circle"></i>TODAY
              </span>
            <?php elseif($dl<=30):?>
              <span class="st-badge bg-warning text-dark">
                <i class="bi bi-clock"></i><?=$dl?>d
              </span>
              <div style="font-size:.6rem;color:#d97706;margin-top:2px">
                <?=date('d M Y',strtotime($p['expiry_date']))?>
              </div>
            <?php elseif($dl<=90):?>
              <div class="fw-semibold" style="font-size:.72rem;color:#0891b2">
                <?=date('d M Y',strtotime($p['expiry_date']))?>
              </div>
              <div style="font-size:.6rem;color:#94a3b8"><?=$dl?> days</div>
            <?php else:?>
              <div style="font-size:.72rem;color:#16a34a">
                <?=date('d M Y',strtotime($p['expiry_date']))?>
              </div>
              <div style="font-size:.6rem;color:#94a3b8"><?=$dl?> days</div>
            <?php endif; else:?>
              <span class="text-muted" style="font-size:.7rem">—</span>
            <?php endif;?>
          </td>

          <!-- Cost Price -->
          <td class="text-end small"><?=$sym?><?=number_format($cost,2)?></td>

          <!-- Sell Price -->
          <td class="text-end fw-semibold"><?=$sym?><?=number_format($sell,2)?></td>

          <!-- Stock Value -->
          <td class="text-end">
            <span class="fw-semibold <?=$isOut?'text-muted':''?>"
                  style="<?=$isOut?'':''?>;font-size:.8rem">
              <?=$sym?><?=number_format($val,2)?>
            </span>
          </td>

          <!-- Status badge -->
          <td class="text-center">
            <span class="st-badge"
                  style="background:<?=$stBg?>;color:<?=$stColor?>">
              <?=$isOut?'🔴 Out':($isLow?'⚠ Low':'✅ OK')?>
            </span>
          </td>

          <!-- Actions -->
          <td class="text-center">
            <div class="d-flex gap-1 justify-content-center">
              <a href="<?=APP_URL?>/stock/movements/<?=$p['id']?>"
                 class="btn btn-sm btn-outline-info py-0 px-2" title="Movements">
                <i class="bi bi-arrow-left-right"></i>
              </a>
              <?php if(Auth::can('stock.manage')):?>
              <a href="<?=APP_URL?>/stock/adjust/<?=$p['id']?>"
                 class="btn btn-sm btn-outline-warning py-0 px-2" title="Adjust">
                <i class="bi bi-sliders"></i>
              </a>
              <?php endif;?>
            </div>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>

      <?php if(!empty($data)):?>
      <tfoot class="table-secondary fw-bold" style="font-size:.75rem">
        <?php
        $pgVal  = array_sum(array_map(fn($p)=>(float)$p['current_stock']*(float)$p['cost_price'],$data));
        $pgSell = array_sum(array_map(fn($p)=>(float)$p['current_stock']*(float)$p['selling_price'],$data));
        ?>
        <tr>
          <td colspan="8" class="ps-3">PAGE TOTAL (<?=count($data)?> products)</td>
          <td class="text-end"><?=$sym?><?=number_format($pgVal,2)?></td>
          <td colspan="2"></td>
        </tr>
        <tr style="background:#f0fdfa">
          <td colspan="8" class="ps-3 text-teal" style="color:#0d9488">
            PAGE SELL VALUE
          </td>
          <td class="text-end fw-bold" style="color:#0d9488">
            <?=$sym?><?=number_format($pgSell,2)?>
          </td>
          <td colspan="2"></td>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>

  <!-- Pagination -->
  <?php if($lastPage > 1):?>
  <div class="card-footer d-flex justify-content-between align-items-center py-2">
    <span class="text-muted small">
      Page <?=$curPage?> of <?=$lastPage?> · <?=number_format($pagination['total'])?> products
    </span>
    <nav>
      <ul class="pagination pagination-sm mb-0">
        <li class="page-item <?=$curPage<=1?'disabled':''?>">
          <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$curPage-1]))?>">‹</a>
        </li>
        <?php foreach(range(max(1,$curPage-2),min($lastPage,$curPage+2)) as $pg):?>
        <li class="page-item <?=$pg===$curPage?'active':''?>">
          <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$pg]))?>"><?=$pg?></a>
        </li>
        <?php endforeach;?>
        <li class="page-item <?=$curPage>=$lastPage?'disabled':''?>">
          <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$curPage+1]))?>">›</a>
        </li>
      </ul>
    </nav>
  </div>
  <?php endif;?>
</div>