<?php

namespace App\Http\Controllers\Api;

use App\Events\GpsPingReceived;
use App\Http\Controllers\Controller;
use App\Models\GpsPing;
use App\Models\Trip;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GpsController extends Controller
{
    /**
     * POST /api/trips/{trip}/ping
     * Driver sends a GPS ping during an active trip.
     */
    public function ping(Request $request, Trip $trip): JsonResponse
    {
        $request->validate([
            'lat'      => 'required|numeric|between:-90,90',
            'lng'      => 'required|numeric|between:-180,180',
            'accuracy' => 'nullable|numeric|min:0',
            'heading'  => 'nullable|numeric|min:0|max:360',
        ]);

        abort_unless($trip->driver_id === $request->user()->id, 403);
        abort_unless($trip->status === 'active', 422, 'Safari hii haipo katika hali ya kufanya kazi.');

        $ping = GpsPing::create([
            'trip_id'     => $trip->id,
            'driver_id'   => $request->user()->id,
            'lat'         => $request->lat,
            'lng'         => $request->lng,
            'accuracy'    => $request->accuracy,
            'heading'     => $request->heading,
            'recorded_at' => now(),
        ]);

        GpsPingReceived::dispatch($ping);

        return response()->json(['ok' => true], 200);
    }

    /**
     * GET /api/trips/{trip}/location
     * Rider gets the last known driver location.
     */
    public function lastLocation(Trip $trip): JsonResponse
    {
        abort_unless(in_array($trip->status, ['active', 'completed']), 404);

        $ping = GpsPing::where('trip_id', $trip->id)
            ->orderByDesc('recorded_at')
            ->first();

        if (!$ping) {
            return response()->json(['location' => null]);
        }

        return response()->json([
            'location' => [
                'lat'         => (float) $ping->lat,
                'lng'         => (float) $ping->lng,
                'heading'     => $ping->heading ? (float) $ping->heading : null,
                'recorded_at' => $ping->recorded_at->toISOString(),
            ],
        ]);
    }
}
