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

<style>
.prod-hero{background:linear-gradient(135deg,#78350f,#b45309 55%,#d97706);
  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.35rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.65rem;text-transform:uppercase;letter-spacing:.05em;margin-top:3px}
.prod-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.prod-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.prod-table tr:hover td{background:#f8fafc}
.stock-bar{height:6px;border-radius:3px;background:#f1f5f9;margin-top:3px}
.stock-fill{height:6px;border-radius:3px}
.prod-img{width:36px;height:36px;border-radius:8px;object-fit:cover;
  background:#f1f5f9;display:flex;align-items:center;justify-content:center;
  flex-shrink:0;font-size:1rem}
.margin-badge{padding:2px 6px;border-radius:12px;font-size:.6rem;font-weight:700}
</style>

<!-- Hero -->
<div class="prod-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-box-seam me-2"></i>Products</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?= $totalActive ?> active &nbsp;·&nbsp;
        <span class="<?=$totalOutStock>0?'text-warning fw-bold':''?>">
          <?= $totalOutStock ?> out of stock
        </span>
        &nbsp;·&nbsp;
        <span class="<?=$totalLowStock>0?'text-warning fw-bold':''?>">
          <?= $totalLowStock ?> low stock
        </span>
        &nbsp;·&nbsp;
        Stock value: <strong><?= $sym ?><?= number_format($totalStockValue,0) ?></strong>
      </div>
    </div>
    <div class="d-flex gap-2">
      <?php if(Auth::can('products.create')):?>
      <a href="<?=APP_URL?>/products/create"
         class="btn btn-light btn-sm fw-semibold" style="color:#b45309">
        <i class="bi bi-plus-circle me-1"></i>Add Product
      </a>
      <?php endif;?>
      <a href="<?=APP_URL?>/products/barcode-labels"
         class="btn btn-outline-light btn-sm">
        <i class="bi bi-upc-scan me-1"></i>Barcode Labels
      </a>
      <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 -->
<?php
// Count expiring within 30 days and expired
$expiringSoon   = 0;
$expiredCount   = 0;
foreach ($data as $p) {
    if (!empty($p['has_expiry']) && !empty($p['expiry_date'])) {
        $dl = (int) ceil((strtotime($p['expiry_date']) - time()) / 86400);
        if ($dl < 0) $expiredCount++;
        elseif ($dl <= 30) $expiringSoon++;
    }
}
?>
<div class="row g-2 mb-3">
  <div class="col-6 col-md-2">
    <div class="kpi-pill" style="background:#fef9c3;border:2px solid #d97706">
      <div class="val" style="color:#d97706"><?= $totalActive ?></div>
      <div class="lbl" style="color:#d97706">Active</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"><?= $totalOutStock ?></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"><?= $totalLowStock ?></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:<?=$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>
  </div>
  <div class="col-6 col-md-2">
    <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>
  </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"><?=$sym?><?=number_format($totalStockValue,0)?></div>
      <div class="lbl" style="color:#16a34a">Stock Value</div>
    </div>
  </div>
</div>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/products"
          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>
      <select name="brand" class="form-select form-select-sm" style="max-width:140px">
        <option value="0">All Brands</option>
        <?php foreach($brands as $br):?>
        <option value="<?=$br['id']?>" <?=$brandId==$br['id']?'selected':''?>>
          <?=e($br['brand_name'])?>
        </option>
        <?php endforeach;?>
      </select>
      <select name="stock" class="form-select form-select-sm" style="max-width:130px">
        <option value="all" <?=$stock==='all'?'selected':''?>>All Stock</option>
        <option value="low" <?=$stock==='low'?'selected':''?>>⚠ Low Stock</option>
        <option value="out" <?=$stock==='out'?'selected':''?>>🔴 Out of Stock</option>
      </select>
      <select name="status" class="form-select form-select-sm" style="max-width:110px">
        <option value="active"  <?=$status==='active'? 'selected':''?>>✓ Active</option>
        <option value="inactive"<?=$status==='inactive'?'selected':''?>>✗ Inactive</option>
        <option value="all"     <?=$status==='all'?    'selected':''?>>All</option>
      </select>
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <a href="<?=APP_URL?>/products" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
    </form>
  </div>
</div>

<!-- Quick stock alerts -->
<?php if($totalOutStock > 0 || $totalLowStock > 0):?>
<div class="d-flex gap-2 mb-3 flex-wrap">
  <?php if($totalOutStock > 0):?>
  <a href="?stock=out" class="btn btn-sm btn-danger fw-semibold">
    <i class="bi bi-exclamation-octagon-fill me-1"></i>
    <?=$totalOutStock?> Out of Stock
  </a>
  <?php endif;?>
  <?php if($totalLowStock > 0):?>
  <a href="?stock=low" class="btn btn-sm btn-warning fw-semibold text-dark">
    <i class="bi bi-exclamation-triangle-fill me-1"></i>
    <?=$totalLowStock?> Low Stock
  </a>
  <?php endif;?>
</div>
<?php endif;?>

<!-- Products 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-box-seam me-1"></i>Product List
    </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 prod-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3" style="width:32px">#</th>
          <th>Product</th>
          <th>Category / Brand</th>
          <th class="text-end">Cost</th>
          <th class="text-end">Selling</th>
          <th class="text-center">Margin</th>
          <th class="text-center">Expiry</th>
          <th class="text-center">Stock</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="11" class="text-center text-muted py-5">
            <i class="bi bi-box-seam d-block fs-2 mb-2 opacity-25"></i>
            No products found.
            <?php if(Auth::can('products.create')):?>
            <div class="mt-2">
              <a href="<?=APP_URL?>/products/create" class="btn btn-sm btn-outline-warning">
                <i class="bi bi-plus-circle me-1"></i>Add First Product
              </a>
            </div>
            <?php endif;?>
          </td>
        </tr>
        <?php endif;?>

        <?php
        $rowNum = ($curPage-1)*$perPage;
        foreach($data as $prod):
          $rowNum++;
          $cost    = (float)$prod['cost_price'];
          $sell    = (float)$prod['selling_price'];
          $stock   = (float)$prod['current_stock'];
          $reorder = (float)($prod['reorder_level'] ?? 0);
          $margin  = $sell > 0 ? round(($sell-$cost)/$sell*100,1) : 0;
          $stockVal= round($stock*$cost,2);
          $isOut   = $stock <= 0;
          $isLow   = !$isOut && $reorder > 0 && $stock <= $reorder;
          $stockColor = $isOut?'#dc2626':($isLow?'#d97706':'#16a34a');
          $stockPct = $reorder>0 ? min(100,round($stock/$reorder*100)) : ($stock>0?100:0);
        ?>
        <tr class="<?=$prod['status']==='inactive'?'opacity-50':''?>">
          <td class="ps-3 text-muted small"><?=$rowNum?></td>

          <!-- Product -->
          <td>
            <div class="d-flex align-items-center gap-2">
              <!-- Image or icon -->
              <?php if(!empty($prod['product_image'])):?>
              <img src="<?=UPLOAD_URL?>/<?=e($prod['product_image'])?>"
                   class="prod-img" alt="">
              <?php else:?>
              <div class="prod-img" style="background:#fef9c3">
                <i class="bi bi-box-seam text-warning"></i>
              </div>
              <?php endif;?>
              <div>
                <div class="fw-semibold"><?=e($prod['product_name'])?></div>
                <div style="font-size:.65rem;color:#94a3b8">
                  <code><?=e($prod['product_code'])?></code>
                  <?php if($prod['barcode']&&$prod['barcode']!==$prod['product_code']):?>
                  &nbsp;·&nbsp;<i class="bi bi-upc me-1"></i><?=e($prod['barcode'])?>
                  <?php endif;?>
                </div>
                <?php if($prod['unit_short']):?>
                <span style="background:#f1f5f9;border-radius:4px;padding:1px 5px;
                             font-size:.6rem;color:#64748b">
                  <?=e($prod['unit_short'])?>
                </span>
                <?php endif;?>
              </div>
            </div>
          </td>

          <!-- Category / Brand -->
          <td>
            <?php if($prod['category_name']):?>
            <div class="small fw-semibold"><?=e($prod['category_name'])?></div>
            <?php endif;?>
            <?php if($prod['brand_name']):?>
            <div style="font-size:.65rem;color:#94a3b8"><?=e($prod['brand_name'])?></div>
            <?php endif;?>
          </td>

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

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

          <!-- Margin -->
          <td class="text-center">
            <span class="margin-badge"
                  style="background:<?=$margin>=20?'#dcfce7':($margin>=10?'#fef9c3':'#fee2e2')?>;
                         color:<?=$margin>=20?'#15803d':($margin>=10?'#854d0e':'#dc2626')?>">
              <?=$margin?>%
            </span>
          </td>

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

          <!-- Stock -->
          <td class="text-center">
            <div class="fw-bold" style="color:<?=$stockColor?>;font-size:.85rem">
              <?=number_format($stock,0)?>
              <?php if($isOut):?>
              <span style="font-size:.6rem">🔴 OUT</span>
              <?php elseif($isLow):?>
              <span style="font-size:.6rem">⚠ LOW</span>
              <?php endif;?>
            </div>
            <?php if($reorder > 0):?>
            <div class="stock-bar" style="max-width:60px;margin:2px auto">
              <div class="stock-fill"
                   style="width:<?=min(100,$stockPct)?>%;background:<?=$stockColor?>">
              </div>
            </div>
            <div style="font-size:.6rem;color:#94a3b8">Min: <?=number_format($reorder,0)?></div>
            <?php endif;?>
          </td>

          <!-- Stock Value -->
          <td class="text-end small text-muted">
            <?=$sym?><?=number_format($stockVal,2)?>
          </td>

          <!-- Status -->
          <td class="text-center">
            <span class="badge <?=$prod['status']==='active'?'bg-success':'bg-secondary'?>"
                  style="font-size:.62rem">
              <?=ucfirst($prod['status'])?>
            </span>
          </td>

          <!-- Actions -->
          <td class="text-center">
            <div class="d-flex gap-1 justify-content-center">
              <?php if(Auth::can('products.edit')):?>
              <a href="<?=APP_URL?>/products/edit/<?=$prod['id']?>"
                 class="btn btn-sm btn-outline-primary py-0 px-2" title="Edit">
                <i class="bi bi-pencil"></i>
              </a>
              <?php endif;?>
              <a href="<?=APP_URL?>/products/barcode/<?=$prod['id']?>" target="_blank"
                 class="btn btn-sm btn-outline-dark py-0 px-2" title="Print Barcode Label">
                <i class="bi bi-upc-scan"></i>
              </a>
              <?php if(Auth::can('products.delete')):?>
              <form method="POST" action="<?=APP_URL?>/products/delete/<?=$prod['id']?>"
                    onsubmit="return confirm('Delete <?=e($prod['product_name'])?>?')">
                <?=Auth::csrfField()?>
                <button class="btn btn-sm btn-outline-danger py-0 px-1" title="Delete">
                  <i class="bi bi-trash3"></i>
                </button>
              </form>
              <?php endif;?>
            </div>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>

      <?php if(!empty($data)):?>
      <tfoot class="table-secondary fw-bold" style="font-size:.75rem">
        <tr>
          <td colspan="7" class="ps-3">PAGE TOTAL (<?=count($data)?>)</td>
          <td class="text-end"><?=$sym?><?=number_format(
            array_sum(array_map(fn($p)=>(float)$p['current_stock']*(float)$p['cost_price'],$data)),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 $p):?>
        <li class="page-item <?=$p===$curPage?'active':''?>">
          <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$p]))?>"><?=$p?></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>