<?php

namespace Modules\Transport\Controllers;

use App\Controllers\BaseController;
use App\Models\TransportLocationModel;
use App\Models\TransportRouteModel;
use App\Models\TransportRouteStopModel;
use Modules\Transport\Services\MapSettingsService;
use Modules\Transport\Services\RouteService;

class RouteController extends BaseController
{
    protected TransportRouteModel $routes;
    protected TransportRouteStopModel $stops;
    protected RouteService $service;

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

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

        $entries = $this->routes
            ->scopeForList($search ?: null, $status)
            ->orderBy('transport_routes.name', 'ASC')
            ->paginate(25);

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

    public function createForm()
    {
        return view('Modules\Transport\Views\routes\create', array_merge($this->baseViewData(), [
            'title'     => 'Add Route',
            'route'     => [],
            'stops'     => [],
            'locations' => (new TransportLocationModel())->getActive(),
            'mapSettings' => (new MapSettingsService())->getSettings(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name'   => 'required|min_length[2]|max_length[200]',
            'status' => 'permit_empty|in_list[active,inactive]',
        ])) {
            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/routes/' . $result['id'])->with('success', 'Route created.');
    }

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

        $stops = $this->stops->getForRoute($id);

        return view('Modules\Transport\Views\routes\show', array_merge($this->baseViewData(), [
            'title'       => $route['name'],
            'route'       => $route,
            'stops'       => $stops,
            'mapSettings' => (new MapSettingsService())->getSettings(),
        ]));
    }

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

        return view('Modules\Transport\Views\routes\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Route',
            'route'     => $route,
            'stops'     => $this->stops->getForRoute($id),
            'locations' => (new TransportLocationModel())->getActive(),
            'mapSettings' => (new MapSettingsService())->getSettings(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name'   => 'required|min_length[2]|max_length[200]',
            'status' => 'permit_empty|in_list[active,inactive]',
        ])) {
            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/routes/' . $id)->with('success', 'Route updated.');
    }

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

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