<?php
class Unit { private $pdo; public function __construct(){ $this->pdo=$GLOBALS['pdo']; }
  // Default: product-capable units
  public function all(){ return $this->pdo->query("SELECT * FROM units WHERE is_active=1 AND (scope='product' OR scope='both') ORDER BY sort_order ASC, name ASC")->fetchAll(); }
  public function allIngredient(){ return $this->pdo->query("SELECT * FROM units WHERE is_active=1 AND (scope='ingredient' OR scope='both') ORDER BY sort_order ASC, name ASC")->fetchAll(); }
  public function allProduct(){ return $this->pdo->query("SELECT * FROM units WHERE is_active=1 AND (scope='product' OR scope='both') ORDER BY sort_order ASC, name ASC")->fetchAll(); }
  public function allWithInactive(){ return $this->pdo->query("SELECT * FROM units ORDER BY sort_order ASC, name ASC")->fetchAll(); }
  public function find($id){ $st=$this->pdo->prepare("SELECT * FROM units WHERE id=?"); $st->execute([$id]); return $st->fetch(); }
  public function create($d){ $st=$this->pdo->prepare("INSERT INTO units (code,name,scope,sort_order,is_active) VALUES (?,?,?,?,?)"); return $st->execute([$d['code'],$d['name'],$d['scope']??'product',$d['sort_order']??0,$d['is_active']??1]); }
  public function update($id,$d){ $st=$this->pdo->prepare("UPDATE units SET code=?, name=?, scope=?, sort_order=?, is_active=? WHERE id=?"); return $st->execute([$d['code'],$d['name'],$d['scope']??'product',$d['sort_order']??0,$d['is_active']??1,$id]); }
  public function delete($id){ $st=$this->pdo->prepare("DELETE FROM units WHERE id=?"); return $st->execute([$id]); }
}
