<?php
session_start();
if (empty($_SESSION['is_admin'])) { header('Location: login.php'); exit; }

$dataFile = __DIR__ . '/../data/products.json';
$products = [];
if (file_exists($dataFile)) { $products = json_decode(file_get_contents($dataFile), true) ?: []; }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $products = array_values(array_filter($products, function($p) use ($id){ return $p['id'] !== $id; }));
        file_put_contents($dataFile, json_encode($products, JSON_PRETTY_PRINT));
        header('Location: products.php'); exit;
    }
}

?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Manage Products - Admin</title>
  <link rel="stylesheet" href="/ecom/styles.css">
</head>
<body>
<?php include __DIR__ . '/../header.php'; ?>
<main class="container">
  <h1>Products</h1>
  <p><a href="add_product.php" class="btn">Add Product</a> <a href="index.php" class="btn" style="background:#999;">Back</a></p>
  <table style="width:100%;border-collapse:collapse;">
    <thead><tr><th style="text-align:left;padding:8px">Title</th><th style="padding:8px">Price</th><th style="padding:8px">Category</th><th style="padding:8px">Actions</th></tr></thead>
    <tbody>
    <?php foreach ($products as $p): ?>
      <tr>
        <td style="padding:8px"><?php echo htmlspecialchars($p['title']); ?></td>
        <td style="padding:8px">$<?php echo $p['price']; ?></td>
        <td style="padding:8px"><?php echo htmlspecialchars($p['cat'] ?? ''); ?></td>
        <td style="padding:8px">
          <a href="edit_product.php?id=<?php echo $p['id']; ?>" class="btn">Edit</a>
          <form method="post" action="products.php" style="display:inline; margin-left:8px;" onsubmit="return confirm('Delete this product?');">
            <input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?php echo $p['id']; ?>">
            <button class="btn" type="submit" style="background:#999;">Delete</button>
          </form>
        </td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</main>
<?php include __DIR__ . '/../footer.php'; ?>
</body>
</html>
