<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}
include('../../includes/config.php');
include('../../includes/header.php');
include('../../includes/footer.php');

// Pagination & filtering
$limit = 15;
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

$filter_category = $_GET['category_id'] ?? '';
$search_name = $_GET['search_name'] ?? '';

$conditions = $params = [];
$types = '';
if ($filter_category !== '') {
    $conditions[] = 'p.category_id=?';
    $params[] = $filter_category;
    $types .= 'i';
}
if ($search_name !== '') {
    $conditions[] = 'p.product_name LIKE ?';
    $params[] = "%$search_name%";
    $types .= 's';
}
$where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : '';

// Count
$countStmt = $conn->prepare("SELECT COUNT(*) AS total FROM products p $where");
if ($params) $countStmt->bind_param($types, ...$params);
$countStmt->execute();
$total = $countStmt->get_result()->fetch_assoc()['total'];
$countStmt->close();
$total_pages = ceil($total / $limit);

// Fetch
$sql = "
SELECT p.*, c.category_name, COALESCE(i.quantity,0) AS quantity, COALESCE(i.restock_threshold,0) AS restock_threshold
FROM products p
LEFT JOIN categories c ON p.category_id=c.id
LEFT JOIN inventory i ON p.id=i.product_id
$where
ORDER BY p.created_at DESC
LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types . 'ii', ...array_merge($params, [$limit, $offset]));
} else {
    $stmt->bind_param('ii', $limit, $offset);
}
$stmt->execute();
$products = $stmt->get_result();
$stmt->close();

