<?php

namespace App\Http\Controllers;

use App\Models\TrafficEvent;
use App\Models\TrafficVisit;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;

class AnalyticsEventController extends Controller
{
    public function store(Request $request)
    {
        if (!config('analytics.enabled', true)) {
            return response()->noContent();
        }

        $data = $request->validate([
            'name' => ['required', 'string', 'max:100'],
            'properties' => ['nullable', 'array'],
        ]);

        $sessionId = $request->session()->getId();
        $userId = optional($request->user())->id;

        // Associate to the most recent visit of this session (last 2 hours)
        $visit = TrafficVisit::query()
            ->where('session_id', $sessionId)
            ->where('created_at', '>=', Carbon::now()->subHours(2))
            ->latest('id')
            ->first();

        // If this is a precise geolocation event, try to enrich the latest visit
        if (($data['name'] ?? '') === 'geolocation' && is_array($data['properties'] ?? null)) {
            $lat = Arr::get($data, 'properties.lat');
            $lon = Arr::get($data, 'properties.lon');
            if (is_numeric($lat) && is_numeric($lon) && $visit) {
                try {
                    $url = 'https://nominatim.openstreetmap.org/reverse';
                    $res = Http::withHeaders([
                        'User-Agent' => 'FamilyTree/1.0 (+https://example.com)'
                    ])->get($url, [
                        'format' => 'jsonv2',
                        'lat' => $lat,
                        'lon' => $lon,
                    ]);
                    if ($res->ok()) {
                        $j = $res->json();
                        $addr = Arr::get($j, 'address', []);
                        $city = Arr::get($addr, 'city')
                            ?? Arr::get($addr, 'town')
                            ?? Arr::get($addr, 'village')
                            ?? Arr::get($addr, 'municipality')
                            ?? Arr::get($addr, 'suburb');
                        $country = Arr::get($addr, 'country');
                        $visit->update([
                            'latitude' => $lat,
                            'longitude' => $lon,
                            'city' => $city ?: $visit->city,
                            'country' => $country ?: $visit->country,
                        ]);
                    }
                } catch (\Throwable $e) {
                    // silently ignore enrichment failures
                }
            }
        }

        TrafficEvent::create([
            'visit_id' => $visit?->id,
            'session_id' => $sessionId,
            'user_id' => $userId,
            'name' => $data['name'],
            'properties' => $data['properties'] ?? [],
        ]);

        return response()->noContent();
    }
}
