<?php

namespace Modules\Transport\Controllers;

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

class LocationController extends BaseController
{
    protected TransportLocationModel $locations;
    protected LocationService $service;

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

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

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

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

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

    public function store()
    {
        if (! $this->validate([
            'name'          => 'required|min_length[2]|max_length[200]',
            'location_type' => 'permit_empty|in_list[depot,stop,hub,warehouse,customer,other]',
            '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/locations/' . $result['id'])->with('success', 'Location created.');
    }

    public function show(int $id)
    {
        $location = $this->locations->find($id);
        if (! $location) {
            return redirect()->to('/transport/locations')->with('error', 'Location not found.');
        }

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

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

        return view('Modules\Transport\Views\locations\edit', array_merge($this->baseViewData(), [
            'title'       => 'Edit Location',
            'location'    => $location,
            'mapSettings' => (new MapSettingsService())->getSettings(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name'          => 'required|min_length[2]|max_length[200]',
            'location_type' => 'permit_empty|in_list[depot,stop,hub,warehouse,customer,other]',
            '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/locations/' . $id)->with('success', 'Location updated.');
    }

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

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