<?php

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