<?php

class TrailerController extends Controller
{
    private Trailer $trailers; private Truck $trucks; private Carrier $carriers;
    public function __construct(){ $this->trailers=new Trailer();$this->trucks=new Truck();$this->carriers=new Carrier(); }
    public function index(): void { Auth::requireRole(['owner','admin','dispatcher','maintenance']);$search=trim((string)($_GET['search']??''));$trailers=$this->trailers->all($search?:null);$this->view('trailers/index',compact('trailers','search'));clear_old(); }
    public function create(): void { Auth::requireRole(['owner','admin','dispatcher','maintenance']);$trailer=null;$trucks=$this->trucks->available();$carriers=$this->carriers->active();$this->view('trailers/create',compact('trailer','trucks','carriers')); }
    public function store(): void { Auth::requireRole(['owner','admin','dispatcher','maintenance']);Csrf::verify();if(trim((string)($_POST['trailer_number']??''))===''){set_old($_POST);$this->flash('danger','Trailer number is required.');$this->redirect('/trailers/create');}$this->trailers->create($_POST);log_activity('trailer_created','Created trailer '.trim((string)$_POST['trailer_number']));$this->flash('success','Trailer created successfully.');$this->redirect('/trailers'); }
    public function edit(): void { Auth::requireRole(['owner','admin','dispatcher','maintenance']);$trailer=$this->trailers->find((int)($_GET['id']??0));if(!$trailer){$this->flash('danger','Trailer not found.');$this->redirect('/trailers');}$trucks=$this->trucks->available();$carriers=$this->carriers->active();$this->view('trailers/edit',compact('trailer','trucks','carriers')); }
    public function update(): void { Auth::requireRole(['owner','admin','dispatcher','maintenance']);Csrf::verify();$id=(int)($_POST['id']??0);if(!$id||trim((string)($_POST['trailer_number']??''))===''){set_old($_POST);$this->flash('danger','Trailer number is required.');$this->redirect('/trailers/edit?id='.$id);}$this->trailers->update($id,$_POST);log_activity('trailer_updated','Updated trailer '.trim((string)$_POST['trailer_number']));$this->flash('success','Trailer updated successfully.');$this->redirect('/trailers'); }
    public function delete(): void { Auth::requireRole(['owner','admin','dispatcher','maintenance']);Csrf::verify();$this->trailers->delete((int)($_POST['id']??0));$this->flash('success','Trailer deleted successfully.');$this->redirect('/trailers'); }
}
