<?php
require_once '../app/Models/Category.php';
class CategoryController { private $model; public function __construct(){ $this->auth(); $this->model=new Category(); }
  private function auth(){ if(!isset($_SESSION['user_id'])){ header('Location:/samanta_crm/login'); exit; } }
  public function index(){ $this->view('categories/index',[ 'categories'=>$this->model->all() ]); }
  public function create(){ $this->view('categories/create'); }
  public function store(){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/categories'); exit; } $name=trim($_POST['name']??''); if($name===''){ $_SESSION['error']='Name required'; header('Location:/samanta_crm/categories/create'); exit; } $this->model->create(['name'=>$name,'description'=>$_POST['description']??'','sort_order'=>$_POST['sort_order']??0]); $_SESSION['success']='Category created'; header('Location:/samanta_crm/categories'); }
  public function edit($id){ $c=$this->model->find($id); if(!$c){ $_SESSION['error']='Not found'; header('Location:/samanta_crm/categories'); exit; } $this->view('categories/edit',[ 'category'=>$c ]); }
  public function update($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/categories'); exit; } $name=trim($_POST['name']??''); if($name===''){ $_SESSION['error']='Name required'; header('Location:/samanta_crm/categories/'.$id.'/edit'); exit; } $this->model->update($id,['name'=>$name,'description'=>$_POST['description']??'','sort_order'=>$_POST['sort_order']??0]); $_SESSION['success']='Updated'; header('Location:/samanta_crm/categories'); }
  public function delete($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location:/samanta_crm/categories'); exit; } $this->model->delete($id); $_SESSION['success']='Deleted'; header('Location:/samanta_crm/categories'); }
  private function view($v,$d=[]){ extract($d); require_once "../app/Views/$v.php"; }
}
