<?php
require_once '../app/Models/Ingredient.php';
require_once '../app/Models/IngredientStorage.php';
require_once '../app/Helpers/UnitHelper.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; 
		}
		
		$ingredientId = (int)($_POST['ingredient_id'] ?? 0);
		$qty = (float)str_replace(',', '.', $_POST['quantity'] ?? 0);
		$inputUnit = $_POST['quantity_unit'] ?? null;
		$reason = $_POST['reason'] ?? 'manual_adjust';
		$note = $_POST['note'] ?? null;
		$location = $_POST['location'] ?? 'MAIN';
		
		// Get ingredient to determine base unit
		$ingredient = $this->ingredient->find($ingredientId);
		if (!$ingredient) {
			$_SESSION['error'] = 'Ingredient not found';
			header('Location:/samanta_crm/stock/ingredients');
			return;
		}
		
		$baseUnit = $ingredient['unit'];
		
		// Convert quantity to base unit if needed
		if ($inputUnit && $inputUnit !== $baseUnit) {
			$convertedQty = convertUnit($qty, $inputUnit, $baseUnit);
			if ($convertedQty !== null) {
				$qty = $convertedQty;
			}
		}
		
		$this->storage->add($ingredientId, $qty, $reason, $note, $location, date('Y-m-d'));
		$_SESSION['success'] = 'Stock adjusted';
		
		$returnTo = $_POST['return_to'] ?? '/samanta_crm/stock/ingredients';
		header('Location:' . $returnTo);
	}
	
	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');
	}
}
