<?php

namespace Modules\Transport\Controllers;

use App\Controllers\BaseController;
use App\Models\TransportDriverModel;
use App\Models\TransportLocationModel;
use App\Models\TransportVehicleModel;
use Modules\Transport\Services\VehicleService;

class VehicleController extends BaseController
{
    protected TransportVehicleModel $vehicles;
    protected VehicleService $service;

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

    public function index()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;
        $type   = $this->request->getGet('type') ?: null;

        $entries = $this->vehicles
            ->scopeForList($search ?: null, $status, $type)
            ->orderBy('transport_vehicles.registration_number', 'ASC')
            ->paginate(25);

        return view('Modules\Transport\Views\vehicles\index', array_merge($this->baseViewData(), [
            'title'   => 'Vehicles',
            'entries' => $entries,
            'pager'   => $this->vehicles->pager,
            'filters' => compact('search', 'status', 'type'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Transport\Views\vehicles\create', array_merge($this->baseViewData(), [
            'title'     => 'Add Vehicle',
            'vehicle'   => [],
            'drivers'   => (new TransportDriverModel())->getActive(),
            'locations' => (new TransportLocationModel())->getActive(),
            'mapSettings' => (new \Modules\Transport\Services\MapSettingsService())->getSettings(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'registration_number' => 'required|max_length[50]',
            'vehicle_type'        => 'permit_empty|in_list[car,van,truck,bus,motorcycle,other]',
            'fuel_type'           => 'permit_empty|in_list[petrol,diesel,electric,hybrid,other]',
            'status'              => 'permit_empty|in_list[active,maintenance,retired]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/transport/vehicles/' . $result['id'])->with('success', 'Vehicle created.');
    }

    public function show(int $id)
    {
        $vehicle = $this->vehicles->scopeForList()->where('transport_vehicles.id', $id)->first();
        if (! $vehicle) {
            return redirect()->to('/transport/vehicles')->with('error', 'Vehicle not found.');
        }

        return view('Modules\Transport\Views\vehicles\show', array_merge($this->baseViewData(), [
            'title'   => $vehicle['registration_number'],
            'vehicle' => $vehicle,
            'mapSettings' => (new \Modules\Transport\Services\MapSettingsService())->getSettings(),
        ]));
    }

    public function editForm(int $id)
    {
        $vehicle = $this->vehicles->find($id);
        if (! $vehicle) {
            return redirect()->to('/transport/vehicles')->with('error', 'Vehicle not found.');
        }

        return view('Modules\Transport\Views\vehicles\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Vehicle',
            'vehicle'   => $vehicle,
            'drivers'   => (new TransportDriverModel())->getActive(),
            'locations' => (new TransportLocationModel())->getActive(),
            'mapSettings' => (new \Modules\Transport\Services\MapSettingsService())->getSettings(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'registration_number' => 'required|max_length[50]',
            'vehicle_type'        => 'permit_empty|in_list[car,van,truck,bus,motorcycle,other]',
            'fuel_type'           => 'permit_empty|in_list[petrol,diesel,electric,hybrid,other]',
            'status'              => 'permit_empty|in_list[active,maintenance,retired]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->update($id, $this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/transport/vehicles/' . $id)->with('success', 'Vehicle updated.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/transport/vehicles')->with('error', $result['error']);
        }

        return redirect()->to('/transport/vehicles')->with('success', 'Vehicle deleted.');
    }
}
