<?php

namespace Modules\Transport\Controllers;

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

class MapController extends BaseController
{
    protected MapSettingsService $service;

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

    public function viewer()
    {
        $settings = $this->service->getSettings();

        $locations = (new TransportLocationModel())->getWithCoordinates(null, 300);
        $vehicles  = (new TransportVehicleModel())
            ->where('status', 'active')
            ->where('latitude IS NOT NULL')
            ->where('longitude IS NOT NULL')
            ->findAll();

        return view('Modules\Transport\Views\maps\viewer', array_merge($this->baseViewData(), [
            'title'       => 'Fleet Map',
            'mapSettings' => $settings,
            'locations'   => $locations,
            'vehicles'    => $vehicles,
        ]));
    }

    public function settingsForm()
    {
        return view('Modules\Transport\Views\maps\settings', array_merge($this->baseViewData(), [
            'title'    => 'Map Settings',
            'settings' => $this->service->getSettings(),
        ]));
    }

    public function updateSettings()
    {
        if (! $this->validate([
            'default_provider' => 'required|in_list[openstreetmap,google]',
            'default_zoom'     => 'permit_empty|integer|greater_than[0]|less_than[21]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/transport/maps/settings')->with('success', 'Map settings saved.');
    }
}