$categories_res = $conn->query("SELECT id, category_name FROM categories ORDER BY category_name");
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Product Management – Digital POS</title>
  <link rel="stylesheet" href="../../css/dashboard.css">
  <style>
    body, html {
      margin:0; padding:0;
      font-family:'Segoe UI',sans-serif;
      background:url('../../images/profile.jpg') no-repeat center center fixed;
      background-size:cover; color:white;
    }
    .overlay {
      position:fixed; top:0; left:0;
      width:100%; height:100%;
      background:rgba(0,0,0,0.6);
      z-index:-1;
    }
    .content {
      margin:100px auto 40px auto;
      max-width:1200px;
      padding:30px 40px;
      background:rgba(255,255,255,0.08);
      backdrop-filter:blur(15px);
      border-radius:20px;
      box-shadow:0 8px 32px rgba(0,0,0,0.5);
    }
    h2 {
      text-align:center;
      margin-bottom:25px;
      font-size:1.8rem;
    }
    .controls {
      display:flex;
      flex-wrap:wrap;
      justify-content:space-between;
      align-items:center;
      gap:12px;
      margin-bottom:20px;
    }
    .controls form {
      display:flex;
      flex-wrap:wrap;
      gap:10px;
      flex-grow:1;
    }
    select, input[type="text"], button {
      padding:10px 14px;
      border:none;
      border-radius:10px;
      background:rgba(255,255,255,0.1);
      color:white;
      font-size:14px;
      cursor:pointer;
    }
    button.primary {
      background:#ff6f00;
      font-weight:bold;
      transition:0.3s;
    }
    button.primary:hover {
      background:#e65c00;
    }
    button.export, button.bulk {
      background:#4caf50;
      margin-bottom:0;
      font-weight:bold;
    }
    button.bulk {
      background:#e53935;
    }
    table {
      width:100%;
      border-collapse:collapse;
      background:rgba(0,0,0,0.3);
      border-radius:12px;
      overflow:hidden;
      box-shadow:0 0 12px rgba(0,0,0,0.6);
    }
    th, td {
      padding:12px 14px;
      text-align:left;
      border-bottom:1px solid rgba(255,255,255,0.1);
      font-size:0.95rem;
    }
    th {
      background:rgba(255,111,0,0.9);
    }
    .low-stock-row {
      background:rgba(255,165,0,0.1);
    }
    .out-stock-row {
      background:rgba(255,0,0,0.1);
    }
    .badge {
      margin-left:5px;
      padding:2px 6px;
      font-size:11px;
      border-radius:4px;
      color:#fff;
    }
    .badge-loss { background:#c62828; }
    .badge-low, .badge-out { background:#ff9800; }

    .pagination {
      margin-top:20px; text-align:center;
    }
    .pagination a {
      background:#ff6f00;
      color:white;
      padding:8px 14px;
      margin:2px;
      border-radius:6px;
      text-decoration:none;
    }
    .pagination a.active {
      background:#e65c00;
      font-weight:bold;
    }

    .actions a {
      margin-right: 10px;
      font-size: 14px;
      font-weight: 600;
      text-decoration: none;
      color: #ff6f00;
      transition: color 0.3s ease;
    }
    .actions a.edit:hover {
      color: #e65c00;
    }
    .actions a.delete {
      color: #f44336;
    }
    .actions a.delete:hover {
      color: #d32f2f;
    }

    @media(max-width:768px) {
      .controls { flex-direction:column; }
      table, thead, tbody, th, td, tr {
        display:block;
        font-size:13px;
      }
      td::before {
        content:attr(data-label);
        display:block;
        font-weight:bold;
        color:#ffa500;
        margin-bottom:5px;
      }
    }
  </style>
</head>
<body>
  <div class="overlay"></div>
  <div class="content">
    <h2>Product Management</h2>

    <div class="controls">
      <div>
        <button class="export" onclick="exportCSV()">Export CSV</button>
        <button class="bulk" id="bulk-delete" disabled onclick="bulkDelete()">Delete Selected</button>
      </div>
      <form method="GET">
        <select name="category_id">
          <option value="">All Categories</option>
          <?php while ($c = $categories_res->fetch_assoc()): ?>
            <option value="<?= $c['id'] ?>" <?= $filter_category==$c['id']?'selected':'' ?>>
              <?= htmlspecialchars($c['category_name']) ?>
            </option>
          <?php endwhile; ?>
        </select>
        <input type="text" name="search_name" placeholder="Search product name" value="<?= htmlspecialchars($search_name) ?>">
        <button type="submit" class="primary">Filter</button>
      </form>
      <button class="primary" onclick="window.location='add_product.php'">+ Add Product</button>
    </div>

    <form id="prodForm">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" id="check-all"></th>
            <th>ID</th><th>Name</th><th>Barcode</th><th>Category</th><th>Unit</th>
            <th>Cost</th><th>Price</th><th>VAT</th><th>Qty</th><th>Image</th><th>Created</th><th>Updated</th><th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php while ($r = $products->fetch_assoc()):
            $qty = (int)$r['quantity'];
            $out = $qty === 0;
            $low = (!$out && $qty <= $r['restock_threshold']);
            $loss = $r['selling_price'] < $r['cost_price'];
            $rowClass = $out ? 'out-stock-row' : ($low ? 'low-stock-row' : '');
          ?>
            <tr class="<?= $rowClass ?>">
              <td><input type="checkbox" class="row-check" value="<?= $r['id'] ?>"></td>
              <td><?= $r['id'] ?></td>
              <td><?= htmlspecialchars($r['product_name']) ?></td>
              <td><?= htmlspecialchars($r['barcode']) ?></td>
              <td><?= htmlspecialchars($r['category_name'] ?: '-') ?></td>
              <td><?= htmlspecialchars($r['unit']) ?></td>
              <td><?= number_format($r['cost_price'],2) ?></td>
              <td>
                <?= number_format($r['selling_price'],2) ?>
                <?= $loss ? '<span class="badge badge-loss">⚠️ Loss</span>' : ''?>
              </td>
              <td><?= number_format($r['vat_rate'],2) ?>%</td>
              <td>
                <?= $qty ?>
                <?= $out ? '<span class="badge badge-out">Out</span>' : ($low ? '<span class="badge badge-low">Low</span>' : '') ?>
              </td>
              <td><?= $r['image_path'] ? '<img src="../../uploads/products/' . htmlspecialchars($r['image_path']) . '" style="max-width:50px;border-radius:6px;">' : '-' ?></td>
              <td><?= date('d M Y', strtotime($r['created_at'])) ?></td>
              <td><?= $r['updated_at'] ? date('d M Y', strtotime($r['updated_at'])) : '-' ?></td>
              <td class="actions">
                <a href="edit_product.php?id=<?= $r['id'] ?>" class="edit">Edit</a>
                <a href="#" class="delete" onclick="deleteOne(<?= $r['id'] ?>); return false;">Delete</a>
              </td>
            </tr>
          <?php endwhile; ?>
          <?php if (!$products->num_rows): ?>
            <tr><td colspan="14" style="text-align:center;">No products found.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </form>

    <div class="pagination">
      <?php for ($i = 1; $i <= $total_pages; $i++): ?>
        <a href="?<?= http_build_query(array_merge($_GET, ['page'=>$i])) ?>" class="<?= $i==$page ? 'active' : '' ?>">
          <?= $i ?>
        </a>
      <?php endfor; ?>
    </div>
  </div>

  <script>
    const allCheck = document.getElementById('check-all');
    const rowChecks = document.querySelectorAll('.row-check');
    const bulkBtn = document.getElementById('bulk-delete');

    allCheck.addEventListener('change', () => {
      rowChecks.forEach(c => c.checked = allCheck.checked);
      bulkBtn.disabled = ![...rowChecks].some(c => c.checked);
    });
    rowChecks.forEach(c => c.addEventListener('change', () => {
      bulkBtn.disabled = ![...rowChecks].some(c => c.checked);
    }));

    function deleteOne(id) {
      if (!confirm('Delete this product?')) return;
      fetch('delete_product.php', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`id=${id}`
      })
      .then(r=>r.json()).then(j=>{
        alert(j.message);
        if (j.success) location.reload();
      });
    }

    function bulkDelete(){
      if (!confirm('Delete selected products?')) return;
      const ids = [...rowChecks].filter(c=>c.checked).map(c=>c.value);
      fetch('delete_multiple.php', {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ids})
      })
      .then(r=>r.json()).then(j=>{
        alert(j.message);
        if (j.success) location.reload();
      });
    }

    function exportCSV() {
      const rows = [...document.querySelectorAll('tbody tr')];
      const csv = rows.map(r =>
        [...r.querySelectorAll('td')].slice(1, -1).map(td => td.innerText.trim()).join(',')
      ).join('\n');
      const a = document.createElement('a');
      a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
      a.download = 'products.csv';
      a.click();
    }
  </script>
</body>
</html>
