<?php

namespace App\Api\V1\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use App\Models\School;
use App\Models\User;
use App\Models\Driver;
use App\Models\Kid;
use App\Models\File;
use App\Models\Route;
use App\Models\RouteLog;

use Illuminate\Support\Facades\Log;


use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

use Carbon\Carbon;

use App\Traits\Hire;
use App\Traits\OneSignalMessages;

use Illuminate\Database\Eloquent\Builder;
use DB;
use Illuminate\Support\Facades\Storage;

use Auth;
use Validator;


/**
 *
 *
 * @mixin Eloquent
 */
class AdminController extends Controller
{

    use Helpers;

    public function login(Request $request)
    {
        $credentials = $request->only(['email', 'password']);

        try {
            $token = Auth::guard()->attempt($credentials);

            if (!$token) {
                throw new AccessDeniedHttpException();
            }
            $user = Auth::user();


            // valida solo choferes, administrador y colegios
           /* $allowedUserTypes = [1, 3, 4];
            if (!in_array($user->user_type_id, $allowedUserTypes)) {
                return response()->json([
                    'message' => '403 Forbidden',
                    'status_code' => 403
                ], 403);
            }*/

            /*if (!$user->hasRole('admin')) {
                throw new AccessDeniedHttpException();
            }*/
        } catch (JWTException $e) {
            throw new HttpException(500);
        }

        return response()
            ->json([
                'status' => 'ok',
                'token' => $token,
                'expires_in' => Auth::guard()->factory()->getTTL() * 60
            ]);
    }

    public function college_index(Request $request)
    {

        $response = null;

        $response['data'] = School::orderBy('id', 'DESC')->get();


        return $response;
    }

    public function college_show(Request $request, $id)
    {

        $response = null;

        $response['data'] = School::with('kids', 'drivers.user')->findOrFail($id);
        return $response;
    }

    public function college_show_user(Request $request, $id)
    {

        $response = null;

        $response['data'] = School::with('kids', 'drivers.user')->where('user_id', $id)->first();
        return $response;
    }

