<?php

namespace Modules\Transport\Services;

use App\Models\ActivityLogModel;
use App\Models\TransportMapSettingsModel;

class MapSettingsService
{
    protected TransportMapSettingsModel $settings;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->settings = new TransportMapSettingsModel();
        $this->activity = new ActivityLogModel();
    }

    public function getSettings(): array
    {
        return $this->settings->getSettings();
    }

    public function update(array $input, ?int $actingUserId): array
    {
        $provider = (string) ($input['default_provider'] ?? 'openstreetmap');
        if (! in_array($provider, ['openstreetmap', 'google'], true)) {
            $provider = 'openstreetmap';
        }

        $zoom = (int) ($input['default_zoom'] ?? 12);
        if ($zoom < 1 || $zoom > 20) {
            $zoom = 12;
        }

        $data = [
            'default_provider'  => $provider,
            'google_api_key'    => trim((string) ($input['google_api_key'] ?? '')) ?: null,
            'default_latitude'  => round((float) ($input['default_latitude'] ?? 26.0667), 7),
            'default_longitude' => round((float) ($input['default_longitude'] ?? 50.5577), 7),
            'default_zoom'      => $zoom,
            'updated_by'        => $actingUserId,
        ];

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

        $this->activity->log('transport_maps', 'settings_updated', $actingUserId, 'Updated transport map settings', '1');

        return ['success' => true];
    }
}
