<?php

class CarrierPortalController extends Controller
{
    private Carrier $carriers;
    private Load $loads;

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

    public function index(): void
    {
        Auth::requireRole(['carrier']);
        $user = Auth::user();
        $carrierId = (int) ($user['carrier_id'] ?? 0);
        $carrier = $carrierId ? $this->carriers->find($carrierId) : null;
        $loads = $carrier ? $this->carriers->loads($carrierId) : [];
        $equipment = $carrier ? $this->carriers->equipment($carrierId) : [];
        $documents = $carrier ? (new Document())->forRelation('carrier', $carrierId) : [];
        $this->view('carrier_portal/index', compact('carrier','loads','equipment','documents'));
    }

    public function showLoad(): void
    {
        Auth::requireRole(['carrier']);
        $user = Auth::user();
        $load = $this->loads->find((int) ($_GET['id'] ?? 0));
        if (!$load || (int) ($load['carrier_id'] ?? 0) !== (int) ($user['carrier_id'] ?? 0)) {
            $this->flash('danger', 'Load not found.');
            $this->redirect('/carrier');
        }
        $documents = (new Document())->forLoadWithStops((int) $load['id']);
        $events = $this->loads->events((int) $load['id']);
        $temperatureLogs = (new TemperatureLog())->forLoad((int) $load['id']);
        $this->view('carrier_portal/show', compact('load','documents','events','temperatureLogs'));
    }
}
