<?php

namespace App\Api\V1\Controllers;

use Symfony\Component\HttpKernel\Exception\HttpException;
use Tymon\JWTAuth\JWTAuth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Driver;
use App\Models\Route;
use App\Models\RouteStop;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Auth;
use Illuminate\Support\Facades\Log;

class RouteController extends Controller
{

    public function index(Request $request)
    {
        $user_id = $request->input('user_id');
        $driver = Driver::where('user_id', $user_id)->first();
        $routes = Route::with('routeStops')->where('driver_id', $driver->id)->get();

        return response()->json($routes);
    }

    public function create(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|max:255',
            'driver_id' => 'required',
            'type' => 'required',
        ]);

        $stops = $request->input('stops');

        $route = new Route($validatedData);
        if(!$route->save()) {
            throw new HttpException(500);
        }

        foreach ($stops as $stop) {
            $newStop = new RouteStop();
            $newStop->route_id = $route->id;
            $newStop->lat = $stop['lat'];
            $newStop->lng = $stop['lng'];
            if ($stop['kid'] !== null) {
                $newStop->kid_id = $stop['kid']['id'];
            }
            if ($stop['school'] !== null) {
                $newStop->school_id = $stop['school']['id'];
            }
            if(!$newStop->save()) {
                throw new HttpException(500);
            }
        }

        $route = Route::with('routeStops')->findOrFail($route->id);

        return response()->json($route);
    }


    public function update(Request $request)
    {

        $validatedData = $request->validate([
            'name' => 'required|max:255',
            'driver_id' => 'required',
            'type' => 'required',
            'id' => 'required'
        ]);

        $stops = $request->input('stops');

        $route = Route::where('id',$request->input('id'))->first();
        $route->name = $request->input('name');
        $route->driver_id = $request->input('driver_id');
        $route->type = $request->input('type');
        if(!$route->save()) {
            throw new HttpException(500);
        }

        //$route_StopsBDD =  RouteStop::where('route_id',$route->id);
        $route_StopsBDD =  RouteStop::where('route_id',$route->id)->orderBy('created_at', 'DESC')->get();

        $contador = 1;
        foreach ($stops as $stop) {

            $valor = $this->comprobarRegistrobdd($stop,$route_StopsBDD);
            if($valor == 0){
                $newStop = RouteStop::where('route_id',$route->id)->where('kid_id',$stop['kid']['id'])->first();
                $newStop->order = $contador;
                $newStop->save();
            }
            if($valor == -1) {
                $newStop = new RouteStop();
                $newStop->route_id = $route->id;
                $newStop->lat = $stop['lat'];
                $newStop->lng = $stop['lng'];
                $newStop->order = $contador;
                if ($stop['kid'] !== null) {
                    $newStop->kid_id = $stop['kid']['id'];
                }
                if ($stop['school'] !== null) {
                    $newStop->school_id = $stop['school']['id'];
                }
                if (!$newStop->save()) {
                    throw new HttpException(500);
                }
            }
            $contador++;
        }


        foreach ($route_StopsBDD as $stop){
            RouteStop::where('route_id',$route->id)->where('kid_id',$stop['kid']['id'])->delete();
        }

        $route = Route::with('routeStops')->findOrFail($route->id);
        return response()->json($route);
    }

     function comprobarRegistrobdd($stopLocal,$route_StopsBDD){
        $valor = -1;

        foreach ($route_StopsBDD as $key => $stopBDD) {
            if($stopBDD['kid_id'] == $stopLocal['kid']['id']) {$valor = 0; unset($route_StopsBDD[$key]); break;}
            //if($stopBDD['kid_id'] != $stopLocal['kid']['id']) {$valor = 1;}
        }
        return $valor;
    }




    public function show(Request $request, $id)
    {
        $route = Route::with('routeStops.kid.school', 'routeStops.school')->findOrFail($id);

        return response()->json($route);
    }

    public function delete(Request $request, $id)
    {
        $route = Route::find($id);
        $route->delete();

        return response()->json($route);
    }
} 