<?php
require_once '../app/Models/Ingredient.php';
require_once '../app/Models/IngredientStorage.php';
class IngredientStorageController {
	private $ingredient; private $storage;
	public function __construct(){ $this->auth(); $this->ingredient=new Ingredient(); $this->storage=new IngredientStorage(); }
	private function auth(){ if(!isset($_SESSION['user_id'])){ header('Location:/samanta_crm/login'); exit; } }
	private function view($v,$d=[]){ extract($d); require_once "../app/Views/$v.php"; }
	public function adjust(){
		if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/stock/ingredients'); return; }
		$ing=(int)($_POST['ingredient_id']??0); $qty=(float)str_replace(',','.', $_POST['quantity']??0); $reason=$_POST['reason']??'manual_adjust'; $note=$_POST['note']??null; $loc=$_POST['location']??'MAIN';
		$this->storage->add($ing,$qty,$reason,$note,$loc,date('Y-m-d'));
		$_SESSION['success']='Stock adjusted';
		$rt = isset($_POST['return_to']) ? $_POST['return_to'] : '/samanta_crm/stock/ingredients';
		header('Location:'.$rt);
	}
	public function mergeRollback(){
		if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/stock/ingredients'); return; }
		$id=(int)$_POST['ingredient_id']; $ok=$this->storage->mergeRollback($id); $_SESSION['success']=$ok?'Rollback merged':'Nothing to merge';
		header('Location:/samanta_crm/stock/ingredients');
	}
}
