<?php
include 'db.php';
session_start();
/* ================= AJAX BATCHES ================= */
if(isset($_GET['ajax_batches']) && isset($_GET['product_id'])){

  $product_id = intval($_GET['product_id']);

  $res = $conn->query("
  SELECT 
      pi.purchase_item_id,
      pi.qty,
      pi.expiry_date,
      pi.cost,
      p.purchase_no,
      p.purchase_date,
      'Purchase' AS stock_type
  FROM purchase_items pi
  LEFT JOIN purchases p 
      ON p.purchase_id = pi.purchase_id
  WHERE pi.product_id = $product_id

UNION ALL


SELECT
    pb.purchase_item_id,
    pb.qty_remaining AS qty,
    pb.expiry_date,
    pb.purchase_price AS cost,
    'Opening Stock' AS purchase_no,
    'Initial' AS purchase_date,
    'Opening Stock' AS stock_type
FROM product_batches pb
WHERE pb.product_id = $product_id
AND pb.purchase_item_id IS NULL
AND pb.qty_remaining > 0

ORDER BY 
    stock_type ASC,
    expiry_date ASC
  ");


  if(!$res){
      echo json_encode([
          "error"=>$conn->error
      ]);
      exit;
  }


  $batches = [];
  $total_cost = 0;
  $total_qty = 0;


  while($r = $res->fetch_assoc()){

      $line_cost = $r['qty'] * $r['cost'];

      $r['batch_id'] = $r['purchase_item_id'];
      $r['qty_remaining'] = $r['qty'];
      $r['purchase_price'] = $r['cost'];
      $r['cost'] = $line_cost;


      $total_cost += $line_cost;
      $total_qty += $r['qty'];


      $batches[] = $r;
  }


  echo json_encode([
      "batches"=>$batches,
      "total_qty"=>$total_qty,
      "total_cost"=>$total_cost
  ]);

  exit;

}

$low_stock_threshold = 4;
$expiry_soon_days = 180;
$products = $conn->query("SELECT p.*, u.unit_name FROM products p LEFT JOIN units u ON p.unit_id = u.unit_id");
$out_stock=[];$low_stock=[];$expired=[];$soon=[];$all=[];
$total_stock_value=0;$total_profit_all=0;
$today = date('Y-m-d');
while($p = $products->fetch_assoc()){
    $purchase=$p['purchase_price'];$sale=$p['sale_price'];$stock=$p['stock'];
    $stock_value=$stock*$purchase;$profit=($sale-$purchase)*$stock;
    $p['value']=$stock_value;$p['profit']=$profit;
    $total_stock_value+=$stock_value;$total_profit_all+=$profit;
    $exp=$conn->query("
    SELECT MIN(expiry_date) as exp 
    FROM product_batches 
    WHERE product_id={$p['product_id']}
    AND qty_remaining > 0
    ")->fetch_assoc();
    $p['expiry']=$exp['exp'];
    $all[]=$p;
    if($p['stock']==0) $out_stock[]=$p;
    elseif($p['stock']<=$low_stock_threshold) $low_stock[]=$p;
    if($p['expiry']&&$p['expiry']<$today) $expired[]=$p;
    elseif($p['expiry']&&$p['expiry']<=date('Y-m-d',strtotime("+$expiry_soon_days days"))) $soon[]=$p;
}
$c_out=count($out_stock);$c_low=count($low_stock);$c_exp=count($expired);$c_soon=count($soon);$c_all=count($all);
$type=$_GET['view']??'all';
$list=$all;
if($type=='out') $list=$out_stock;
if($type=='low') $list=$low_stock;
if($type=='exp') $list=$expired;
if($type=='soon') $list=$soon;
?>
<!DOCTYPE html>
<html lang="ps" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stock Dashboard</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/all.min.css">
<style>
:root {
  --bg-deep:    #060b17;
  --bg-mid:     #0d1626;
  --bg-card:    #111d30;
  --bg-glass:   rgba(17,29,48,0.7);
  --border:     rgba(255,255,255,0.07);
  --border-glow:rgba(255,255,255,0.14);
  --text-primary:#f0f4ff;
  --text-muted:  #6a7d9e;
  --text-dim:    #3a4d68;
  --accent-red:  #ff4560;
  --accent-orange:#ff9500;
  --accent-blue: #3b82f6;
  --accent-cyan: #06b6d4;
  --accent-green:#10d97e;
  --accent-purple:#8b5cf6;
  --glow-red:    rgba(255,69,96,0.3);
  --glow-orange: rgba(255,149,0,0.3);
  --glow-blue:   rgba(59,130,246,0.3);
  --glow-green:  rgba(16,217,126,0.3);
}

*{box-sizing:border-box;margin:0;padding:0;}

body {
  background: var(--bg-deep);
  color: var(--text-primary);
  font-family: 'DM Sans', sans-serif;
  min-height: 100vh;
  overflow-x: hidden;
}

/* ---- BACKGROUND ---- */
body::before {
  content:'';
  position:fixed;
  inset:0;
  background:
    radial-gradient(ellipse 80% 50% at 10% -10%, rgba(59,130,246,0.12) 0%, transparent 60%),
    radial-gradient(ellipse 60% 40% at 90% 100%, rgba(139,92,246,0.1) 0%, transparent 55%),
    radial-gradient(ellipse 40% 30% at 50% 50%, rgba(6,182,212,0.05) 0%, transparent 70%);
  pointer-events:none;
  z-index:0;
}

.container{position:relative;z-index:1;}

/* ---- TOP BAR ---- */
.top-bar {
  display:flex;
  justify-content:space-between;
  align-items:center;
  padding: 24px 0 28px;
  border-bottom: 1px solid var(--border);
  margin-bottom: 32px;
}

.page-title {
  font-family: 'Syne', sans-serif;
  font-size: 1.5rem;
  font-weight: 800;
  letter-spacing: -0.02em;
  color: var(--text-primary);
  display:flex;
  align-items:center;
  gap: 12px;
}

.page-title span.dot {
  display:inline-block;
  width:8px;height:8px;
  border-radius:50%;
  background: var(--accent-cyan);
  box-shadow: 0 0 10px var(--accent-cyan);
  animation: pulse-dot 2s ease-in-out infinite;
}

@keyframes pulse-dot {
  0%,100%{opacity:1;transform:scale(1);}
  50%{opacity:.5;transform:scale(0.7);}
}

.back-btn {
  display:inline-flex;
  align-items:center;
  gap: 8px;
  background: var(--bg-card);
  border: 1px solid var(--border);
  color: var(--text-muted);
  font-family:'DM Sans',sans-serif;
  font-size:0.85rem;
  font-weight:500;
  padding: 9px 18px;
  border-radius: 10px;
  text-decoration:none;
  transition: all .25s ease;
}

.back-btn:hover {
  background: rgba(59,130,246,0.12);
  border-color: rgba(59,130,246,0.4);
  color: #93c5fd;
  transform: translateX(-3px);
}

/* ---- STAT CARDS ---- */
.stat-cards {
  display:grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 14px;
  margin-bottom: 28px;
}

@media(max-width:900px){
  .stat-cards{grid-template-columns:repeat(3,1fr);}
}

.stat-card {
  position:relative;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 18px;
  padding: 22px 16px 18px;
  text-decoration:none;
  cursor:pointer;
  overflow:hidden;
  transition: transform .3s cubic-bezier(.34,1.56,.64,1), box-shadow .3s ease, border-color .3s ease;
  display:block;
}

.stat-card::before {
  content:'';
  position:absolute;
  inset:0;
  border-radius:18px;
  opacity:0;
  transition:opacity .3s;
}

.stat-card:hover {
  transform: translateY(-6px) scale(1.02);
}

.stat-card:hover::before{opacity:1;}

/* card colors */
.stat-card.c-red   { --clr:var(--accent-red);   --glow:var(--glow-red); }
.stat-card.c-orange{ --clr:var(--accent-orange); --glow:var(--glow-orange); }
.stat-card.c-blue  { --clr:var(--accent-blue);   --glow:var(--glow-blue); }
.stat-card.c-cyan  { --clr:var(--accent-cyan);   --glow:rgba(6,182,212,0.3); }
.stat-card.c-green { --clr:var(--accent-green);  --glow:var(--glow-green); }

.stat-card:hover{
  border-color: var(--clr);
  box-shadow: 0 8px 30px var(--glow), 0 0 0 1px var(--clr);
}

.stat-card-glow {
  position:absolute;
  width:120px;height:120px;
  border-radius:50%;
  background: var(--clr);
  opacity:.08;
  top:-30px;right:-30px;
  filter:blur(30px);
  transition: opacity .3s;
}

.stat-card:hover .stat-card-glow{opacity:.18;}

.stat-card-icon {
  width:38px;height:38px;
  border-radius:10px;
  display:flex;align-items:center;justify-content:center;
  background: rgba(255,255,255,0.05);
  border:1px solid var(--border);
  font-size:15px;
  color: var(--clr);
  margin-bottom:14px;
  transition: background .3s, border-color .3s;
}

.stat-card:hover .stat-card-icon{
  background: rgba(255,255,255,0.1);
  border-color: var(--clr);
}

.stat-card-count {
  font-family:'Syne',sans-serif;
  font-size:2.1rem;
  font-weight:800;
  line-height:1;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.stat-card-label {
  font-size:0.78rem;
  font-weight:500;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing:0.08em;
}

.stat-card-bar {
  position:absolute;
  bottom:0;left:0;right:0;
  height:3px;
  background: var(--clr);
  opacity:0;
  transition:opacity .3s;
  border-radius:0 0 18px 18px;
}

.stat-card:hover .stat-card-bar{opacity:1;}

/* ---- SUMMARY STRIP ---- */
.summary-strip {
  display:grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 14px;
  margin-bottom: 24px;
}

.summary-cell {
  background: var(--bg-glass);
  border: 1px solid var(--border);
  border-radius: 14px;
  padding: 16px 20px;
  backdrop-filter:blur(8px);
  display:flex;
  align-items:center;
  gap:14px;
}

.summary-cell-icon {
  width:42px;height:42px;min-width:42px;
  border-radius:10px;
  display:flex;align-items:center;justify-content:center;
  font-size:16px;
}

.summary-cell-icon.val  { background:rgba(59,130,246,0.15); color:var(--accent-blue); }
.summary-cell-icon.prof { background:rgba(16,217,126,0.15); color:var(--accent-green); }
.summary-cell-icon.prod { background:rgba(139,92,246,0.15); color:var(--accent-purple); }

.summary-cell-body {}
.summary-cell-label {
  font-size:0.72rem;
  font-weight:500;
  color:var(--text-muted);
  text-transform:uppercase;
  letter-spacing:0.07em;
  margin-bottom:3px;
}

.summary-cell-value {
  font-family:'Syne',sans-serif;
  font-size:1.15rem;
  font-weight:700;
  color:var(--text-primary);
}

/* ---- SEARCH ---- */
.search-wrap {
  position:relative;
  margin-bottom: 20px;
}

.search-wrap i {
  position:absolute;
  top:50%;
  right:16px;
  transform:translateY(-50%);
  color:var(--text-muted);
  font-size:14px;
  pointer-events:none;
}

.search-input {
  width:100%;
  background: var(--bg-card);
  border: 1px solid var(--border);
  color: var(--text-primary);
  padding: 13px 44px 13px 18px;
  border-radius: 12px;
  font-family:'DM Sans',sans-serif;
  font-size:0.9rem;
  outline:none;
  transition: border-color .25s, box-shadow .25s;
}

.search-input::placeholder{color:var(--text-dim);}
.search-input:focus {
  border-color: rgba(59,130,246,0.5);
  box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
}

/* ---- TABLE WRAPPER ---- */
.table-wrap {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 18px;
  overflow:hidden;
  box-shadow: 0 4px 30px rgba(0,0,0,0.3);
}

.table-wrap table {
  width:100%;
  border-collapse:collapse;
  color: var(--text-primary) !important;
}

.table-wrap thead tr {
  background: rgba(255,255,255,0.03);
  border-bottom: 1px solid var(--border);
}

.table-wrap thead th {
  padding: 14px 18px;
  font-family:'Syne',sans-serif;
  font-size:0.72rem;
  font-weight:600;
  text-transform:uppercase;
  letter-spacing:0.1em;
  color: var(--text-muted);
  white-space:nowrap;
}

.table-wrap tbody tr {
  border-bottom: 1px solid var(--border);
  transition: background .2s;
  cursor:pointer;
}

.table-wrap tbody tr:last-child{border-bottom:none;}

.table-wrap tbody tr:hover {
  background: rgba(59,130,246,0.08) !important;
}

.table-wrap tbody td {
  padding: 13px 18px;
  font-size:0.88rem;
  font-weight:400;
  color: var(--text-primary);
}

.td-product-name {
  font-weight:600;
  color:var(--text-primary);
}

.td-stock {
  font-family:'Syne',sans-serif;
  font-weight:700;
}

.stock-badge {
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:38px;
  padding:3px 8px;
  border-radius:8px;
  font-size:0.82rem;
  font-weight:700;
}

.stock-ok   { background:rgba(16,217,126,0.12); color:var(--accent-green); border:1px solid rgba(16,217,126,0.2); }
.stock-low  { background:rgba(255,149,0,0.12);  color:var(--accent-orange);border:1px solid rgba(255,149,0,0.2); }
.stock-out  { background:rgba(255,69,96,0.12);  color:var(--accent-red);   border:1px solid rgba(255,69,96,0.2); }

.profit-val {
  color:var(--accent-green);
  font-weight:600;
}

.expiry-badge {
  display:inline-flex;
  align-items:center;
  gap:5px;
  font-size:0.8rem;
  padding:3px 9px;
  border-radius:7px;
  background:rgba(255,255,255,0.04);
  border:1px solid var(--border);
  color:var(--text-muted);
}

.expiry-danger  { background:rgba(255,69,96,0.1);   color:var(--accent-red);    border-color:rgba(255,69,96,0.2); }
.expiry-warning { background:rgba(255,149,0,0.1);   color:var(--accent-orange); border-color:rgba(255,149,0,0.2); }

/* ---- MODAL OVERLAY ---- */
#modal {
  display:none;
  position:fixed;
  inset:0;
  background:rgba(0,0,0,.75);
  backdrop-filter:blur(6px);
  z-index:1000;
  overflow-y:auto;
}

.modal-wrap {
  max-width:860px;
  margin:40px auto;
  padding:0 16px 60px;
}

.modal-box {
  background: var(--bg-mid);
  border: 1px solid var(--border-glow);
  border-radius: 22px;
  overflow:hidden;
  box-shadow: 0 30px 80px rgba(0,0,0,.6), 0 0 0 1px rgba(255,255,255,0.04);
  animation: modal-pop .35s cubic-bezier(.34,1.56,.64,1);
}

@keyframes modal-pop {
  from{opacity:0;transform:scale(.94) translateY(20px);}
  to{opacity:1;transform:scale(1) translateY(0);}
}

.modal-header {
  padding:22px 28px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  border-bottom:1px solid var(--border);
  background: rgba(255,255,255,0.02);
}

.modal-title {
  font-family:'Syne',sans-serif;
  font-size:1rem;
  font-weight:700;
  display:flex;
  align-items:center;
  gap:10px;
  color:var(--text-primary);
}

.modal-title-icon {
  width:32px;height:32px;
  background:rgba(59,130,246,0.15);
  border:1px solid rgba(59,130,246,0.3);
  border-radius:8px;
  display:flex;align-items:center;justify-content:center;
  font-size:13px;
  color:var(--accent-blue);
}

.modal-close {
  width:34px;height:34px;
  background:rgba(255,69,96,0.1);
  border:1px solid rgba(255,69,96,0.25);
  border-radius:9px;
  color:var(--accent-red);
  font-size:14px;
  cursor:pointer;
  display:flex;align-items:center;justify-content:center;
  transition:background .2s, transform .2s;
  outline:none;
}

.modal-close:hover{background:rgba(255,69,96,0.2);transform:scale(1.1);}

.modal-body { padding: 24px 28px; }

/* modal summary */
.modal-summary {
  display:grid;
  grid-template-columns:repeat(3,1fr);
  gap:12px;
  margin-bottom:24px;
}

.modal-stat {
  background:rgba(255,255,255,0.03);
  border:1px solid var(--border);
  border-radius:12px;
  padding:14px 16px;
  text-align:center;
}

.modal-stat-label {
  font-size:0.7rem;
  text-transform:uppercase;
  letter-spacing:0.08em;
  color:var(--text-muted);
  margin-bottom:6px;
}

.modal-stat-value {
  font-family:'Syne',sans-serif;
  font-size:1.2rem;
  font-weight:700;
  color:var(--text-primary);
}

.modal-stat.s-green .modal-stat-value{color:var(--accent-green);}
.modal-stat.s-blue  .modal-stat-value{color:var(--accent-blue);}
.modal-stat.s-orange.modal-stat-value{color:var(--accent-orange);}

/* modal table */
.modal-table-wrap{
  border:1px solid var(--border);
  border-radius:12px;
  overflow:hidden;
}

.modal-table-wrap table{
  width:100%;
  border-collapse:collapse;
  color:var(--text-primary) !important;
}

.modal-table-wrap thead th{
  background:rgba(255,255,255,0.03);
  padding:11px 16px;
  font-family:'Syne',sans-serif;
  font-size:0.7rem;
  font-weight:600;
  letter-spacing:0.09em;
  text-transform:uppercase;
  color:var(--text-muted);
  border-bottom:1px solid var(--border);
}

.modal-table-wrap tbody td{
  padding:11px 16px;
  font-size:0.85rem;
  border-bottom:1px solid var(--border);
}

.modal-table-wrap tbody tr:last-child td{border-bottom:none;}
.modal-table-wrap tbody tr:hover{background:rgba(255,255,255,0.03);}

/* scrollbar */
::-webkit-scrollbar{width:6px;height:6px;}
::-webkit-scrollbar-track{background:transparent;}
::-webkit-scrollbar-thumb{background:rgba(255,255,255,0.1);border-radius:4px;}

/* stagger animation */
.stat-card{opacity:0;transform:translateY(20px);animation:slide-up .5s ease forwards;}
.stat-card:nth-child(1){animation-delay:.05s;}
.stat-card:nth-child(2){animation-delay:.1s;}
.stat-card:nth-child(3){animation-delay:.15s;}
.stat-card:nth-child(4){animation-delay:.2s;}
.stat-card:nth-child(5){animation-delay:.25s;}

.summary-strip{opacity:0;animation:slide-up .5s ease .35s forwards;}
.table-wrap{opacity:0;animation:slide-up .5s ease .45s forwards;}

@keyframes slide-up{
  from{opacity:0;transform:translateY(20px);}
  to{opacity:1;transform:translateY(0);}
}
</style>
</head>
<body>

<div class="container" style="max-width:1200px;padding:0 20px;">

  <!-- TOP BAR -->
  <div class="top-bar">
    <div class="page-title">
      <span class="dot"></span>
      POS Stock Dashboard
    </div>
    <a href="index.php" class="back-btn">
      <i class="fas fa-arrow-right"></i>
      Back to Dashboard
    </a>
  </div>

  <!-- STAT CARDS -->
  <div class="stat-cards">

    <a href="?view=out" class="stat-card c-red text-decoration-none">
      <div class="stat-card-glow"></div>
      <div class="stat-card-icon"><i class="fas fa-times-circle"></i></div>
      <div class="stat-card-count"><?= $c_out ?></div>
      <div class="stat-card-label">Out of Stock</div>
      <div class="stat-card-bar"></div>
    </a>

    <a href="?view=low" class="stat-card c-orange text-decoration-none">
      <div class="stat-card-glow"></div>
      <div class="stat-card-icon"><i class="fas fa-exclamation-triangle"></i></div>
      <div class="stat-card-count"><?= $c_low ?></div>
      <div class="stat-card-label">Low Stock</div>
      <div class="stat-card-bar"></div>
    </a>

    <a href="?view=exp" class="stat-card c-red text-decoration-none">
      <div class="stat-card-glow"></div>
      <div class="stat-card-icon"><i class="fas fa-calendar-times"></i></div>
      <div class="stat-card-count"><?= $c_exp ?></div>
      <div class="stat-card-label">Expired</div>
      <div class="stat-card-bar"></div>
    </a>

    <a href="?view=soon" class="stat-card c-orange text-decoration-none">
      <div class="stat-card-glow"></div>
      <div class="stat-card-icon"><i class="fas fa-hourglass-half"></i></div>
      <div class="stat-card-count"><?= $c_soon ?></div>
      <div class="stat-card-label">Expiring Soon</div>
      <div class="stat-card-bar"></div>
    </a>

    <a href="?view=all" class="stat-card c-blue text-decoration-none">
      <div class="stat-card-glow"></div>
      <div class="stat-card-icon"><i class="fas fa-boxes"></i></div>
      <div class="stat-card-count"><?= $c_all ?></div>
      <div class="stat-card-label">All Products</div>
      <div class="stat-card-bar"></div>
    </a>

  </div>

  <!-- SUMMARY STRIP -->
  <div class="summary-strip">
    <div class="summary-cell">
      <div class="summary-cell-icon val"><i class="fas fa-wallet"></i></div>
      <div class="summary-cell-body">
        <div class="summary-cell-label">Total Stock Value</div>
        <div class="summary-cell-value"><?= number_format($total_stock_value,2) ?></div>
      </div>
    </div>
    <div class="summary-cell">
      <div class="summary-cell-icon prof"><i class="fas fa-chart-line"></i></div>
      <div class="summary-cell-body">
        <div class="summary-cell-label">Total Profit</div>
        <div class="summary-cell-value" style="color:var(--accent-green)"><?= number_format($total_profit_all,2) ?></div>
      </div>
    </div>
    <div class="summary-cell">
      <div class="summary-cell-icon prod"><i class="fas fa-cube"></i></div>
      <div class="summary-cell-body">
        <div class="summary-cell-label">Total Products</div>
        <div class="summary-cell-value"><?= $c_all ?></div>
      </div>
    </div>
  </div>

  <!-- SEARCH -->
  <div class="search-wrap">
    <i class="fas fa-search"></i>
    <input type="text" id="searchInput" class="search-input" placeholder="Search product by name...">
  </div>

  <!-- TABLE -->
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>Product</th>
          <th>Stock</th>
          <th>Purchase</th>
          <th>Sale Price</th>
          <th>Profit</th>
          <th>Stock Value</th>
          <th>Nearest Expiry</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($list as $p):
          $stockClass = $p['stock']==0 ? 'stock-out' : ($p['stock']<=$low_stock_threshold ? 'stock-low' : 'stock-ok');
          $expiryClass = '';
          $expiryIcon = 'fa-calendar-alt';
          if($p['expiry'] && $p['expiry'] < $today){ $expiryClass='expiry-danger'; $expiryIcon='fa-calendar-times'; }
          elseif($p['expiry'] && $p['expiry'] <= date('Y-m-d',strtotime("+$expiry_soon_days days"))){ $expiryClass='expiry-warning'; $expiryIcon='fa-exclamation-circle'; }
        ?>
        <tr onclick="openBatches(<?= $p['product_id'] ?>)">
          <td class="td-product-name"><?= htmlspecialchars($p['name']) ?></td>
          <td><span class="stock-badge <?= $stockClass ?>"><?= $p['stock'] ?></span></td>
          <td><?= number_format($p['purchase_price'],2) ?></td>
          <td><?= number_format($p['sale_price'],2) ?></td>
          <td class="profit-val"><?= number_format($p['profit'],2) ?></td>
          <td><?= number_format($p['value'],2) ?></td>
          <td>
            <?php if($p['expiry']): ?>
            <span class="expiry-badge <?= $expiryClass ?>">
              <i class="fas <?= $expiryIcon ?>"></i>
              <?= $p['expiry'] ?>
            </span>
            <?php else: ?>
            <span style="color:var(--text-dim);">—</span>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

</div>

<!-- MODAL -->
<div id="modal">
  <div class="modal-wrap">
    <div class="modal-box">
      <div class="modal-header">
        <div class="modal-title">
          <div class="modal-title-icon"><i class="fas fa-layer-group"></i></div>
          Batch-Wise Breakdown
        </div>
        <button class="modal-close" onclick="closeModal()"><i class="fas fa-times"></i></button>
      </div>
      <div class="modal-body">
        <div id="modal-summary" class="modal-summary"></div>
        <div class="modal-table-wrap">
          <table>
          <thead>
          <tr>
    <th>Purchase No</th>
    <th>Purchase Date</th>
    <th>Batch ID</th>
    <th>Qty Remaining</th>
    <th>Expiry Date</th>
    <th>Purchase Cost</th>
    <th>Est. Value</th>
    <th>Profit</th>
</tr>
</thead>
            <tbody id="batchBody"></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="assets/js/jquery.min.js"></script>
<script>
$('#searchInput').on('keyup', function(){
  var v = $(this).val().toLowerCase();
  $('.table-wrap tbody tr').filter(function(){
    $(this).toggle($(this).text().toLowerCase().indexOf(v) > -1);
  });
});

function openBatches(id){
  $.get("stock.php", {ajax_batches:1, product_id:id}, function(res){
    console.log(res);
    var data = JSON.parse(res);
    var html = '';
    var costTotal = 0;
    var qtyTotal = 0;
    var profitTotal = 0;

    data.batches.forEach(function(b){
      var cost  = b.cost;
      var value = cost * 1.25;
      var profit = value - cost;
      costTotal   += cost;
      qtyTotal    += parseFloat(b.qty_remaining);
      profitTotal += profit;
      html += '<tr>'
  + '<td style="font-family:\'Syne\',sans-serif;font-weight:700;color:#93c5fd">' 
  + (b.purchase_no ?? 'N/A') 
  + '</td>'
  + '<td>' 
  + (b.purchase_date ?? 'N/A') 
  + '</td>'
  + '<td>'
  + b.batch_id
  + '</td>'
  + '<td>' + b.qty_remaining + '</td>'
  + '<td>'
      + (b.expiry_date
          ? '<span class="expiry-badge">' + b.expiry_date + '</span>'
          : '<span style="color:#888;">N/A</span>')
  + '</td>'
  + '<td>' + cost.toFixed(2) + '</td>'
  + '<td>' + value.toFixed(2) + '</td>'
  + '<td style="color:#10d97e;font-weight:600">' + profit.toFixed(2) + '</td>'
  + '</tr>';
    });

    $('#batchBody').html(html);
    $('#modal-summary').html(
      '<div class="modal-stat s-blue">'
        + '<div class="modal-stat-label">Total Qty</div>'
        + '<div class="modal-stat-value">' + qtyTotal + '</div>'
      + '</div>'
      + '<div class="modal-stat">'
        + '<div class="modal-stat-label">Total Cost</div>'
        + '<div class="modal-stat-value">' + costTotal.toFixed(2) + '</div>'
      + '</div>'
      + '<div class="modal-stat s-green">'
        + '<div class="modal-stat-label">Total Profit</div>'
        + '<div class="modal-stat-value">' + profitTotal.toFixed(2) + '</div>'
      + '</div>'
    );

    $('#modal').fadeIn(200);
  });
}

function closeModal(){
  $('#modal').fadeOut(200);
}

$('#modal').on('click', function(e){
  if($(e.target).is('#modal')) closeModal();
});
</script>

</body>
</html>