<?php
require_once __DIR__ . '/../config/db.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['admin_id'])) { header('Location: /WATCHING/admin/login.php'); exit; }

// Handle toggles
if (isset($_GET['toggle']) && isset($_GET['field'])) {
  $id = (int)$_GET['toggle']; $field = $_GET['field'];
  if (in_array($field, ['is_featured','is_best_seller','is_new_arrival'])) {
    db()->query("UPDATE products SET $field = 1 - $field WHERE id = $id");
  }
  header('Location: /WATCHING/admin/products_list.php'); exit;
}

$res = db()->query("SELECT p.id, p.title, p.price, p.is_featured, p.is_best_seller, p.is_new_arrival, b.name as brand
  FROM products p LEFT JOIN brands b ON p.brand_id = b.id ORDER BY p.created_at DESC");
?>
<!doctype html>
<html><head><link href="/WATCHING/assets/css/styles.css" rel="stylesheet"></head><body class="glass-bg">
<div class="container glass-card" style="padding:16px;margin-top:20px;">
  <h2>Manage Products</h2>
  <table class="table">
    <thead><tr><th>Title</th><th>Brand</th><th>Price</th><th>Flags</th><th>Actions</th></tr></thead>
    <tbody>
      <?php while ($p = $res->fetch_assoc()): ?>
        <tr>
          <td><?php echo htmlspecialchars($p['title']); ?></td>
          <td><?php echo htmlspecialchars($p['brand']); ?></td>
          <td>BDT <?php echo number_format($p['price'], 2); ?></td>
          <td>
            F: <?php echo $p['is_featured'] ? 'Yes' : 'No'; ?> |
            B: <?php echo $p['is_best_seller'] ? 'Yes' : 'No'; ?> |
            N: <?php echo $p['is_new_arrival'] ? 'Yes' : 'No'; ?>
          </td>
          <td>
            <a class="btn" href="?toggle=<?php echo $p['id']; ?>&field=is_featured">Toggle Featured</a>
            <a class="btn" href="?toggle=<?php echo $p['id']; ?>&field=is_best_seller">Toggle Best</a>
            <a class="btn" href="?toggle=<?php echo $p['id']; ?>&field=is_new_arrival">Toggle New</a>
          </td>
        </tr>
      <?php endwhile; ?>
    </tbody>
  </table>
</div>
</body></html>