<?php
require 'header.php';
require 'db.php';
require 'unit_converters.php';

/* Fetch latest sales (include category from stock when available) */
$allSales = $conn->query(
    'SELECT s.*, COALESCE(st.name, "- (deleted) -") AS item_name, COALESCE(st.category, "") AS category
     FROM sales s
     LEFT JOIN stock st ON s.stock_id = st.id
     ORDER BY s.sold_at DESC
     LIMIT 200'
);
?>

<!-- Modern colorful UI for Recent Sales -->
<style>
:root{
  --bg: #f6f8fb;
  --card: #ffffff;
  --muted: #64748b;
  --accent-blue: #2563eb;
  --accent-teal: #06b6d4;
  --accent-gold: #f59e0b;
  --accent-silver: #94a3b8;
  --accent-diamond: #a78bfa;
  --success: #16a34a;
  --radius: 12px;
  --shadow: 0 10px 30px rgba(2,6,23,0.06);
  --glass: rgba(2,6,23,0.04);
}
* { box-sizing: border-box; font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial; }
body { background: var(--bg); color: #0f172a; }
.container { max-width: 1100px; margin: 24px auto; padding: 20px; }
.header { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:14px; }
.title { font-size:1.25rem; font-weight:800; }
.subtitle { color:var(--muted); font-size:0.95rem; }
.card { background:var(--card); border-radius:var(--radius); box-shadow:var(--shadow); padding:16px; border:1px solid var(--glass); }
.controls { display:flex; gap:10px; align-items:center; margin-bottom:12px; flex-wrap:wrap; }
.input { padding:8px 10px; border-radius:10px; border:1px solid #e6eef8; min-width:220px; }
.select { padding:8px 10px; border-radius:10px; border:1px solid #e6eef8; background:transparent; }
.badge { display:inline-block; padding:6px 10px; border-radius:999px; font-weight:700; font-size:0.85rem; color:white; }
.badge.gold { background: linear-gradient(90deg,var(--accent-gold), #f97316); color:#2b1500; }
.badge.silver { background: linear-gradient(90deg,var(--accent-silver), #cbd5e1); color:#062023; }
.badge.diamond { background: linear-gradient(90deg,var(--accent-diamond), #7c3aed); color:white; }
.badge.unknown { background:#e2e8f0; color:#1f2937; }

/* Table */
.table-wrap { overflow:auto; border-radius:10px; border:1px solid #eef2ff; }
table { width:100%; border-collapse:collapse; min-width:860px; }
thead th { position: sticky; top:0; background: linear-gradient(180deg,#ffffff,#fbfdff); z-index:2; padding:12px; text-align:left; font-weight:700; color:#0f172a; border-bottom:1px solid #e6eef8; }
tbody td { padding:12px; border-bottom:1px solid #f1f5f9; vertical-align:middle; color:#0f172a; }
tbody tr:nth-child(even) { background: #fbfdff; }
.small-muted { color:var(--muted); font-size:0.9rem; }

/* responsive column sizing */
.col-id { width:60px; }
.col-item { width:36%; }
.col-qty { width:80px; text-align:center; }
.col-weight { width:200px; }
.col-time { width:220px; }

/* utility */
.chips { display:flex; gap:8px; align-items:center; }
.kv { color:var(--muted); font-size:0.92rem; }

/* mobile */
@media(max-width:880px){
  thead { display:none; }
  table, tbody, tr, td { display:block; width:100%; }
  tr { margin-bottom:12px; border-radius:10px; background:var(--card); box-shadow:var(--shadow); padding:10px; }
  td { padding:6px 0; border-bottom:none; }
  td::before { content: attr(data-label); display:block; font-weight:700; color:var(--muted); margin-bottom:6px; }
  .col-time, .col-id { display:none; }
  .table-wrap { border:none; box-shadow:none; }
}

/* search highlight */
.row-highlight { background: linear-gradient(90deg, rgba(99,102,241,0.06), rgba(6,182,212,0.03)); }
.empty-note { padding:18px; text-align:center; color:var(--muted); }
</style>

<div class="container">
  <div class="header">
    <div>
      <div class="title">Recent Sales</div>
      <div class="subtitle">Latest sales (no prices shown). Showing up to 200 recent records.</div>
    </div>

    <div class="kv">Total shown: <?php echo $allSales->num_rows ?></div>
  </div>

  <div class="card">
    <div class="controls">
      <input id="searchInput" class="input" placeholder="Search item name, qty or weight (type to filter)">

      <select id="filterCat" class="select">
        <option value="">All categories</option>
        <option value="gold">Gold</option>
        <option value="silver">Rupa</option>
        <option value="diamond">Hira</option>
      </select>

      <div style="margin-left:auto" class="chips">
        <div class="kv small-muted">Tip: tap a row on mobile to see details</div>
      </div>
    </div>

    <div class="table-wrap" id="tableWrap">
      <?php if ($allSales->num_rows === 0): ?>
        <div class="empty-note">No sales to show.</div>
      <?php else: ?>
      <table id="salesTable" role="table" aria-label="Recent sales">
        <thead>
          <tr>
            <th class="col-id">ID</th>
            <th class="col-item">Item</th>
            <th class="col-qty">Qty</th>
            <th class="col-weight">Weight</th>
            <th class="col-time">Sold At</th>
            <th>Category</th>
          </tr>
        </thead>
        <tbody>
          <?php while($s = $allSales->fetch_assoc()):
            $u = gramsToUnits(floatval($s['sold_weight_g'] ?? 0));
            $cat = strtolower(trim($s['category'] ?? ''));
            $badgeClass = $cat === 'gold' ? 'gold' : ($cat === 'silver' ? 'silver' : ($cat === 'diamond' ? 'diamond' : 'unknown'));
          ?>
          <tr data-name="<?php echo htmlspecialchars(strtolower($s['item_name'])) ?>"
              data-qty="<?php echo (int)$s['qty'] ?>"
              data-grams="<?php echo floatval($s['sold_weight_g'] ?? 0) ?>"
              data-cat="<?php echo htmlspecialchars($cat) ?>">
            <td class="col-id" data-label="ID"><?php echo (int)$s['id'] ?></td>
            <td class="col-item" data-label="Item">
              <div style="font-weight:700"><?php echo htmlspecialchars($s['item_name']) ?></div>
              <div class="small-muted"><?php echo htmlspecialchars($s['sku'] ?? '') ?></div>
            </td>
            <td class="col-qty" data-label="Qty"><?php echo (int)$s['qty'] ?></td>
            <td class="col-weight" data-label="Weight"><?php echo $u['vori'].' ভরি '.$u['ana'].' আনা ('.$u['grams'].' g)' ?></td>
            <td class="col-time" data-label="Sold At"><?php echo htmlspecialchars($s['sold_at']) ?></td>
            <td data-label="Category"><span class="badge <?php echo $badgeClass ?>"><?php echo $cat ? ucfirst($cat) : '—' ?></span></td>
          </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
(function(){
  const search = document.getElementById('searchInput');
  const filterCat = document.getElementById('filterCat');
  const table = document.getElementById('salesTable');
  if (!table) return;
  const rows = Array.from(table.querySelectorAll('tbody tr'));

  function normalize(s){ return (s||'').toString().trim().toLowerCase(); }

  function applyFilter(){
    const q = normalize(search.value);
    const cat = normalize(filterCat.value);

    let visibleCount = 0;
    rows.forEach(r=>{
      const name = normalize(r.getAttribute('data-name'));
      const qty = normalize(r.getAttribute('data-qty'));
      const grams = normalize(r.getAttribute('data-grams'));
      const rcat = normalize(r.getAttribute('data-cat'));

      const matchesQuery = !q || name.includes(q) || qty.includes(q) || grams.includes(q);
      const matchesCat = !cat || (rcat === cat);

      if (matchesQuery && matchesCat) {
        r.style.display = '';
        // highlight query matches
        if (q && name.includes(q)) r.classList.add('row-highlight'); else r.classList.remove('row-highlight');
        visibleCount++;
      } else {
        r.style.display = 'none';
        r.classList.remove('row-highlight');
      }
    });
    // Optionally show a note when no rows
    const tableWrap = document.getElementById('tableWrap');
    if (visibleCount === 0) {
      if (!document.getElementById('noRowsNote')) {
        const note = document.createElement('div');
        note.id = 'noRowsNote';
        note.className = 'empty-note';
        note.innerText = 'No matching records.';
        tableWrap.appendChild(note);
      }
    } else {
      const note = document.getElementById('noRowsNote');
      if (note) note.remove();
    }
  }

  search.addEventListener('input', applyFilter);
  filterCat.addEventListener('change', applyFilter);

  // Improve keyboard accessibility: focus row to copy values (mobile friendly)
  rows.forEach(r=>{
    r.addEventListener('click', ()=> {
      // toggle expanded look on small screens
      r.classList.toggle('row-highlight');
    });
    r.addEventListener('keydown', (e)=>{
      if (e.key === 'Enter') r.click();
    });
    r.tabIndex = 0;
  });

})();
</script>

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