<?php

class DriverController extends Controller
{
    private Driver $drivers;
    private Carrier $carriers;

    public function __construct(){ $this->drivers=new Driver();$this->carriers=new Carrier(); }

    public function index(): void
    {
        Auth::requireRole(['owner','admin','dispatcher']);$search=trim((string)($_GET['search']??''));$drivers=$this->drivers->all($search?:null);$this->view('drivers/index',compact('drivers','search'));clear_old();
    }

    public function create(): void
    {
        Auth::requireRole(['owner','admin','dispatcher']);$driver=null;$carriers=$this->carriers->active();$this->view('drivers/create',compact('driver','carriers'));
    }

    public function store(): void
    {
        Auth::requireRole(['owner','admin','dispatcher']);Csrf::verify();
        if(trim((string)($_POST['name']??''))===''){set_old($_POST);$this->flash('danger','Driver name is required.');$this->redirect('/drivers/create');}
        $this->drivers->create($_POST);log_activity('driver_created','Created driver '.trim((string)$_POST['name']));$this->flash('success','Driver created successfully.');$this->redirect('/drivers');
    }

    public function edit(): void
    {
        Auth::requireRole(['owner','admin','dispatcher']);$driver=$this->drivers->find((int)($_GET['id']??0));if(!$driver){$this->flash('danger','Driver not found.');$this->redirect('/drivers');}
        $carriers=$this->carriers->active();$this->view('drivers/edit',compact('driver','carriers'));
    }

    public function update(): void
    {
        Auth::requireRole(['owner','admin','dispatcher']);Csrf::verify();$id=(int)($_POST['id']??0);
        if(!$id||trim((string)($_POST['name']??''))===''){set_old($_POST);$this->flash('danger','Driver name is required.');$this->redirect('/drivers/edit?id='.$id);}
        $this->drivers->update($id,$_POST);log_activity('driver_updated','Updated driver '.trim((string)$_POST['name']));$this->flash('success','Driver updated successfully.');$this->redirect('/drivers');
    }

    public function delete(): void
    {
        Auth::requireRole(['owner','admin','dispatcher']);Csrf::verify();$this->drivers->delete((int)($_POST['id']??0));$this->flash('success','Driver deleted successfully.');$this->redirect('/drivers');
    }
}
