<?php

namespace App\Http\Controllers;

use App\Models\Garage;
use App\Models\Location;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class LocationController extends Controller
{

    public function index()
    {
         $agents = Location::with('user')->get()->toArray();
        $markers = Garage::get()->toArray();
        return view('configuration.location.index',compact('agents','markers'));
    }

    /**
     * Create Location
     * @queryParam lat  required
     * @queryParam lng  required
     */

    public function store(Request $request)
    {
        try {

            $validateloc = Validator::make(
                $request->all(),
                [
                    'lat' => 'required',
                    'lng' => 'required',
                ]
            );
            if ($validateloc->fails()) {
                return response()->json([
                    'status' => false,
                    'message' => 'validation error',
                    'errors' => $validateloc->errors()
                ], 401);
            }

            Location::updateOrCreate(['user_id' => Auth::user()->id], [
                'lat' => $request->lat,
                'lng' => $request->lng,
            ]);


            return response()->json([
                'status' => true,
                'message' => 'Updated Successfully',
            ], 200);

        } catch (\Throwable $th) {
            return response()->json([
                'status' => false,
                'message' => $th->getMessage()
            ], 500);
        }
    }
}
