<?php

namespace Modules\Transport\Controllers;

use App\Controllers\BaseController;
use App\Traits\ExportsReport;
use Modules\Transport\Services\DriverScheduleExportService;

class DriverScheduleExportController extends BaseController
{
    use ExportsReport;

    protected DriverScheduleExportService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->service = new DriverScheduleExportService();
    }

    public function index()
    {
        $filters = $this->service->resolveFilters($this->request->getGet() ?? []);
        $trips   = $this->service->fetchTrips($filters);
        $groups  = $this->service->groupByDriver($trips);
        $stopsByTrip = $this->service->stopsForTrips($trips);
        $payload = $this->service->buildExportPayload($trips, $filters);

        if ($export = $this->exportSections(
            $payload['filename'],
            $payload['title'],
            $payload['sections'] !== []
                ? $payload['sections']
                : [['title' => 'No trips', 'headers' => ['Message'], 'rows' => [['No driver schedules match the selected filters.']]]],
            $payload['subtitle']
        )) {
            return $export;
        }

        return view('Modules\Transport\Views\schedules\export', array_merge($this->baseViewData(), [
            'title'   => 'Driver Schedule Export',
            'filters' => $filters,
            'drivers' => $this->service->activeDrivers(),
            'groups'  => $groups,
            'stopsByTrip' => $stopsByTrip,
            'tripCount' => count($trips),
            'exportQuery' => $this->exportQuery([
                'driver_id' => $filters['driver_id'] ?? '',
                'date_from' => $filters['date_from'],
                'date_to'   => $filters['date_to'],
                'status'    => $filters['status'] ?? '',
            ]),
        ]));
    }
}
