<?php
require_once '../app/Models/Ingredient.php';
require_once '../app/Models/Unit.php';
require_once '../app/Models/IngredientStorage.php';
require_once '../app/Models/Product.php';
require_once '../app/Models/ProductIngredient.php';
class IngredientController {
  private $model; private $unitModel; private $storage; private $product; private $pivot;
  public function __construct(){ $this->auth(); $this->model=new Ingredient(); $this->unitModel=new Unit(); $this->storage=new IngredientStorage(); $this->product=new Product(); $this->pivot=new ProductIngredient(); }
  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'] ?? '');
    $data = [
      'name'=>$name,
      'unit'=>$unit,
      'supplier'=>$supplier,
      'notes'=>$_POST['notes']??'',
      'low_stock'=>!empty($_POST['low_stock']) ? (float)$_POST['low_stock'] : null,
      'high_stock'=>!empty($_POST['high_stock']) ? (float)$_POST['high_stock'] : null,
      'critical_low_stock'=>!empty($_POST['critical_low_stock']) ? (float)$_POST['critical_low_stock'] : null,
      'critical_high_stock'=>!empty($_POST['critical_high_stock']) ? (float)$_POST['critical_high_stock'] : null
    ];
    $this->model->create($data); $_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);
    $products=$this->product->search('','','all',500,0);
    $productLinks=$this->getProductLinksForIngredient($id);
    $this->view('ingredients/edit',[ 'ingredient'=>$c, 'units'=>$this->getUnits(), 'locationStocks'=>$locations, 'movements'=>$movements, 'products'=>$products, 'productLinks'=>$productLinks ]);
  }
  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'] ?? ''); 
    
    // Get current ingredient to know the base unit
    $ingredient = $this->model->find($id);
    $baseUnit = $ingredient['unit'] ?? $unit;
    
    // Convert stock levels to base unit if units are specified
    $critical_low_stock = null;
    $low_stock = null;
    $high_stock = null;
    $critical_high_stock = null;
    
    if (!empty($_POST['critical_low_stock'])) {
      $value = (float)$_POST['critical_low_stock'];
      $inputUnit = $_POST['critical_low_stock_unit'] ?? $baseUnit;
      $critical_low_stock = ($inputUnit !== $baseUnit) ? convertUnit($value, $inputUnit, $baseUnit) : $value;
    }
    
    if (!empty($_POST['low_stock'])) {
      $value = (float)$_POST['low_stock'];
      $inputUnit = $_POST['low_stock_unit'] ?? $baseUnit;
      $low_stock = ($inputUnit !== $baseUnit) ? convertUnit($value, $inputUnit, $baseUnit) : $value;
    }
    
    if (!empty($_POST['high_stock'])) {
      $value = (float)$_POST['high_stock'];
      $inputUnit = $_POST['high_stock_unit'] ?? $baseUnit;
      $high_stock = ($inputUnit !== $baseUnit) ? convertUnit($value, $inputUnit, $baseUnit) : $value;
    }
    
    if (!empty($_POST['critical_high_stock'])) {
      $value = (float)$_POST['critical_high_stock'];
      $inputUnit = $_POST['critical_high_stock_unit'] ?? $baseUnit;
      $critical_high_stock = ($inputUnit !== $baseUnit) ? convertUnit($value, $inputUnit, $baseUnit) : $value;
    }
    
    $data = [
      'name' => $name,
      'unit' => $unit,
      'supplier' => $supplier,
      'notes' => $_POST['notes'] ?? '',
      'low_stock' => $low_stock,
      'high_stock' => $high_stock,
      'critical_low_stock' => $critical_low_stock,
      'critical_high_stock' => $critical_high_stock
    ];
    
    $this->model->update($id, $data); 
    $_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 getProductLinksForIngredient($ingredientId){
    return $this->pivot->forIngredient($ingredientId);
  }
  
  public function linkProducts($id){
    if($_SERVER['REQUEST_METHOD']!=='POST'){ 
      header('Content-Type: application/json');
      echo json_encode(['success'=>false,'message'=>'Invalid request method']);
      exit;
    }
    
    $productId = (int)($_POST['product_id']??0);
    $qty = (float)($_POST['ingredient_qty']??0);
    
    if($productId<=0 || $qty<=0){ 
      header('Content-Type: application/json');
      echo json_encode(['success'=>false,'message'=>'Invalid product or quantity']);
      exit;
    }
    
    // Check if already linked
    if($this->pivot->exists($productId, $id)){ 
      header('Content-Type: application/json');
      echo json_encode(['success'=>false,'message'=>'Product already linked to this ingredient']);
      exit;
    }
    
    // Get ingredient unit
    $ingredient = $this->model->find($id);
    $unit = $ingredient['unit']??null;
    
    // Add link
    $result = $this->pivot->link($productId, $id, $qty, $unit);
    
    header('Content-Type: application/json');
    if($result){
      echo json_encode(['success'=>true,'message'=>'Product linked successfully']);
    } else {
      echo json_encode(['success'=>false,'message'=>'Failed to link product']);
    }
  }
  
  public function unlinkProduct($id){
    if($_SERVER['REQUEST_METHOD']!=='POST'){ 
      header('Content-Type: application/json');
      echo json_encode(['success'=>false,'message'=>'Invalid request method']);
      exit;
    }
    
    $productId = (int)($_POST['product_id']??0);
    if($productId<=0){ 
      header('Content-Type: application/json');
      echo json_encode(['success'=>false,'message'=>'Invalid product']);
      exit;
    }
    
    $result = $this->pivot->unlink($productId, $id);
    
    header('Content-Type: application/json');
    if($result){
      echo json_encode(['success'=>true,'message'=>'Product unlinked successfully']);
    } else {
      echo json_encode(['success'=>false,'message'=>'Failed to unlink product']);
    }
  }
  
  public function getProductLinks($id){
    header('Content-Type: application/json');
    $links = $this->getProductLinksForIngredient($id);
    echo json_encode(['success'=>true,'links'=>$links]);
  }
  
  public function updateLinkQuantity($id){
    if($_SERVER['REQUEST_METHOD']!=='POST'){ 
      header('Content-Type: application/json');
      echo json_encode(['success'=>false,'message'=>'Invalid request method']);
      exit;
    }
    
    $productId = (int)($_POST['product_id']??0);
    $quantity = (float)($_POST['quantity']??0);
    
    if($productId<=0 || $quantity<=0){ 
      header('Content-Type: application/json');
      echo json_encode(['success'=>false,'message'=>'Invalid product or quantity']);
      exit;
    }
    
    // Update quantity
    $result = $this->pivot->updateQuantity($productId, $id, $quantity);
    
    header('Content-Type: application/json');
    if($result){
      echo json_encode(['success'=>true,'message'=>'Quantity updated successfully']);
    } else {
      echo json_encode(['success'=>false,'message'=>'Failed to update quantity']);
    }
  }
  
  private function view($v,$d=[]){ extract($d); require_once "../app/Views/$v.php"; }
}
