<?php
require_once '../app/Models/Ingredient.php';
require_once '../app/Models/Unit.php';
require_once '../app/Models/IngredientStorage.php';
class IngredientController {
  private $model; private $unitModel; private $storage;
  public function __construct(){ $this->auth(); $this->model=new Ingredient(); $this->unitModel=new Unit(); $this->storage=new IngredientStorage(); }
  private function auth(){ if(!isset($_SESSION['user_id'])){ header('Location:/samanta_crm/login'); exit; } }
  private function getUnits(){ return $this->unitModel->allIngredient(); }
  public function index(){ $units=$this->indexUnitsMap(); $this->view('ingredients/index',[ 'ingredients'=>$this->model->all(), 'unitsMap'=>$units ]); }
  private function indexUnitsMap(){ $list=$this->getUnits(); $map=[]; foreach($list as $u){ $map[$u['code']]=$u; } return $map; }
  public function create(){ $this->view('ingredients/create',[ 'units'=>$this->getUnits() ]); }
  public function store(){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/ingredients'); exit; } $name=trim($_POST['name']??''); if($name===''){ $_SESSION['error']='Name required'; header('Location:/samanta_crm/ingredients/create'); exit; }
    $unit = $_POST['unit_code'] ?? '';
    $supplier = trim($_POST['supplier'] ?? '');
    $this->model->create(['name'=>$name,'unit'=>$unit,'supplier'=>$supplier,'notes'=>$_POST['notes']??'']); $_SESSION['success']='Ingredient created'; header('Location:/samanta_crm/ingredients'); }
  public function edit($id){
    $c=$this->model->find($id);
    if(!$c){ $_SESSION['error']='Not found'; header('Location:/samanta_crm/ingredients'); exit; }
    $locations=$this->storage->stockByLocations($id);
    $movements=$this->storage->movements($id,50);
    $this->view('ingredients/edit',[ 'ingredient'=>$c, 'units'=>$this->getUnits(), 'locationStocks'=>$locations, 'movements'=>$movements ]);
  }
  public function update($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/ingredients'); exit; } $name=trim($_POST['name']??''); if($name===''){ $_SESSION['error']='Name required'; header('Location:/samanta_crm/ingredients/'.$id.'/edit'); exit; } $unit=$_POST['unit_code']??''; $supplier=trim($_POST['supplier'] ?? ''); $this->model->update($id,['name'=>$name,'unit'=>$unit,'supplier'=>$supplier,'notes'=>$_POST['notes']??'']); $_SESSION['success']='Updated'; header('Location:/samanta_crm/ingredients'); }
  public function delete($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/ingredients'); exit; } $this->model->delete($id); $_SESSION['success']='Deleted'; header('Location:/samanta_crm/ingredients'); }
  private function view($v,$d=[]){ extract($d); require_once "../app/Views/$v.php"; }
}
