<?php
// items.php (full) - grouped by name (case-insensitive, trimmed) + detailed weight breakdown lines
require 'header.php';
require 'db.php';
require 'unit_converters.php';

// allowed categories (used for filter dropdown and cards)
$allowedCats = ['gold' => 'Gold', 'silver' => 'silver', 'diamond' => 'diamond'];

// get category filter from GET (server-side)
$filterCat = null;
if (isset($_GET['category']) && array_key_exists($_GET['category'], $allowedCats)) {
    $filterCat = $_GET['category'];
}

// fetch all items (apply category filter if set)
if ($filterCat) {
    $stmt = $conn->prepare("SELECT * FROM stock WHERE category = ? ORDER BY id DESC");
    $stmt->bind_param('s', $filterCat);
    $ok = $stmt->execute();
    $res = $ok ? $stmt->get_result() : false;
} else {
    $res = $conn->query("SELECT * FROM stock ORDER BY id DESC");
}
if ($res === false) {
    error_log("Query failed: " . $conn->error);
    $items = [];
} else {
    $items = $res->fetch_all(MYSQLI_ASSOC);
}

/*
 Grouping logic:
 - normalize name by trimming, collapsing spaces, and lowercasing (mb_strtolower)
 - use normalized name as grouping key so "Ring", " ring ", "RING" -> same group
 - display name will be the first-original-name encountered for that group
*/
$groups = []; // key => ['display_name'=>'','total_qty'=>int,'total_g'=>float,'items'=>[]]
foreach ($items as $it) {
    $rawName = (string)($it['name'] ?? '');
    $trim = trim($rawName);
    if ($trim === '') $trim = '(unnamed)';
    // collapse internal whitespace to single space
    $collapsed = preg_replace('/\s+/u', ' ', $trim);
    // normalization key: lowercase (mb) for unicode safety
    $key = mb_strtolower($collapsed, 'UTF-8');

    if (!isset($groups[$key])) {
        $groups[$key] = [
            'display_name' => $collapsed,
            'total_qty' => 0,
            'total_g' => 0.0,
            'items' => []
        ];
    }
    $qty = intval($it['quantity'] ?? 0);
    $wg = floatval($it['weight_g'] ?? 0.0);
    $groups[$key]['total_qty'] += $qty;
    $groups[$key]['total_g'] += $wg;
    $groups[$key]['items'][] = $it;
}

// optional: sort groups by total_qty desc then display_name
uasort($groups, function($a, $b){
    if ($a['total_qty'] === $b['total_qty']) {
        return strcmp(mb_strtolower($a['display_name'],'UTF-8'), mb_strtolower($b['display_name'],'UTF-8'));
    }
    return ($a['total_qty'] > $b['total_qty']) ? -1 : 1;
});

// compute category totals for cards
$cats = ['gold'=>'Gold','silver'=>'Rupa','diamond'=>'Hira'];
$categoryTotals = [];
foreach ($cats as $key => $label) {
    $q = $conn->query("SELECT COALESCE(SUM(weight_g),0) AS total_g, COALESCE(SUM(quantity),0) AS total_qty FROM stock WHERE category='{$key}'");
    $r = $q ? $q->fetch_assoc() : ['total_g'=>0,'total_qty'=>0];
    $total_g = floatval($r['total_g'] ?? 0);
    $total_qty = intval($r['total_qty'] ?? 0);
    $units = gramsToUnits($total_g);
    $categoryTotals[$key] = [
        'label' => $label,
        'grams' => $total_g,
        'qty'   => $total_qty,
        'units' => $units
    ];
}

// overall
$overallRes = $conn->query("SELECT COALESCE(SUM(weight_g),0) AS total_g, COALESCE(SUM(quantity),0) AS total_qty FROM stock");
$overallRow = $overallRes ? $overallRes->fetch_assoc() : ['total_g'=>0,'total_qty'=>0];
$overall_total_g = floatval($overallRow['total_g'] ?? 0);
$overall_total_qty = intval($overallRow['total_qty'] ?? 0);
$overall_units = gramsToUnits($overall_total_g);

