<?php
class ProductIngredient { private $pdo; public function __construct(){ $this->pdo=$GLOBALS['pdo']; }
  public function forProduct($productId){ $st=$this->pdo->prepare("SELECT pi.*, i.name, i.unit FROM product_ingredients pi LEFT JOIN ingredients i ON pi.ingredient_id=i.id WHERE pi.product_id=? ORDER BY pi.id ASC"); $st->execute([$productId]); return $st->fetchAll(); }
  public function forIngredient($ingredientId){ $st=$this->pdo->prepare("SELECT pi.product_id, pi.ingredient_id, pi.quantity as ingredient_qty, pi.unit, p.name as product_name, p.code as product_code FROM product_ingredients pi LEFT JOIN products p ON pi.product_id=p.id WHERE pi.ingredient_id=? ORDER BY p.name ASC"); $st->execute([$ingredientId]); return $st->fetchAll(); }
  public function exists($productId, $ingredientId){ $st=$this->pdo->prepare("SELECT id FROM product_ingredients WHERE product_id=? AND ingredient_id=?"); $st->execute([$productId,$ingredientId]); return (bool)$st->fetch(); }
  public function link($productId, $ingredientId, $quantity, $unit=null){ $st=$this->pdo->prepare("INSERT INTO product_ingredients (product_id, ingredient_id, quantity, unit) VALUES (?,?,?,?)"); return $st->execute([$productId, $ingredientId, $quantity, $unit]); }
  public function updateQuantity($productId, $ingredientId, $quantity){ $st=$this->pdo->prepare("UPDATE product_ingredients SET quantity=? WHERE product_id=? AND ingredient_id=?"); return $st->execute([$quantity, $productId, $ingredientId]); }
  public function unlink($productId, $ingredientId){ $st=$this->pdo->prepare("DELETE FROM product_ingredients WHERE product_id=? AND ingredient_id=?"); return $st->execute([$productId, $ingredientId]); }
  public function sync($productId,$items){ // items: [['ingredient_id'=>, 'qty'=>, 'unit'=>]]
    $this->pdo->prepare("DELETE FROM product_ingredients WHERE product_id=?")->execute([$productId]);
    $st=$this->pdo->prepare("INSERT INTO product_ingredients (product_id,ingredient_id,quantity,unit) VALUES (?,?,?,?)");
    foreach($items as $it){ if(empty($it['ingredient_id'])) continue; $st->execute([$productId,$it['ingredient_id'],$it['quantity']??null,$it['unit']??null]); }
  }
}