    public function college_new(Request $request)
    {
        $validatedData = $request->validate([
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'password' => 'required|min:6',
            'school_name' => 'required|max:255',
            'user_email' => 'required|email',
            'identification' => 'required|unique:user',
            'working_time' => 'nullable',
            'district' => 'required',
            'address' => 'required',
            'school_email' => 'nullable',
            'school_phone' => 'nullable',
            'user_phone' => 'nullable',
            'lat' => 'nullable',
            'lng' => 'nullable',

            'first_arrival_time' => 'nullable',
            'first_closing_time' => 'nullable',
            'second_arrival_time' => 'nullable',
            'second_closing_time' => 'nullable',
        ]);


        $usuarioAdmin = User::where('email', $validatedData['user_email'])->first();
        if($usuarioAdmin){
            return response()->json(['validacion_usuario' => 'EL correo '.$validatedData['user_email'].' ya esta siendo utilizado '], 200);
        }

        $usuarioSchool = User::where('email', $validatedData['school_email'])->first();
        if($usuarioSchool){
            return response()->json(['validacion_usuario' => 'EL correo '.$validatedData['school_email'].' ya esta siendo utilizado '], 200);
        }
 
            /*$allowedUserTypes = [1,2];
            if (!in_array($user->user_type_id, $allowedUserTypes)) {
                return response()->json([
                    'message' => '403 Forbidden',
                    'status_code' => 403
                ], 403);
            }*/

        $newUser = new User();
        $newUser->first_name = $validatedData['first_name'];
        $newUser->last_name = $validatedData['last_name'];
        $newUser->password = $validatedData['password'];
        $newUser->email = $validatedData['user_email'];
        $newUser->identification = $validatedData['identification'];
        $newUser->user_type_id = 4;
        if ($validatedData['user_phone'] !== 'null') {
            $newUser->phone = $validatedData['user_phone'];
        }
        $newUser->save();
        $newSchool = new School();
        $newSchool->name = $validatedData['school_name'];
        $newSchool->district = $validatedData['district'];
        $newSchool->address = $validatedData['address'];
        $newSchool->user_id = $newUser->id;

        if ($validatedData['first_arrival_time'] !== 'null') {
            $newSchool->first_arrival_time = $validatedData['first_arrival_time'];
            $newSchool->first_closing_time = $validatedData['first_closing_time'];
        }
        if ($validatedData['second_arrival_time'] !== 'null') {
            $newSchool->second_arrival_time = $validatedData['second_arrival_time'];
            $newSchool->second_closing_time = $validatedData['second_closing_time'];
        }


        if ($validatedData['working_time'] !== 'null') {
            $newSchool->working_time = $validatedData['working_time'];
        }
        if ($validatedData['school_email'] !== 'null') {
            $newSchool->email = $validatedData['school_email'];
        }
        if ($validatedData['school_phone'] !== 'null') {
            $newSchool->phone = $validatedData['school_phone'];
        }

        $newSchool->lat = $validatedData['lat'];
        $newSchool->lng = $validatedData['lng'];

        if (!$newSchool->save()) {
            throw new HttpException(500);
        } else {
            //Revisamos si existe el avatar para borrarlo
            $avatar = $request->input('avatar');
            if ($avatar != 'null' && $avatar !== null) {


            $image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $avatar));
            $imageName = uniqid($newSchool->id) . '.jpg';

            $storage = Storage::disk('avatars')->put($newSchool->id . 'photoProfileCollege.jpg', $image_data);
            $newSchool->avatar = $imageName;
        }
           /* if ($image) {
                $image = json_decode($image);
                $file_name = uniqid($newSchool->id) . $image->name;
                $file_name = str_replace(' ', '', $file_name);
                $file_data = $image->fileData;
                $file_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file_data));
                if ($file_data != "") {
                    // storing image in storage/app/public Folder
                    Storage::disk('avatars')->put($file_name, $file_data);
                    $newSchool->avatar = $file_name;
                    $newSchool->update();
                }
            }*/
        }
        return response()->json($newSchool);
    }

    public function college_edit(Request $request, $id)
    {
        $validatedData = $request->validate([
            'name' => 'required|max:255',
            'working_time' => 'nullable',
            'district' => 'required',
            'address' => 'required',
            'email' => 'nullable',
            'phone' => 'nullable',
            'lat' => 'required',
            'lng' => 'required',

            'first_arrival_time' => 'nullable',
            'first_closing_time' => 'nullable',
            'second_arrival_time' => 'nullable',
            'second_closing_time' => 'nullable',
        ]);




        $usuarioSchool = User::where('email', $validatedData['email'])->first();
        if($usuarioSchool){
            return response()->json(['validacion_usuario' => 'EL correo '.$validatedData['email'].' ya esta siendo utilizado '], 200);
        }

        $editedSchool = School::findOrFail($id);
        $editedSchool->name = $validatedData['name'];
        if ($validatedData['working_time'] === 'null') {
            $editedSchool->working_time = null;
        } else {
            $editedSchool->working_time = $validatedData['working_time'];
        }
        $editedSchool->district = $validatedData['district'];
        $editedSchool->address = $validatedData['address'];
        if ($validatedData['email'] === 'null') {
            $editedSchool->email = null;
        } else {
            $editedSchool->email = $validatedData['email'];
        }
        if ($validatedData['phone'] === 'null') {
            $editedSchool->phone = null;
        } else {
            $editedSchool->phone = $validatedData['phone'];
        }
        $editedSchool->lat = $validatedData['lat'];
        $editedSchool->lng = $validatedData['lng'];

        if ($validatedData['first_arrival_time'] !== 'null') {
            $editedSchool->first_arrival_time = $validatedData['first_arrival_time'];
            $editedSchool->first_closing_time = $validatedData['first_closing_time'];
        }
        else{
            $editedSchool->first_arrival_time = null;
            $editedSchool->first_closing_time = null;
        }
        if ($validatedData['second_arrival_time'] !== 'null') {
            $editedSchool->second_arrival_time = $validatedData['second_arrival_time'];
            $editedSchool->second_closing_time = $validatedData['second_closing_time'];
        }
        else{
            $editedSchool->second_arrival_time = null;
            $editedSchool->second_closing_time = null;
        }
        //$editedSchool->first_arrival_time = $validatedData['first_arrival_time'];
        //$editedSchool->first_closing_time = $validatedData['first_closing_time'];
        //$editedSchool->second_arrival_time = $validatedData['second_arrival_time'];
        //$editedSchool->second_closing_time = $validatedData['second_closing_time'];

        //Revisamos si existe el avatar para borrarlo
        $avatar = $request->input('avatar');
        if ($avatar != 'null' && $avatar !== null) {
            Storage::disk('avatars')->delete($editedSchool->avatar);

            $image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $avatar));
            $imageName = uniqid($editedSchool->id) . '.jpg';

            $storage = Storage::disk('avatars')->put($editedSchool->id . 'photoProfileCollege.jpg', $image_data);
            $editedSchool->avatar = $imageName;
        }

        if (!$editedSchool->update()) {
            throw new HttpException(500);
        }
        return response()->json($editedSchool);
    }


    public function getAvatarCollege($id)
    {

        $user = $this->auth->user();
        try {
            $image_data = Storage::disk('avatars')->get($id . 'photoProfileCollege.jpg');

            $base64_image = base64_encode($image_data);

            return response()->json(['image_data' => 'data:image/jpeg;base64,' . $base64_image], 200);
        } catch (\Exception $e) {

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



    public function getAvatar($id)
    {

        $user = $this->auth->user();
        try {
        $image_data = Storage::disk('avatars')->get($id . 'photoProfile.jpg');

        $base64_image = base64_encode($image_data);

        return response()->json(['image_data' => 'data:image/jpeg;base64,' . $base64_image], 200);
        }
        catch (\Exception $e) {

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




    public function users_index(Request $request, $id)
    {

        $user = $this->auth->user();
        $response = null;

        if ($user->user_type_id === 3) {
            if ($id == 3) {
                $response['data'] = Kid::orderBy('id', 'DESC')
                    ->get();
            } else if ($id == 2) {
                $response['data'] = User::where('user_type_id', $id)
                    ->orderBy('id', 'DESC')
                    ->get();
            } else {
                $response['data'] = User::with('driver', 'files')->where('user_type_id', $id)
                    ->orderBy('id', 'DESC')
                    ->get();
            }
        } else if ($user->user_type_id === 4) {
            $school = School::with('user')->where('user_id', $user->id)->first();
            if ($id == 3) {

                $response['data'] = Kid::where('school_id', $school->id)->orderBy('id', 'DESC')
                    ->get();
            } else if ($id == 2) {
                $response['data'] = User::where('user_type_id', $id)->whereHas('kids', function ($query) use ($school) {
                    $query->where('school_id', $school->id);
                })->where('user_type_id', $id)->get();
            } else {
                $response['data'] = User::with('driver', 'files')
                    ->whereHas('driver.schools', function ($query) use ($school) {
                        $query->where('id', $school->id);
                    })->where('user_type_id', $id)->get();
            }
        }

        return $response;
    }


    public function users_show(Request $request, $id)
    {

        $user = User::findOrFail($id);
        if ($user->user_type_id == 1) {
            $user->load('driver');
        }

        return $user;
    }

    public function users_edit(Request $request, $id)
    {
        $validatedData = $request->validate([
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'email' => 'required',
            'identification' => 'nullable',
            'nationality' => 'nullable',
            'phone' => 'nullable',
            'birth_date' => 'nullable',
            'gender' => 'nullable',
        ]);

        $editedUser = User::findOrFail($id);
        $editedUser->first_name = $validatedData['first_name'];
        $editedUser->last_name = $validatedData['last_name'];
        $editedUser->email = $validatedData['email'];
        if ($validatedData['identification'] === 'null') {
            $editedUser->identification = null;
        } else {
            $editedUser->identification = $validatedData['identification'];
        }
        if ($validatedData['nationality'] === 'null') {
            $editedUser->nationality = null;
        } else {
            $editedUser->nationality = $validatedData['nationality'];
        }
        if ($validatedData['phone'] === 'null') {
            $editedUser->phone = null;
        } else {
            $editedUser->phone = $validatedData['phone'];
        }
        if ($validatedData['birth_date'] === 'null') {
            $editedUser->birth_date = null;
        } else {
            $editedUser->birth_date = $validatedData['birth_date'];
        }
        if ($validatedData['gender'] === 'null') {
            $editedUser->gender = null;
        } else {
            $editedUser->gender = $validatedData['gender'];
        }

        //Revisamos si existe el avatar para borrarlo
        $avatar = $request->input('avatar');


        $avatar = $request->input('avatar');
        if ($avatar != 'null' && $avatar !== null) {
            Storage::disk('avatars')->delete($editedUser->avatar);

            $image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $avatar));
            $imageName = uniqid($editedUser->id) . '.jpg';

            $storage = Storage::disk('avatars')->put($editedUser->id . 'photoProfile.jpg', $image_data);
            $editedUser->avatar = $imageName;
        }

        /* if ($avatar != null) {
            Storage::disk('avatars')->delete($editedUser->avatar);
            $avatar = json_decode($avatar);
            $file_name = uniqid($editedUser->id).$avatar->name;
            $file_name = str_replace(' ', '', $file_name);
            $file_data = $avatar->fileData;
            $file_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file_data));
            if($file_data!=""){
                // storing image in storage/app/public Folder
                Storage::disk('avatars')->put($file_name, $file_data);
                $editedUser->avatar = $file_name;
            }
        }*/

        if (!$editedUser->update()) {
            throw new HttpException(500);
        }
        return response()->json($editedUser);
    }

    public function showKid(Request $request, $id)
    {
        $kid = Kid::with('users', 'drivers.user', 'school')->findOrFail($id);

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

    public function kids_edit(Request $request, $id)
    {
        $validatedData = $request->validate([
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'address' => 'required',
            'identification' => 'nullable',
            'nationality' => 'nullable',
            'birth_date' => 'nullable',
            'gender' => 'nullable',
            'medical_condition' => 'nullable',
            'grade' => 'nullable',
        ]);

        $editedKid = Kid::findOrFail($id);
        $editedKid->first_name = $validatedData['first_name'];
        $editedKid->last_name = $validatedData['last_name'];
        $editedKid->address = $validatedData['address'];
        if ($validatedData['identification'] === 'null') {
            $editedKid->identification = null;
        } else {
            $editedKid->identification = $validatedData['identification'];
        }
        if ($validatedData['nationality'] === 'null') {
            $editedKid->nationality = null;
        } else {
            $editedKid->nationality = $validatedData['nationality'];
        }
        if ($validatedData['birth_date'] === 'null') {
            $editedKid->birth_date = null;
        } else {
            $editedKid->birth_date = $validatedData['birth_date'];
        }
        if ($validatedData['gender'] === 'null') {
            $editedKid->gender = null;
        } else {
            $editedKid->gender = $validatedData['gender'];
        }
        if ($validatedData['medical_condition'] === 'null') {
            $editedKid->medical_condition = null;
        } else {
            $editedKid->medical_condition = $validatedData['medical_condition'];
        }
        if ($validatedData['grade'] === 'null') {
            $editedKid->grade = null;
        } else {
            $editedKid->grade = $validatedData['grade'];
        }

        if (!$editedKid->update()) {
            throw new HttpException(500);
        }
        return response()->json($editedKid);
    }


    public function driver_documents(Request $request, $user_id)
    {
        //
        if ($user_id == 0) {
            $user = $this->auth->user();

            $response['file_types'] = \App\Models\FileType::orderBy('order')->get();
            $response['user'] = User::with('driver')->findOrFail($user->id);
            $response['files'] = File::with('file_type')
                ->where('user_id', $user->id)
                ->orderBy('file_type_id')->get();
        } else {
            $response['file_types'] = \App\Models\FileType::orderBy('order')->get();
            $response['user'] = User::with('driver')->findOrFail($user_id);
            $response['files'] = File::with('file_type')
                ->where('user_id', $user_id)
                ->orderBy('file_type_id')->get();
        }

        return $response;
    }

    public function driver_documents_upload_phone(Request $request)
    {
        //

        $user = $this->auth->user();

        $this->validate($request, [
            'file' => 'mimes:jpeg,jpg,png,doc,docx,pdf'
        ]);


        $file = $request->file('file');

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

        //Revisamos si existe para borrarlo
        $fileDelete = File::where('user_id', $user->id)
            ->where('file_type_id', $file_type_id)->first();

        $extension = $file->getClientOriginalExtension();
        $fechaActual = Carbon::now();
        $fechaFormateada = $fechaActual->format('dmY');
        $numeroAleatorio = str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT);
        $nombreDoc = 'documento' . $numeroAleatorio . $fechaFormateada . $user->id . $file_type_id . '.' . $extension;


        if ($fileDelete != null && $request->input('name_doc')  != null) {
            $name_doc_before = $request->input('name_doc');
            Storage::disk('documents')->delete('driver/' . $name_doc_before);
            $fileDelete->delete();
        }



        //$file_name = uniqid($user->id.'-').'-'.$file->getClientOriginalName();




        $path = $file->storeAs(
            'driver',
            $nombreDoc,
            'documents'
        );

        $newFile = new File();
        $newFile->name = $nombreDoc; //$file->getClientOriginalName();
        $newFile->filename = $path;
        $newFile->file_type_id = $file_type_id;
        $newFile->user_id = $user->id;
        $newFile->status = 0;

        $newFile->save();

        Log::info("probando");

        $response = $newFile;

        return $response;
    }

    public function driver_documents_upload(Request $request)
    {
        //
        $user = $this->auth->user();

        $this->validate($request, [
            'file' => 'mimes:jpeg,jpg,png,doc,docx,pdf'
        ]);


        $file = $request->file('file');

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

        //Revisamos si existe para borrarlo
        $fileDelete = File::where('user_id', $user->id)
            ->where('file_type_id', $file_type_id)->first();

        $extension = $file->getClientOriginalExtension();
        $fechaActual = Carbon::now();
        $fechaFormateada = $fechaActual->format('dmY');
        $numeroAleatorio = str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT);
        $nombreDoc = 'documento' . $numeroAleatorio . $fechaFormateada . $user->id . $file_type_id . '.' . $extension;


        if ($fileDelete != null && $request->input('name_doc')  != null) {
            $name_doc_before = $request->input('name_doc');
            Storage::disk('documents')->delete('driver/' . $name_doc_before);
            $fileDelete->delete();
        }



        //$file_name = uniqid($user->id.'-').'-'.$file->getClientOriginalName();




        $path = $file->storeAs(
            'driver',
            $nombreDoc,
            'documents'
        );

        $newFile = new File();
        $newFile->name = $nombreDoc; //$file->getClientOriginalName();
        $newFile->filename = $path;
        $newFile->file_type_id = $file_type_id;
        $newFile->user_id = $user->id;
        $newFile->status = 0;

        $newFile->save();



        $response = $newFile;

        return $response;
    }



    public function getDocumentDownload(Request $request)
    {

        $user = $this->auth->user();
        try {
            $nombreDoc = $request->input('nombre_doc');
            $image_data = Storage::disk('documents')->get('driver/' . $nombreDoc);
            $base64_image = base64_encode($image_data);

            $file_extension = pathinfo($nombreDoc, PATHINFO_EXTENSION);
            $mimetype = $this->getMimeType($file_extension);

            return response()->json(['image_data' => 'data:'.$mimetype.';base64,' . $base64_image], 200);
        } catch (\Exception $e) {
            Log::info($e);
            return response()->json(['image_data' => ''], 200);
        }
    }

    public function routes_index(Request $request)
    {
        $user = $this->auth->user();
        if ($user->user_type_id === 3) {
            $routes = Route::with('driver.user')->get();
        } else if ($user->user_type_id === 4) {
            $school = School::with('user')->where('user_id', $user->id)->first();
            $routes = Route::with('driver.user')->whereHas('driver.schools', function ($query) use ($school) {
                $query->where('id', $school->id);
            })->get();
        }

        return $routes;
    }

    public function routes_show(Request $request, $route_id)
    {
        $route = Route::with('driver.user', 'routeStops.kid', 'routeStops.kid', 'routeStops.school')->findOrFail($route_id);
        return $route;
    }

    public function route_history(Request $request, $route_id)
    {
        $routeLogs = RouteLog::with('route')->where('route_id', $route_id)->get();
        return $routeLogs;
    }

    public function route_history_show(Request $request, $route_log_id)
    {
        $routeLog = RouteLog::with(array('routeLogKids' => function ($query) {
            $query->with('kid.school')->orderBy('created_at', 'ASC');
        }))->findOrFail($route_log_id);
        $routeLog->load('routeLogGps', 'route');
        return $routeLog;
    }

    public function pending_documents(Request $request)
    {
        $routes = File::with('user', 'file_type')->where('status', 0)->get();
        return $routes;
    }

    public function approved_documents(Request $request)
    {
        $routes = File::with('user', 'file_type')->where('approval_date', '!=', null)->orderBy('approval_date', 'DESC')->get();
        return $routes;
    }

    public function approve_document(Request $request, $file_id)
    {
        $file = File::findOrFail($file_id);
        $driver = Driver::with('user.files')->where('user_id', $file->user_id)->first();
       
        if($driver->validation == 'Autorizado/a'){
            return response()->json(['status_docs' => 'Autorizado/a'], 200);
        }

        $file->status = 1;
        $file->approval_date = Carbon::now();
        $file->update();

        $driverNew = Driver::with('user.files')->where('user_id', $file->user_id)->first();
        if (count($driverNew->user->files) >= 11) {
            $counter = 0;
            foreach ($driverNew->user->files as $userFile) {
                if ($userFile->status == 1) {
                    $counter += 1;
                }
            }
            if ($counter == 11) {
                $driverNew->validation = 'Autorizado/a';
                $driverNew->update();
            } else {
                $driverNew->validation = null;
                $driverNew->update();
            }
        }

        return $file;
    }

    public function reject_document(Request $request, $file_id)
    {
        $file = File::findOrFail($file_id);
        $driver = Driver::with('user.files')->where('user_id', $file->user_id)->first();

        if($driver->validation == 'Autorizado/a'){
            return response()->json(['status_docs' => 'Autorizado/a'], 200);
        }

        $file->status = 2;
        $file->approval_date = null;
        $file->update();
        $driverNew = Driver::with('user.files')->where('user_id', $file->user_id)->first();
       
        if (count($driverNew->user->files) >= 11) {
            $counter = 0;
            foreach ($driverNew->user->files as $userFile) {
                if ($userFile->status == 1) {
                    $counter += 1;
                }
            }
            if ($counter == 11) {
                $driverNew->validation = 'Autorizado/a';
                $driverNew->update();
            } else {
                $driverNew->validation = null;
                $driverNew->update();
            }
        }

        return $file;
    }

    public function admin_stats(Request $request)
    {
        $user = $this->auth->user();
        $response = null;
        if ($user->user_type_id === 3) {
            $response['kids'] = Kid::count();
            $response['pending_drivers'] = Driver::with('user')->whereNull('validation')->get();
            $response['approved_drivers'] = Driver::whereNotNull('validation')->count();
            $response['parents'] = User::where('user_type_id', 2)->count();
        } else if ($user->user_type_id === 4) {
            $school = School::with('user')->where('user_id', $user->id)->first();
            $response['drivers'] = Driver::with('user')
            ->whereHas('schools', function ($query) use ($school) {
                $query->where('id', $school->id);
            })
            ->get();



            
            // NECESITO OBTENER EL ROUTElOGIDA Y VUELTA POR CADA CONDUCTOR
            $response['drivers']->map(function ($driver) {
                $routeLogIda = RouteLog::select('route_log.id', 'route_log.route_id', 'route_log.start', 'route_log.end', 'route_log.created_at', 'route_log.updated_at', 'route_log.status_route')
                ->join('route', 'route_log.route_id', '=', 'route.id')
                ->join('driver', 'driver.id', '=', 'route.driver_id')
                ->where('driver.user_id', $driver->user_id)
                ->where('route.type', 1)
                ->orderByDesc('route_log.created_at')
                ->first();
        
            $routeLogRegreso = RouteLog::select('route_log.id', 'route_log.route_id', 'route_log.start', 'route_log.end', 'route_log.created_at', 'route_log.updated_at', 'route_log.status_route')
                ->join('route', 'route_log.route_id', '=', 'route.id')
                ->join('driver', 'driver.id', '=', 'route.driver_id')
                ->where('driver.user_id', $driver->user_id)
                ->where('route.type', 2)
                ->orderByDesc('route_log.created_at')
                ->first();

                $driver->routeLogIda = $routeLogIda;
                $driver->routeLogRegreso = $routeLogRegreso;

            });

      

            //$response['routeLogIda'] = $routeLogIda;
            //$response['routeLogRegreso'] = $routeLogRegreso;
        }
        return $response;
    }

    public function remove_college_logo(Request $request, $id)
    {
        $school = School::findOrFail($id);
        //Revisamos si existe para borrarlo
        $fileDelete = $school->avatar;

        if ($fileDelete != null) {
            Storage::disk('avatars')->delete($fileDelete);
            $school->avatar = null;
            $school->update();
        }
        return $school;
    }

    public function remove_user_avatar(Request $request, $id)
    {
        $user = User::findOrFail($id);
        //Revisamos si existe para borrarlo
        $fileDelete = $user->avatar;

        if ($fileDelete != null) {
            Storage::disk('avatars')->delete($fileDelete);
            $user->avatar = null;
            $user->update();
        }
        return $user;
    }



    public function getMimeType($type)
    {

        $file_mimetypes = [
            '3gp' => 'video/3gpp',
            'ai' => 'application/postscript',
            'aif' => 'audio/x-aiff',
            'apk' => 'application/vnd.android.package-archive',
            'avi' => 'video/x-msvideo',
            'bmp' => 'image/bmp',
            'csv' => 'text/csv',
            'doc' => 'application/msword',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'eps' => 'application/postscript',
            'gif' => 'image/gif',
            'html' => 'text/html',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'mp3' => 'audio/mpeg',
            'mp4' => 'video/mp4',
            'pdf' => 'application/pdf',
            'png' => 'image/png',
            'ppt' => 'application/vnd.ms-powerpoint',
            'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'rar' => 'application/x-rar-compressed',
            'rtf' => 'application/rtf',
            'svg' => 'image/svg+xml',
            'txt' => 'text/plain',
            'wav' => 'audio/wav',
            'webm' => 'video/webm',
            'xls' => 'application/vnd.ms-excel',
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'xml' => 'application/xml',
            'zip' => 'application/zip',
            '7z' => 'application/x-7z-compressed',
            'aac' => 'audio/aac',
            'apk' => 'application/vnd.android.package-archive',
            'bat' => 'application/x-msdownload',
            'bz' => 'application/x-bzip',
            'bz2' => 'application/x-bzip2',
            'class' => 'application/java-vm',
            'cpp' => 'text/x-c++src',
            'css' => 'text/css',
            'dll' => 'application/x-msdownload',
            'eot' => 'application/vnd.ms-fontobject',
            'exe' => 'application/x-msdownload',
            'flv' => 'video/x-flv',
            'gz' => 'application/gzip',
            'ico' => 'image/x-icon',
            'java' => 'text/x-java',
            'jsonld' => 'application/ld+json',
            'm4a' => 'audio/x-m4a',
            'midi' => 'audio/midi',
            'odp' => 'application/vnd.oasis.opendocument.presentation',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ogg' => 'audio/ogg',
            'ogv' => 'video/ogg',
            'otf' => 'font/otf',
            'php' => 'application/x-php',
            'pl' => 'application/x-perl',
            'py' => 'application/x-python',
            'rar' => 'application/x-rar-compressed',
            'rpm' => 'application/x-rpm',
            'sh' => 'application/x-sh',
            'sql' => 'application/sql',
            'tar' => 'application/x-tar',
            'ttf' => 'font/ttf',
            'wav' => 'audio/wav',
            'webp' => 'image/webp',
            'woff' => 'font/woff',
            'woff2' => 'font/woff2',
            'xml' => 'application/xml',
            'yaml' => 'text/yaml',
            'zip' => 'application/zip',
        ];

        $file_mimetype = $file_mimetypes[$type];
        return $file_mimetype;
    }
}
