<?php
class Restock {
	private $pdo; public function __construct(){ $this->pdo=$GLOBALS['pdo']; }
	private function hasSupplier(){ static $has=null; if($has!==null) return $has; try { $cols=$this->pdo->query("SHOW COLUMNS FROM restocks LIKE 'supplier'")->fetchAll(); $has=!!$cols; } catch(Exception $e){ $has=false; } return $has; }
	public function all($limit=100){
		// Include aggregate summary: item count & total quantity
		$sql="SELECT r.*, COUNT(ri.id) AS item_count, COALESCE(SUM(ri.quantity),0) AS total_qty
			  FROM restocks r
			  LEFT JOIN restock_items ri ON ri.restock_id=r.id
			  GROUP BY r.id
			  ORDER BY r.restock_date DESC, r.id DESC
			  LIMIT $limit";
		return $this->pdo->query($sql)->fetchAll();
	}
	public function find($id){ $st=$this->pdo->prepare("SELECT * FROM restocks WHERE id=?"); $st->execute([$id]); return $st->fetch(); }
	public function create($d){
		if($this->hasSupplier()){
			$st=$this->pdo->prepare("INSERT INTO restocks (restock_date, supplier, notes, created_by) VALUES (?,?,?,?)");
			$ok=$st->execute([$d['restock_date'],$d['supplier']??null,$d['notes']??null,$d['created_by']??null]);
		} else {
			$st=$this->pdo->prepare("INSERT INTO restocks (restock_date, notes, created_by) VALUES (?,?,?)");
			$ok=$st->execute([$d['restock_date'],$d['notes']??null,$d['created_by']??null]);
		}
		return $ok? $this->pdo->lastInsertId():false;
	}
	public function update($id,$d){
		if($this->hasSupplier()){
			$st=$this->pdo->prepare("UPDATE restocks SET restock_date=?, supplier=?, notes=? WHERE id=?");
			return $st->execute([$d['restock_date'],$d['supplier']??null,$d['notes']??null,$id]);
		}
		$st=$this->pdo->prepare("UPDATE restocks SET restock_date=?, notes=? WHERE id=?");
		return $st->execute([$d['restock_date'],$d['notes']??null,$id]);
	}
	public function delete($id){ $st=$this->pdo->prepare("DELETE FROM restocks WHERE id=?"); return $st->execute([$id]); }
	public function items($restockId){ $st=$this->pdo->prepare("SELECT ri.*, i.name, i.unit FROM restock_items ri JOIN ingredients i ON i.id=ri.ingredient_id WHERE ri.restock_id=? ORDER BY ri.id ASC"); $st->execute([$restockId]); return $st->fetchAll(); }
	public function replaceItems($restockId,$items){
		$del=$this->pdo->prepare("DELETE FROM restock_items WHERE restock_id=?"); $del->execute([$restockId]);
		if(!$items) return true;
		$ins=$this->pdo->prepare("INSERT INTO restock_items (restock_id, ingredient_id, quantity, location) VALUES (?,?,?,?)");
		foreach($items as $it){ $ins->execute([$restockId,$it['ingredient_id'],$it['quantity'],$it['location']??'MAIN']); }
		return true;
	}
}
