<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/db.php';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id > 0) {
  $stmt = db()->prepare("SELECT stock FROM products WHERE id = ?");
  $stmt->bind_param("i", $id);
  $stmt->execute();
  $res = $stmt->get_result();
  $row = $res->fetch_assoc();
  $stmt->close();

  if ($row) {
    $available = (int)$row['stock'];
    $currentQty = $_SESSION['cart'][$id] ?? 0;
    if ($available > $currentQty) {
      if (!isset($_SESSION['cart'])) $_SESSION['cart'] = [];
      $_SESSION['cart'][$id] = $currentQty + 1;
    } else {
      header('Location: /WATCHING/pages/product.php?id=' . $id); exit;
    }
  }
}
header('Location: /WATCHING/pages/cart.php');