<?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'])){ header('Location:/samanta_crm/login'); exit; } }
  public function index(){ $this->view('units/index',['units'=>$this->m->allWithInactive()]); }
  public function create(){ $this->view('units/create'); }
  public function store(){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/units'); exit; } $code=trim($_POST['code']??''); $name=trim($_POST['name']??''); $scope=$_POST['scope']??'product'; if($code===''||$name===''){ $_SESSION['error']='Code & Name required'; header('Location:/samanta_crm/units/create'); exit; } $this->m->create(['code'=>$code,'name'=>$name,'scope'=>$scope,'sort_order'=>$_POST['sort_order']??0,'is_active'=>isset($_POST['is_active'])?1:0]); $_SESSION['success']='Unit created'; header('Location:/samanta_crm/units'); }
  public function edit($id){ $u=$this->m->find($id); if(!$u){ $_SESSION['error']='Not found'; header('Location:/samanta_crm/units'); exit; } $this->view('units/edit',['unit'=>$u]); }
  public function update($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/units'); exit; } $code=trim($_POST['code']??''); $name=trim($_POST['name']??''); $scope=$_POST['scope']??'product'; $this->m->update($id,['code'=>$code,'name'=>$name,'scope'=>$scope,'sort_order'=>$_POST['sort_order']??0,'is_active'=>isset($_POST['is_active'])?1:0]); $_SESSION['success']='Updated'; header('Location:/samanta_crm/units'); }
  public function delete($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/units'); exit; } $this->m->delete($id); $_SESSION['success']='Deleted'; header('Location:/samanta_crm/units'); }
  private function view($v,$d=[]){ extract($d); require_once "../app/Views/$v.php"; }
}
