<?php

class MaintenanceController extends Controller
{
    private Maintenance $maintenance;
    private Truck $trucks;
    private Trailer $trailers;

    public function __construct()
    {
        $this->maintenance = new Maintenance();
        $this->trucks = new Truck();
        $this->trailers = new Trailer();
    }

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

    public function create(): void
    {
        Auth::requireRole(['owner','admin','maintenance']);
        $trucks = $this->trucks->all();
        $trailers = $this->trailers->all();
        $this->view('maintenance/create', compact('trucks', 'trailers'));
    }

    public function store(): void
    {
        Auth::requireRole(['owner','admin','maintenance']);
        Csrf::verify();
        if (empty(trim($_POST['service_type'] ?? '')) || empty($_POST['service_date']) || (empty($_POST['truck_id']) && empty($_POST['trailer_id']))) {
            set_old($_POST);
            $this->flash('danger', 'Equipment, service type, and service date are required.');
            $this->redirect('/maintenance/create');
        }
        $this->maintenance->create($_POST);
        log_activity('maintenance_created', 'Added maintenance record');
        $this->flash('success', 'Maintenance record saved successfully.');
        $this->redirect('/maintenance');
    }

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