<?php
namespace App\Http\Controllers;

use App\Models\Route;
use App\Models\Mountain;
use Illuminate\Http\Request;
use App\Traits\ApiResponse;


class RouteController extends Controller
{
    use ApiResponse;


    public function index()
    {
        return Route::where('user_id', auth()->id())->get();
    }

    public function mountainRoutes($id)
    {
        $res = Mountain::where('id', $id)->with('routes')->get();
        if ($res) {
            return response()->json($res->first()->routes, 201);
        }
        return response()->json($res);
    }
    public function publicRoute($id)
    {
        $log = Route::where('public', true)->where('id', '=', $id)->with('mountains')->get()->first();
        return response()->json($log);

    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'description' => 'string',
            'distance' => 'numeric',
            'title' => 'string',
            'points' => 'string'
        ]);

        $route = Route::create([
            'user_id' => auth()->id(),
            'description' => $validated['description'],
            'distance' => $validated['distance'],
            'title' => $validated['title'],
            'points' => $validated['points'],
            'public' => 0

        ]);

        $mountains = $request['mountains'];

        if ($route && $mountains) {
            $route->mountains()->attach($mountains);
        }

        return response()->json($mountains, 201);
    }

    public function show($id)
    {
        $log = Route::where('user_id', '=', auth()->id())->where('id', '=', $id)->with('mountains')->get()->first();
        return response()->json($log);
    }

    public function update(Request $request, Route $route)
    {
        $validated = $request->validate([
            'id' => 'required',
            'description' => 'string',
            'distance' => 'numeric',
            'title' => 'string',
            'points' => 'string'
        ]);

        $route = Route::where('user_id', '=', auth()->id())->where('id', '=', $validated['id'])->first();


        $route->mountains()->detach();
        $res = $route->update([
            'description' => $validated['description'],
            'distance' => $validated['distance'],
            'title' => $validated['title'],
            'points' => $validated['points'],
        ]);

        $mountains = $request['mountains'];

        if ($route && $mountains) {
            $route->mountains()->attach($mountains);
        }


        return response()->json([
            'message' => $res,
        ]);
    }

    public function destroy($id)
    {

        $res = Route::where('user_id', '=', auth()->id())->where('id', '=', $id)->delete();
        return response()->json([
            'message' => $res,
        ]);
    }
}