<?php

namespace Modules\Transport\Controllers;

use App\Controllers\BaseController;
use App\Models\ActivityLogModel;
use App\Models\TransportAiSettingsModel;
use App\Models\TransportLocationModel;

class AiSettingsController extends BaseController
{
    protected TransportAiSettingsModel $settings;

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

    public function form()
    {
        $depots = (new TransportLocationModel())
            ->where('status', 'active')
            ->where('location_type', 'depot')
            ->where('latitude IS NOT NULL')
            ->where('longitude IS NOT NULL')
            ->orderBy('name', 'ASC')
            ->findAll();

        return view('Modules\Transport\Views\ai\settings', array_merge($this->baseViewData(), [
            'title'    => 'AI Planner Settings',
            'settings' => $this->settings->getSettings(),
            'depots'   => $depots,
        ]));
    }

    public function update()
    {
        if (! $this->validate([
            'fuel_price_per_litre'     => 'required|decimal',
            'cost_per_km'              => 'required|decimal',
            'driver_max_daily_minutes' => 'required|integer|greater_than[0]',
            'pickup_service_minutes'   => 'required|integer|greater_than_equal_to[0]',
            'arrival_buffer_minutes'   => 'required|integer|greater_than_equal_to[0]',
            'road_factor'              => 'required|decimal|greater_than[0]',
            'average_speed_kmh'        => 'required|decimal|greater_than[0]',
            'osrm_base_url'            => 'required|valid_url',
            'llm_provider'             => 'required|in_list[none,openai]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $userId = (int) $this->session->get('user_id');
        $post   = $this->request->getPost();

        $data = [
            'fuel_price_per_litre'     => $post['fuel_price_per_litre'],
            'cost_per_km'              => $post['cost_per_km'],
            'driver_max_daily_minutes' => (int) $post['driver_max_daily_minutes'],
            'pickup_service_minutes'   => (int) $post['pickup_service_minutes'],
            'arrival_buffer_minutes'   => (int) $post['arrival_buffer_minutes'],
            'default_base_location_id' => ! empty($post['default_base_location_id']) ? (int) $post['default_base_location_id'] : null,
            'road_factor'              => $post['road_factor'],
            'average_speed_kmh'        => $post['average_speed_kmh'],
            'osrm_base_url'            => rtrim(trim((string) $post['osrm_base_url']), '/'),
            'llm_provider'             => $post['llm_provider'],
            'llm_api_base_url'         => trim((string) ($post['llm_api_base_url'] ?? '')) ?: null,
            'llm_model'                => trim((string) ($post['llm_model'] ?? '')) ?: null,
            'updated_by'               => $userId,
        ];

        foreach (['consumption_car', 'consumption_van', 'consumption_truck', 'consumption_bus', 'consumption_motorcycle', 'consumption_other'] as $field) {
            if (isset($post[$field]) && is_numeric($post[$field])) {
                $data[$field] = $post[$field];
            }
        }

        // Keep the stored key unless a new one is provided (the form never echoes it back).
        $apiKey = trim((string) ($post['llm_api_key'] ?? ''));
        if ($apiKey !== '') {
            $data['llm_api_key'] = $apiKey;
        }
        if (! empty($post['clear_llm_api_key'])) {
            $data['llm_api_key'] = null;
        }

        if ($this->settings->find(1)) {
            $this->settings->update(1, $data);
        } else {
            $this->settings->insert(['id' => 1] + $data);
        }

        (new ActivityLogModel())->log('transport_ai', 'settings_updated', $userId, 'Updated AI planner settings', '1');

        return redirect()->to('/transport/ai/settings')->with('success', 'AI planner settings saved.');
    }
}
