<?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 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]); }
  }
}
