<?php
require_once '../app/Models/ProductionSite.php';
class ProductionSiteController { private $m; public function __construct(){ $this->auth(); $this->m=new ProductionSite(); }
  private function auth(){ if(!isset($_SESSION['user_id'])){ redirect('login'); exit; } }
  public function index(){ $this->view('production_sites/index',['sites'=>$this->m->allWithInactive()]); }
  public function create(){ $this->view('production_sites/create'); }
  public function store(){ if($_SERVER['REQUEST_METHOD']!=='POST'){ redirect('production-sites'); exit; } $code=trim($_POST['code']??''); $name=trim($_POST['name']??''); if($code===''||$name===''){ $_SESSION['error']='Code & Name required'; redirect('production-sites/create'); exit; } $this->m->create(['code'=>$code,'name'=>$name,'description'=>$_POST['description']??'','sort_order'=>$_POST['sort_order']??0,'is_active'=>isset($_POST['is_active'])?1:0]); $_SESSION['success']='Site created'; redirect('production-sites'); }
  public function edit($id){ $u=$this->m->find($id); if(!$u){ $_SESSION['error']='Not found'; redirect('production-sites'); exit; } $this->view('production_sites/edit',['site'=>$u]); }
  public function update($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ redirect('production-sites'); exit; } $this->m->update($id,['code'=>$_POST['code'],'name'=>$_POST['name'],'description'=>$_POST['description']??'','sort_order'=>$_POST['sort_order']??0,'is_active'=>isset($_POST['is_active'])?1:0]); $_SESSION['success']='Updated'; redirect('production-sites'); }
  public function delete($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ redirect('production-sites'); exit; } $this->m->delete($id); $_SESSION['success']='Deleted'; redirect('production-sites'); }
  private function view($v,$d=[]){ extract($d); require_once "../app/Views/$v.php"; }
}


