<?php

namespace Modules\Transport\Controllers;

use App\Controllers\BaseController;
use App\Models\TransportDriverModel;
use App\Models\TransportRouteModel;
use App\Models\TransportScheduleModel;
use App\Models\TransportScheduleStopModel;
use App\Models\TransportVehicleModel;
use Modules\Transport\Services\ScheduleService;

class ScheduleController extends BaseController
{
    protected TransportScheduleModel $schedules;
    protected ScheduleService $service;

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

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

        $entries = $this->schedules
            ->scopeForList($search ?: null, $status, $dateFrom, $dateTo)
            ->orderBy('transport_schedules.schedule_date', 'DESC')
            ->orderBy('transport_schedules.departure_time', 'ASC')
            ->paginate(25);

        $unseenAiChanges = $this->schedules->countUnseenAiFlags();

        $html = view('Modules\Transport\Views\schedules\index', array_merge($this->baseViewData(), [
            'title'           => 'Scheduling',
            'entries'         => $entries,
            'pager'           => $this->schedules->pager,
            'filters'         => compact('search', 'status', 'dateFrom', 'dateTo'),
            'unseenAiChanges' => $unseenAiChanges,
        ]));

        // The red AI-change indicators vanish after they have been displayed.
        $seenIds = [];
        foreach ($entries as $entry) {
            if (! empty($entry['ai_flag']) && empty($entry['ai_flag_seen_at'])) {
                $seenIds[] = (int) $entry['id'];
            }
        }
        $this->schedules->markAiFlagsSeen($seenIds);

        return $html;
    }

    public function createForm()
    {
        return view('Modules\Transport\Views\schedules\create', array_merge($this->baseViewData(), [
            'title'    => 'Schedule Trip',
            'schedule' => [],
            'routes'   => (new TransportRouteModel())->getActive(),
            'vehicles' => (new TransportVehicleModel())->getActive(),
            'drivers'  => (new TransportDriverModel())->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'title'         => 'required|min_length[2]|max_length[200]',
            'schedule_date' => 'required|valid_date',
            'priority'      => 'permit_empty|in_list[low,normal,high,urgent]',
            'status'        => 'permit_empty|in_list[planned,scheduled]',
        ])) {
            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/scheduling/' . $result['id'])->with('success', 'Trip scheduled.');
    }

    public function show(int $id)
    {
        $schedule = $this->schedules->scopeForList()->where('transport_schedules.id', $id)->first();
        if (! $schedule) {
            return redirect()->to('/transport/scheduling')->with('error', 'Schedule not found.');
        }

        return view('Modules\Transport\Views\schedules\show', array_merge($this->baseViewData(), [
            'title'    => $schedule['number'],
            'schedule' => $schedule,
            'stops'    => (new TransportScheduleStopModel())->getForSchedule($id),
        ]));
    }

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

        if (! in_array($schedule['status'], ['planned', 'scheduled'], true)) {
            return redirect()->to('/transport/scheduling/' . $id)
                ->with('error', 'Only planned or scheduled trips can be edited.');
        }

        return view('Modules\Transport\Views\schedules\edit', array_merge($this->baseViewData(), [
            'title'    => 'Edit Trip',
            'schedule' => $schedule,
            'routes'   => (new TransportRouteModel())->getActive(),
            'vehicles' => (new TransportVehicleModel())->getActive(),
            'drivers'  => (new TransportDriverModel())->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'title'         => 'required|min_length[2]|max_length[200]',
            'schedule_date' => 'required|valid_date',
            'priority'      => 'permit_empty|in_list[low,normal,high,urgent]',
            'status'        => 'permit_empty|in_list[planned,scheduled]',
        ])) {
            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/scheduling/' . $id)->with('success', 'Trip updated.');
    }

    public function confirm(int $id)
    {
        $result = $this->service->transition($id, 'scheduled', (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Trip confirmed.');
    }

    public function start(int $id)
    {
        $result = $this->service->transition($id, 'in_progress', (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Trip started.');
    }

    public function complete(int $id)
    {
        $result = $this->service->transition($id, 'completed', (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Trip completed.');
    }

    public function cancel(int $id)
    {
        $result = $this->service->transition($id, 'cancelled', (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Trip cancelled.');
    }

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

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