// flash
$flash = '';
if (isset($_GET['deleted']) && $_GET['deleted'] == '1') {
    $flash = '<div class="alert success">Item deleted successfully.</div>';
} elseif (isset($_GET['error'])) {
    $err = htmlspecialchars($_GET['error']);
    $flash = '<div class="alert error">Error: ' . $err . '</div>';
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Items grouped by Name</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
    body { font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, Arial; background:#f7faf9; margin:0; padding:18px; color:#0b4b46; }
    .items-wrap { max-width:1200px; margin:0 auto; padding:8px 12px 30px; }
    .header-row { display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:14px; flex-wrap:wrap; }
    .page-title { font-size:20px; font-weight:800; color:#063c3a; }
    .page-sub { color:#6b7280; font-size:13px; margin-top:4px; }

    .card-row { display:grid; grid-template-columns:repeat(3,1fr); gap:14px; margin-bottom:18px; }
    .cat-card { border-radius:12px; padding:14px; box-shadow:0 8px 24px rgba(2,6,23,0.06); background:linear-gradient(180deg,#fff,#fbfffe); display:flex; flex-direction:column; gap:8px; min-height:110px; text-decoration:none; color:inherit; }
    .cat-top { display:flex; justify-content:space-between; align-items:flex-start; }
    .cat-title { font-weight:800; font-size:15px; color:#08303a; }
    .cat-sub { color:#6b7280; font-size:13px; }
    .cat-qty { font-weight:800; font-size:18px; color:#0f766e; }
    .breakdown { display:flex; gap:8px; flex-wrap:wrap; margin-top:8px; }
    .break-item { background:rgba(255,255,255,0.85); border-radius:8px; padding:8px 10px; min-width:84px; text-align:center; box-shadow:0 6px 14px rgba(2,6,23,0.03); }
    .break-item .num { font-weight:800; font-size:16px; color:#0b4b46; }
    .break-item .lbl { color:#6b7280; font-size:12px; margin-top:4px; }

    .table-card { background:#fff; border-radius:12px; padding:12px; box-shadow:0 8px 24px rgba(2,6,23,0.04); margin-bottom:18px; }
    .groups-table { width:100%; border-collapse:collapse; }
    .groups-table thead th { background:#f1f5f9; color:#111827; padding:10px; text-align:left; font-weight:700; }
    .groups-table tbody td { padding:10px; border-bottom:1px solid #f3f4f6; vertical-align:middle; }
    .group-row { cursor:pointer; }
    .group-row:hover { background:#f8fffb; }

    .item-details { display:none; background:#fff; border-radius:8px; margin:10px 0 18px 0; padding:10px; box-shadow:0 6px 16px rgba(2,6,23,0.04); }
    .small-table { width:100%; border-collapse:collapse; }
    .small-table th, .small-table td { padding:8px; border-bottom:1px solid #f3f4f6; text-align:left; font-size:14px; }

    .actions a { margin-right:8px; text-decoration:none; padding:6px 8px; border-radius:8px; font-weight:600; font-size:13px; display:inline-block; }
    .actions .in { background:#eef2ff; color:#1e3a8a; }
    .actions .out { background:#fff7ed; color:#92400e; }
    .actions .sell { background:#ecfdf5; color:#065f46; }
    .actions .del { background:#fff1f2; color:#991b1b; }

    .alert { padding:10px; border-radius:10px; margin-bottom:12px; font-weight:600; }
    .alert.success { background:#ecfdf5; color:#065f46; }
    .alert.error { background:#fff1f2; color:#991b1b; }

    /* controls */
    select, input[type="search"] { font-size:14px; padding:6px 10px; border-radius:8px; border:1px solid #e6eef0; }

    /* ====== NEW WEIGHT BREAKDOWN STYLES ====== */
    /* weight breakdown small cards */
    .weight-grid {
      display:flex;
      flex-wrap:wrap;
      gap:8px;
      align-items:center;
    }
    .weight-box {
      background: linear-gradient(180deg,#ffffff,#fbfffe);
      border-radius:8px;
      padding:8px 10px;
      min-width:78px;
      text-align:center;
      box-shadow:0 6px 14px rgba(2,6,23,0.03);
      font-weight:700;
    }
    .weight-box .lbl { display:block; font-weight:600; font-size:12px; color:#6b7280; margin-top:4px; }
    .weight-box .val { font-size:16px; color:#0b4b46; }

    /* compact vertical stack for group row (keeps previous layout but cleaner) */
    .group-weight-compact { display:flex; gap:10px; flex-wrap:wrap; align-items:center; }
    .group-weight-compact .meta { color:#6b7280; font-size:13px; }

    /* tweak small-table center alignment */
    .small-table td .weight-grid { justify-content:center; }

    /* responsive: on small screens stack boxes */
    @media (max-width:900px) {
      .card-row { grid-template-columns:repeat(2,1fr); }
    }
    @media (max-width:600px) {
      .card-row { grid-template-columns:1fr; }
    }
    @media (max-width:480px) {
      .weight-grid { gap:6px; }
      .weight-box { min-width:60px; padding:6px 8px; font-size:14px; }
    }
    /* ====== END NEW STYLES ====== */
  </style>
</head>
<body>
<div class="items-wrap">
  <div class="header-row">
    <div>
      <div class="page-title">Items by Name (Grouped)</div>
      <div class="page-sub">Click a name to view its individual items and totals — ভরি / আনা / রটি / পয়েন্ট / গ্রাম মোট।</div>
    </div>
    <div>
      <a href="stock_in.php" class="actions in" style="text-decoration:none;">Stock In</a>
      <a href="items.php" class="actions" style="text-decoration:none;">Refresh</a>
    </div>
  </div>

  <?php echo $flash; ?>

  <!-- category cards -->
  <div class="card-row" role="list" style="margin-bottom:14px;">
    <?php foreach ($categoryTotals as $key => $data):
        $isActive = ($filterCat === $key) ? 'outline:2px solid #0b4b46;' : '';
    ?>
    <a class="cat-card" role="listitem" aria-label="<?php echo htmlspecialchars(ucfirst($key)); ?> total" href="items.php?category=<?php echo $key; ?>" style="<?php echo $isActive; ?>">
      <div class="cat-top">
        <div>
          <div class="cat-title"><?php echo htmlspecialchars(ucfirst($key)); ?></div>
          <div class="cat-sub">Pieces: <strong><?php echo $data['qty']; ?></strong></div>
        </div>
        <div style="text-align:right">
          <div class="cat-qty"><?php echo $data['units']['vori']; ?> ভরি <?php echo $data['units']['ana']; ?> আনা</div>
          <div class="cat-sub"><?php echo number_format($data['grams'],4); ?> g</div>
        </div>
      </div>

      <div class="breakdown" aria-hidden="false">
        <div class="break-item"><div class="num"><?php echo $data['units']['vori']; ?></div><div class="lbl">ভরি</div></div>
        <div class="break-item"><div class="num"><?php echo $data['units']['ana']; ?></div><div class="lbl">আনা</div></div>
        <div class="break-item"><div class="num"><?php echo $data['units']['roti']; ?></div><div class="lbl">রটি</div></div>
        <div class="break-item"><div class="num"><?php echo $data['units']['point']; ?></div><div class="lbl">পয়েন্ট</div></div>
        <div class="break-item"><div class="num"><?php echo number_format($data['grams'],4); ?></div><div class="lbl">গ্রাম মোট</div></div>
      </div>
    </a>
    <?php endforeach; ?>
  </div>

  <!-- controls -->
  <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px;flex-wrap:wrap;">
    <div>
      <form id="filterForm" method="get" action="items.php" style="margin:0;display:inline-block;">
        <label for="categoryFilter" style="font-weight:700;margin-right:6px;">Show</label>
        <select name="category" id="categoryFilter" onchange="this.form.submit();">
          <option value="">All categories</option>
          <?php foreach ($allowedCats as $k => $t): ?>
            <option value="<?php echo $k; ?>" <?php echo ($filterCat === $k) ? 'selected' : ''; ?>><?php echo ucfirst($k); ?> (<?php echo $categoryTotals[$k]['qty']; ?>)</option>
          <?php endforeach; ?>
        </select>
        <?php if ($filterCat): ?><a href="items.php" style="margin-left:8px;font-weight:700;color:#0b4b46;text-decoration:none;">Clear</a><?php endif; ?>
      </form>
    </div>

    <div>
      <label for="liveSearch" style="color:#6b7280;font-size:13px;margin-right:6px;">Search:</label>
      <input id="liveSearch" type="search" placeholder="search name, sku, category..." />
    </div>
  </div>

  <!-- Groups table (one row per unique normalized name) -->
  <div class="table-card">
    <table class="groups-table" role="table" aria-label="Groups by name">
      <thead>
        <tr>
          <th style="width:48px;">#</th>
          <th>Name</th>
          <th style="width:140px;text-align:center;">Total pieces</th>
          <th style="width:240px;text-align:left;">Total weight</th>
          <th style="width:120px;text-align:center;"># of distinct items</th>
        </tr>
      </thead>
      <tbody id="groupsTbody">
        <?php if (count($groups) === 0): ?>
          <tr><td colspan="5" style="text-align:center;padding:18px;color:#6b7280;">No items found.</td></tr>
        <?php else:
          $i = 0;
          foreach ($groups as $gkey => $gdata):
            $i++;
            $units = gramsToUnits($gdata['total_g']);
            $distinctCount = count($gdata['items']);
            // data-name uses display_name (but normalized for searching via JS toLowerCase)
            $displayNameEsc = htmlspecialchars($gdata['display_name'], ENT_QUOTES, 'UTF-8');
        ?>
        <tr class="group-row" data-name="<?php echo $displayNameEsc; ?>" data-index="<?php echo $i; ?>">
          <td><?php echo $i; ?></td>
          <td style="font-weight:700;color:#0b4b46;"><?php echo $displayNameEsc; ?></td>
          <td style="text-align:center;font-weight:800;"><?php echo $gdata['total_qty']; ?></td>

          <!-- Total weight breakdown -->
          <td>
            <div class="group-weight-compact">
              <div class="weight-grid" aria-hidden="false" style="flex-wrap:nowrap;">
                <div class="weight-box"><div class="val"><?php echo $units['vori']; ?></div><div class="lbl">ভরি</div></div>
                <div class="weight-box"><div class="val"><?php echo $units['ana']; ?></div><div class="lbl">আনা</div></div>
                <div class="weight-box"><div class="val"><?php echo $units['roti']; ?></div><div class="lbl">রটি</div></div>
                <div class="weight-box"><div class="val"><?php echo $units['point']; ?></div><div class="lbl">পয়েন্ট</div></div>
                <div class="weight-box"><div class="val"><?php echo number_format($units['grams'],4); ?></div><div class="lbl">গ্রাম মোট</div></div>
              </div>
            </div>
          </td>

          <td style="text-align:center;"><?php echo $distinctCount; ?></td>
        </tr>

        <!-- hidden details for this group (individual item rows) -->
        <tr class="item-details" id="details-<?php echo $i; ?>">
          <td colspan="5">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
              <div style="font-weight:800;color:#063c3a;">Details for: <?php echo $displayNameEsc; ?></div>
              <div style="color:#6b7280;font-weight:700;">
                <?php echo $gdata['total_qty']; ?> pcs — <?php echo number_format($gdata['total_g'],4); ?> g
              </div>
            </div>
            <table class="small-table" role="table" aria-label="Items list for <?php echo $displayNameEsc; ?>">
              <thead>
                <tr>
                  <th style="width:56px;">ID</th>
                  <th style="width:120px;">SKU</th>
                  <th>Category</th>
                  <th style="width:80px;text-align:center;">Qty</th>
                  <th style="width:160px;text-align:center;">Weight (v / a / g)</th>
                  <th style="width:140px;">Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($gdata['items'] as $it):
                  $itId = (int)$it['id'];
                  $itSku = htmlspecialchars($it['sku'], ENT_QUOTES, 'UTF-8');
                  $itCat = htmlspecialchars(ucfirst($it['category']), ENT_QUOTES, 'UTF-8');
                  $itQty = intval($it['quantity']);
                  $itW = floatval($it['weight_g'] ?? 0);
                  $itU = gramsToUnits($itW);
                ?>
                <tr>
                  <td><?php echo $itId; ?></td>
                  <td><?php echo $itSku; ?></td>
                  <td><?php echo $itCat; ?></td>
                  <td style="text-align:center;"><?php echo $itQty; ?></td>
                  <td style="text-align:center;">
                    <div class="weight-grid" style="justify-content:center;">
                      <div class="weight-box"><div class="val"><?php echo $itU['vori']; ?></div><div class="lbl">ভরি</div></div>
                      <div class="weight-box"><div class="val"><?php echo $itU['ana']; ?></div><div class="lbl">আনা</div></div>
                      <div class="weight-box"><div class="val"><?php echo $itU['roti']; ?></div><div class="lbl">রটি</div></div>
                      <div class="weight-box"><div class="val"><?php echo $itU['point']; ?></div><div class="lbl">পয়েন্ট</div></div>
                      <div class="weight-box"><div class="val"><?php echo number_format($itU['grams'],4); ?></div><div class="lbl">g</div></div>
                    </div>
                  </td>
                  <td>
                    <div class="actions" style="display:flex;gap:6px;flex-wrap:wrap;">
                      <a class="in" href="stock_in.php?id=<?php echo $itId; ?>">➕ In</a>
                      <a class="out" href="stock_out.php?id=<?php echo $itId; ?>">➖ Out</a>
                      <a class="sell" href="sell.php?id=<?php echo $itId; ?>">💰 Sell</a>
                      <a class="del" href="delete_item.php?id=<?php echo $itId; ?>&return=items.php" onclick="return confirm('Confirm delete?')">🗑 Delete</a>
                    </div>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </td>
        </tr>

        <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>

  <!-- overall summary -->
  <div style="margin-top:6px;color:#6b7280;font-size:13px;">
    Overall: <?php echo $overall_units['vori']; ?> ভরি <?php echo $overall_units['ana']; ?> আনা — <?php echo number_format($overall_units['grams'],4); ?> g — <?php echo $overall_total_qty; ?> pieces
  </div>

</div>

<script>
// Toggle details rows when group row is clicked
document.addEventListener('click', function(e) {
  var tr = e.target.closest('.group-row');
  if (!tr) return;
  var idx = tr.getAttribute('data-index');
  var details = document.getElementById('details-' + idx);
  if (!details) return;
  // collapse other open details
  document.querySelectorAll('.item-details').forEach(function(d){
    if (d !== details) d.style.display = 'none';
  });
  details.style.display = (details.style.display === 'table-row' || details.style.display === 'block') ? 'none' : 'table-row';
  // scroll into view when opening
  if (details.style.display === 'table-row' || details.style.display === 'block') details.scrollIntoView({behavior:'smooth', block:'nearest'});
});

// live search across group name, sku, category, and inside items
document.getElementById('liveSearch').addEventListener('input', function(e) {
  var q = e.target.value.trim().toLowerCase();
  document.querySelectorAll('#groupsTbody tr.group-row').forEach(function(grow) {
    var name = (grow.getAttribute('data-name') || '').toLowerCase();
    var idx = grow.getAttribute('data-index');
    var detailsRow = document.getElementById('details-' + idx);
    var match = false;
    if (!q) match = true;
    if (name.indexOf(q) !== -1) match = true;

    // search inside detail content text (SKU, category, etc)
    if (!match && detailsRow) {
      var txt = detailsRow.textContent.toLowerCase();
      if (txt.indexOf(q) !== -1) match = true;
    }

    grow.style.display = match ? '' : 'none';
    if (detailsRow) {
      // hide details when group is filtered out
      detailsRow.style.display = match && detailsRow.style.display === 'table-row' ? 'table-row' : 'none';
    }
  });
});
</script>

</body>
</html>

<?php require 'footer.php'; ?>
