<?php
require_once '../app/Models/Unit.php';
class UnitController { 
  private $m; 
  
  public function __construct(){ 
    $this->auth(); 
    $this->m=new Unit(); 
  }
  
  private function auth(){ 
    if(!isset($_SESSION['user_id'])){ 
      redirect('login'); 
      exit; 
    } 
  }
  
  public function index(){ 
    $this->view('units/index',['units'=>$this->m->getAllWithConversions()]); 
  }
  
  public function create(){ 
    $this->view('units/create',['allUnits'=>$this->m->allWithInactive()]); 
  }
  
  public function store(){ 
    if($_SERVER['REQUEST_METHOD']!=='POST'){ 
      redirect('units'); 
      exit; 
    } 
    
    $code=trim($_POST['code']??''); 
    $name=trim($_POST['name']??''); 
    $scope=$_POST['scope']??'product'; 
    
    if($code===''||$name===''){ 
      $_SESSION['error']='Code & Name required'; 
      redirect('units/create'); 
      exit; 
    } 
    
    $base_unit = !empty($_POST['base_unit']) ? (int)$_POST['base_unit'] : null;
    $conversion_factor = !empty($_POST['conversion_factor']) ? (float)$_POST['conversion_factor'] : null;
    
    $this->m->create([
      'code'=>$code,
      'name'=>$name,
      'scope'=>$scope,
      'sort_order'=>$_POST['sort_order']??0,
      'is_active'=>isset($_POST['is_active'])?1:0,
      'base_unit'=>$base_unit,
      'conversion_factor'=>$conversion_factor
    ]); 
    
    $_SESSION['success']='Unit created'; 
    redirect('units'); 
  }
  
  public function edit($id){ 
    $u=$this->m->find($id); 
    if(!$u){ 
      $_SESSION['error']='Not found'; 
      redirect('units'); 
      exit; 
    } 
    $this->view('units/edit',['unit'=>$u, 'allUnits'=>$this->m->allWithInactive()]); 
  }
  
  public function update($id){ 
    if($_SERVER['REQUEST_METHOD']!=='POST'){ 
      redirect('units'); 
      exit; 
    } 
    
    $code=trim($_POST['code']??''); 
    $name=trim($_POST['name']??''); 
    $scope=$_POST['scope']??'product'; 
    
    $base_unit = !empty($_POST['base_unit']) ? (int)$_POST['base_unit'] : null;
    $conversion_factor = !empty($_POST['conversion_factor']) ? (float)$_POST['conversion_factor'] : null;
    
    $this->m->update($id,[
      'code'=>$code,
      'name'=>$name,
      'scope'=>$scope,
      'sort_order'=>$_POST['sort_order']??0,
      'is_active'=>isset($_POST['is_active'])?1:0,
      'base_unit'=>$base_unit,
      'conversion_factor'=>$conversion_factor
    ]); 
    
    $_SESSION['success']='Updated'; 
    redirect('units'); 
  }
  
  public function delete($id){ 
    if($_SERVER['REQUEST_METHOD']!=='POST'){ 
      redirect('units'); 
      exit; 
    } 
    $this->m->delete($id); 
    $_SESSION['success']='Deleted'; 
    redirect('units'); 
  }
  
  private function view($v,$d=[]){ 
    extract($d); 
    require_once "../app/Views/$v.php"; 
  }
}


