<?php
namespace App\Controllers\Responder;

use Core\Auth;
use Core\Request;
use Core\Response;
use App\Models\Responder;

class LocationController
{
    public function updateCoordinates()
    {
        $data = Request::json(); // Fetching raw JSON from the AJAX POST request
        
        if (!isset($data['latitude']) || !isset($data['longitude'])) {
            return Response::json(['status' => 'error', 'message' => 'Coordinates missing.'], Response::BAD_REQUEST);
        }

        // Get the responder profile for the logged-in user
        $responder = Responder::where('user_id', Auth::user()['id']);

        if (!$responder) {
            return Response::json(['status' => 'error', 'message' => 'Responder profile not found.'], Response::FORBIDDEN);
        }

        // Update the responder's base/current location in the database.
        // The Proximity Proximity Calculation algorithm uses these fields to find nearest units.
        Responder::update($responder['id'], [
            'base_latitude' => $data['latitude'],
            'base_longitude' => $data['longitude']
        ]);

        return Response::json(['status' => 'success']);
    }
}