<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Boat;
use App\Schedule;
use App\User;
use App\Customer;
use App\Status;
use App\CreditUser;
use App\CreditRegister;
use App\Reservations;
use App\GlobalPreference;
use App\Festive;
use App\Bookings24h;
use App\Block;
use App\Inspection;
use App\Http\Requests\ReservationsRequest;
use App\MailinCustome;

use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Alert;
use Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Input;
use DateTime;


require_once  'esendex/autoload.php';

class ReservationsController extends Controller
{
	public function __construct() {
		$this->middleware('auth');
		date_default_timezone_set('Europe/Madrid');
	}

	public function getScheduleValue($schedule_id){
		$schedule = Schedule::find($schedule_id);
		if(isset($schedule) && !empty($schedule)){
			return $schedule;
		}else{
			return false;
		}
	}

	public function index()
	{
		if(Auth::user()->role->role_permission('view_reservation')){
			$array_of_grouped_def = [];
			if(Auth::user()->role->role_permission('view_reservation')->level == 'all'){

				// $reservations = Reservations::where('status_id', '!=' , 3)->orderBy('date_start', 'desc')->paginate(30);
				$reservations = Reservations::orderBy('date_start', 'desc')->paginate(30);
				$status = Status::get();
				$estado = ["" => ""] + Status::lists('name', 'id')->toArray();
				$turno = ["" => ""] + Schedule::groupBy('name')->lists('name', 'id')->toArray();
				$users = ["" => ""] + User::select(DB::raw('CONCAT(first_name, " ",last_name) AS fullname, id'))
						->lists('fullname', 'id')->toArray();
				$boats = ["" => ""] + Boat::lists('name', 'id')->toArray();
				$barcos = $boats;
			}else{
				$array_of_grouped = [];
				$reservations = Reservations::where('user_id', Auth::user()->id)->orderBy('date_start', 'desc')->paginate(30);

				$i = 0;

				$array_of_reservations = [];

				foreach ($reservations as $key => $value) {
					array_push($array_of_reservations, $value);
				}

				foreach ($reservations as $key => $value) {
					$schedule_object = $this->getScheduleValue($value->schedule_id);

					if($schedule_object != false){

						//SET TIME START OF RESERVATION
						$date_time_first_start = Carbon::createFromFormat('d/m/Y H:i:s', $value->date_start.' '.$schedule_object->start_hour);
						//SET TIME END OF RESARVATION
						$date_time_first_end = Carbon::createFromFormat('d/m/Y H:i:s', $value->date_start.' '.$schedule_object->end_hour);
						//TO ADD ANOTHER DAY IF SCHEDULE IS NIGHT TIME, BECAUSE OF THE $schedule_object->end_hour;
						if($schedule_object->id == 2 || $schedule_object->id == 4){
							$date_time_first_end->addHours(24);
						}

						foreach ($array_of_reservations as $key_two => $value_two) {
							$schedule_object_two = $this->getScheduleValue($value_two->schedule_id);

							//SET TIME START OF RESERVATION TO COMPARE
							$date_time_two_start = Carbon::createFromFormat('d/m/Y H:i:s', $value_two->date_start.' '.$schedule_object_two->start_hour);
							//SET TIME END OF RESERVATION TO COMPARE
							$date_time_two_end = Carbon::createFromFormat('d/m/Y H:i:s', $value_two->date_start.' '.$schedule_object_two->end_hour);
							if($schedule_object_two->id == 2 || $schedule_object_two->id == 4){
								$date_time_two_end->addHours(24);
							}

							if(
								$value_two->id != $value->id
								&& $date_time_first_end->format('d/m/Y H:i:s') == $date_time_two_start->format('d/m/Y H:i:s')
								&& $value->boat_id == $value_two->boat_id
								&& $value->user_id == $value_two->user_id
								&& $value->status_id == $value_two->status_id
							){

								$object = [
									'date_start' => $date_time_first_start->format('d/m/Y H:i:s'),
									'date_start_end' => $date_time_first_end->format('d/m/Y H:i:s'),
									'date_end_start' => $date_time_two_start->format('d/m/Y H:i:s'),
									'date_end_end' => $date_time_two_end->format('d/m/Y H:i:s'),
									'ids' => [],
									'id' => $value->id,
									'boat_id' => $value->boat_id,
									'boat' => $value->boat,
									'schedule' => $value->schedule,
									'schedule_two' => $value_two->schedule,
									'user_id' => $value->user_id,
									'customer_id' => $value->customer_id,
									'status_id' => $value->status_id,
									'status' => $value->status,
									'reference_numbers' => [],
									'delete' => false,
								];

								array_push($object['ids'], $value->id);
								array_push($object['ids'], $value_two->id);
								array_push($object['reference_numbers'], $value->reference_number);
								array_push($object['reference_numbers'], $value_two->reference_number);

								array_push($array_of_grouped, $object);
								// array_splice($array_of_reservations, $key_two, 1);

							}
						}
					}
				}

				foreach ($array_of_grouped as $key => $value) {
					foreach ($array_of_grouped as $key_two => $value_two) {
						if(
							$value['date_end_start'] == $value_two['date_start']
							&& $value['user_id'] == $value_two['user_id']
							&& $value['boat_id'] == $value_two['boat_id']
						){
							$array_of_grouped[$key]['date_end_end'] = $value_two['date_end_end'];

							foreach ($value_two['ids'] as $key_three => $value_three) {
								array_push($array_of_grouped[$key]['ids'], $value_three);
							}

							foreach ($value_two['reference_numbers'] as $key_three => $value_three) {
								array_push($array_of_grouped[$key]['reference_numbers'], $value_three);
							}

							$array_of_grouped[$key]['ids'] = array_unique($array_of_grouped[$key]['ids']);
							$array_of_grouped[$key]['reference_numbers'] = array_unique($array_of_grouped[$key]['reference_numbers']);
							$array_of_grouped[$key_two]['delete'] = true;
						}
						foreach ($array_of_grouped as $key_three => $value_three) {
							if(
								$value_two['date_end_start'] == $value_three['date_start']
								&& $value_two['user_id'] == $value_three['user_id']
								&& $value_two['boat_id'] == $value_three['boat_id']
							){
								$array_of_grouped[$key]['date_end_end'] = $value_three['date_end_end'];

								foreach ($value_three['ids'] as $key_alt => $value_alt) {
									array_push($array_of_grouped[$key_two]['ids'], $value_alt);
								}

								foreach ($value_three['reference_numbers'] as $key_alt => $value_alt) {
									array_push($array_of_grouped[$key_two]['reference_numbers'], $value_alt);
								}

								$array_of_grouped[$key_two]['ids'] = array_unique($array_of_grouped[$key_two]['ids']);
								sort($array_of_grouped[$key_two]['ids']);
								$array_of_grouped[$key_two]['reference_numbers'] = array_unique($array_of_grouped[$key_two]['reference_numbers']);
								$array_of_grouped[$key_three]['delete'] = true;
							}

						}
					}
				}
				$array_of_grouped_def = [];

				foreach ($array_of_grouped as $key => $value) {



					if(!$value['delete']){

						$reservation_start = Reservations::find($value['ids'][0]);
						$reservation_end = Reservations::find(end($value['ids']));


						$schedule_object_one = $this->getScheduleValue($reservation_start->schedule_id);
						$schedule_object_two = $this->getScheduleValue($reservation_end->schedule_id);

						// $value['date_start'] = $reservation_start->date_start;
						$value['date_start'] = Carbon::createFromFormat('d/m/Y H:i:s', $reservation_start->date_start.' '.$schedule_object_one->end_hour)->format('d/m/Y H:i:s');

						$date_time_two_end = Carbon::createFromFormat('d/m/Y H:i:s', $reservation_end->date_start.' '.$schedule_object_two->end_hour);

						if($schedule_object_two->id == 2 || $schedule_object_two->id == 4){
							$date_time_two_end->addHours(24);
						}

						$value['date_end_end'] = $date_time_two_end->format('d/m/Y H:i:s');

						array_push($array_of_grouped_def, $value);
					}
				}



			}


			return view('reservations.index', compact('reservations','status','turno','estado','users','boats','barcos', 'array_of_grouped_def'));
		}else{
			abort(403);
		}
	}

	public function search(Request $request)
	{
		$array_of_grouped_def = [];
		$estado = ["" => ""] + Status::lists('name', 'id')->toArray();
		$status = Status::get();
		$barcos = ["" => ""] + Boat::lists('name', 'id')->toArray();
		$turno = ["" => ""] + Schedule::groupBy('name')->lists('name', 'id')->toArray();

		if(Auth::user()->role->role_permission('view_reservation'))
		{

			$reservations = Reservations::where('first_name', 'LIKE', '%'. $request->get('term') .'%')
				->orWhere('last_name', 'LIKE', '%'. $request->get('term') .'%')
				->orWhere('email', 'LIKE', '%'. $request->get('term') .'%')
				->orderBy('date_start', 'desc')
				->paginate(30);

			if(Auth::user()->role->role_permission('view_reservation')->level == 'all')
			{

				$reservations = Reservations::where('first_name', 'LIKE', '%'. $request->get('term') .'%')
					->orWhere('last_name', 'LIKE', '%'. $request->get('term') .'%')
					->orWhere('email', 'LIKE', '%'. $request->get('term') .'%')
					->orderBy('date_start', 'desc')
					->paginate(30);
			}else{
				$reservations = Reservations::select('reservations.*', 'boat.name as boat_name', 'schedules.name as schedule_name')
					->where('user_id', Auth::user()->id)
					->join('boat', 'boat.id', '=', 'reservations.boat_id')
					->join('schedules', 'schedules.id', '=', 'reservations.schedule_id')
					->where('first_name', 'LIKE', '%'. $request->get('term') .'%')
					->orWhere('boat.name', 'LIKE', '%'. $request->get('term') .'%')
					->orWhereDate('date_start', '=', $request->get('term'))
					->orWhere('schedules.name', 'LIKE', '%'.$request->get('term').'%')
					// ->orWhereYear('date_start', '=', $request->get('term'))
					// ->orWhereMonth('date_start', '=', $request->get('term'))
					// ->orWhereDay('date_start', '=', $request->get('term'))
					// ->orWhere('email', 'LIKE', '%'. $request->get('term') .'%')
					->orderBy('date_start', 'desc')
					->paginate(30);

			}
			return view('reservations.index', compact('reservations', 'estado', 'status', 'barcos', 'turno', 'array_of_grouped_def'));

		}else{
			abort(403);
		}
	}

	public function create()
	{

		if(Auth::user()->role->role_permission('create_reservation'))
		{
			if(Auth::user()->role->role_permission('create_reservation')->level == 'all')
			{
				$reservations = Reservations::paginate(30);
				$status = Status::get();
				$users = ["" => ""] + User::select(DB::raw('CONCAT(first_name, " ",last_name) AS fullname, id'))
						->lists('fullname', 'id')->toArray();
			}else{
				$reservations = Reservations::where('user_id', Auth::user()->id)->paginate(30);
				$users = ["" => ""] + User::where('id', Auth::user()->id)->select(DB::raw('CONCAT(first_name, " ",last_name) AS fullname, id'))
						->lists('fullname', 'id')->toArray();
			}
			$reference_number = strtoupper(uniqid('RS'));

			$customer_id = Auth::user()->customer_id;
			$boat = ["" => ""] + Customer::find($customer_id)->boats->lists('name', 'id')->toArray();
			$motor = null;
			$vela = null;

			$tipo= Customer::find($customer_id)->boats;
			foreach($tipo as $type){
				if($type->boattype_id == 2){
					$vela = 2;
				}
				elseif($type->boattype_id == 1){
					$motor = 1;
				}

			}

			$schedule = ["" => ""] + Schedule::where('boattype_id',$vela)->orWhere('boattype_id',$motor)->lists('name', 'id')->toArray();
			return view('reservations.create', compact('reference_number','boat','users','schedule','status'));

		}else{
			abort(403);
		}
	}

	public function storecalendar (Request $request)
	{
		dd($request->all());
	}

	public function store_old(Request $request) #HERE CREATE RESERVATION OLD
	{

		if(Auth::user()->role->role_permission('create_reservation')){
			$motor = false;
			$vela = false;
			$maxbookmotor = null;
			$maxbookvela = null;
			$fechaReserva = null;

			if(isset($request->date_start_)){
				$date_start = Carbon::createFromFormat('d/m/Y',$request->date_start_)->format('Y-m-d');
				if ($request->schedule_id == 2 ){
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start_ . ' 15:00');
				}elseif ($request->schedule_id == 4){
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start_ . ' 18:00');
				}else {
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start_ . ' 09:30');
				}
			}
			else {
				$date_start = Carbon::createFromFormat('d/m/Y',$request->date_start)->format('Y-m-d');
				if ($request->schedule_id == 2 ){
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start . ' 15:00');
				}elseif ($request->schedule_id == 4){
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start . ' 18:00');
				}else {
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start . ' 09:30');
				}
			}


			$diff = $fechaReserva->diffInSeconds(Carbon::now());
			$is24h = ($diff < 86400) ? true : false;
			return $diff;
			$request->merge(['date_start' => $date_start]);

			$users = Customer::with('boats')->where('id',$request->customer_id)->first();
			$user = User::where('id', $request->user_id)->first();
			$boat =  Boat::where('id',$request->boat_id)->first();
			$global= GlobalPreference::first();

			if($boat){
				if($boat->boattype_id = 2){
					$vela = true;
				}
				else{
					$motor = true;
				}
			}

			$request->merge(['first_name' => $user->first_name]);
			$request->merge(['last_name' => $user->last_name]);
			$request->merge(['email' => $user->email]);
			$request->merge(['telephone' => $user->telephone]);
			$request->merge(['customer_id' => $request->customer_id]);
			$request->merge(['boat_id' => $request->boat_id]);

			//manipulación de fechas
			$dateMonthStart = new Carbon($request->date_start);

			$startMonth = $dateMonthStart->startOfMonth()->startOfDay()->format('Y-m-d');

			//Si la reserva es realizada por el socio es una PRE-Reserva
			//if(Auth::user()->role->role_permission('create_reservation')->level <> 'all'){
			//	$request->merge(['status_id' => 2]);
			//}

			// Comprobamos antes de guardar que no existe una reserva para el mismo barco, misma franja horaria
			$sqlCheck = 'SELECT * FROM reservations WHERE date_start = STR_TO_DATE("'.$date_start.'", "%Y-%m-%d") AND schedule_id = '. $request->schedule_id . ' AND status_id = 1 AND boat_id = '. $request->boat_id;
			$resultados = count(DB::select($sqlCheck));

			// Comprobar que no se haya hecho una reserva justo antes de la nuestra.
			$sqlReservaPrevia = 'SELECT * FROM reservations WHERE date_start = STR_TO_DATE("'.$date_start.'", "%Y-%m-%d") AND schedule_id = '. $request->schedule_id . ' AND status_id != 3 AND boat_id = '. $request->boat_id;
			$existeReservaPrevia = count(DB::select($sqlReservaPrevia));

			$sql24h = 'SELECT * FROM reservations WHERE date_start = STR_TO_DATE("'.$date_start.'", "%Y-%m-%d") AND boat_id = '.$request->boat_id .' AND status_id = 3 AND customer_id = ' . $request->customer_id;
			$control24h = count(DB::select($sql24h));

			if ($resultados < 1 && $existeReservaPrevia < 1 ){

				// Inserto la reserva
				$reservation = Reservations::create($request->all());

				$reservaReg = Reservations::where('id', $reservation->id)->first();
				$reservaReg->customer_id = $request->customer_id;
				$reservaReg->date_end = $date_time_end;

				if ($existeReservaPrevia > 0){
					$reservaReg->status_id = 4;
				}

				$reservaReg->save();

				// Almacenamiento de creditos por la reserva
				if($request->status_id == 1){

					// falta verificar si en el rango de fechas es fin de semana
					//dd($date_start->dayOfWeek,Carbon::SATURDAY);
					//dd($date_start->dayOfWeek,Carbon::SUNDAY);

					// se usa el modelo CreditController para establecer la cantidad de puntos a usar.

					$creditUserInput = array(
						'quantity' => '1',
						'date' => $request->date_start,
						'user_id' => $request->user_id,
						'credit_id' => '1',
						'reservation_id' => $reservation->id,
					);

					// Inserto el credito del usuario
					//$credituser = CreditUser::create($creditUserInput);
				}

				// Si es para la misma fecha o la reserva está dentro de las próximas 24h, insertamos en la tabla de 24h
				if ( ($request->date_start == date('Y-m-d') || $is24h) && $control24h < 1 ) {
					DB::table('bookings24h')->insert(['reservation_id' => $reservation->id]);
				}

				return redirect('reservations')->withSuccess($reservation->name.' has been saved.');

			}else {
				return redirect('reservations')->withErrors('La embarcación ya no está disponible');
			}

		}else{
			abort(403);
		}
	}

	public function store(Request $request) #HERE CREATE RESERVATION
	{
		if(Auth::user()->role->role_permission('create_reservation')){


			$motor = false;
			$vela = false;
			$maxbookmotor = null;
			$maxbookvela = null;
			$fechaReserva = null;
			$customer = Customer::find(Auth::user()->customer_id);

			$schedule = $this->getScheduleValue($request->schedule_id);






			if(isset($request->date_start_)){
				$date_start = Carbon::createFromFormat('d/m/Y',$request->date_start_)->format('Y-m-d');
				if ($request->schedule_id == 2 ){
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start_ . ' 15:00');
					$date_time_end = Carbon::createFromFormat('d/m/Y H:i', $request->date_start_.' 09:30');
				}elseif ($request->schedule_id == 4){
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start_ . ' 18:00');
					$date_time_end = Carbon::createFromFormat('d/m/Y H:i', $request->date_start_.' 09:30');
				}else {
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start_ . ' 09:30');
					$date_time_end = Carbon::createFromFormat('d/m/Y H:i', $request->date_start_.' 15:00');
				}
			} else {
				$date_start = Carbon::createFromFormat('d/m/Y',$request->date_start)->format('Y-m-d');
				if ($request->schedule_id == 2 ){
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start . ' 15:00');
					$date_time_end = Carbon::createFromFormat('d/m/Y H:i', $request->date_start.' 09:30');
				}elseif ($request->schedule_id == 4){
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start . ' 18:00');
					$date_time_end = Carbon::createFromFormat('d/m/Y H:i', $request->date_start.' 09:30');
				}elseif ($request->schedule_id == 1) {
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start . ' 09:30');
					$date_time_end = Carbon::createFromFormat('d/m/Y H:i', $request->date_start.' 18:00');
				} else {
					$fechaReserva = Carbon::createFromFormat('d/m/Y H:i',$request->date_start . ' 09:30');
					$date_time_end = Carbon::createFromFormat('d/m/Y H:i', $request->date_start.' 15:00');
				}
			}
			if($request->schedule_id%2 == 0){
				$date_time_end->addDay();
			}


			$diff = $fechaReserva->diffInSeconds(Carbon::now());
			$is24h = ($diff < 86400) ? true : false;
			$request->merge(['date_start' => $date_start]);

			$users = Customer::with('boats')->where('id',$request->customer_id)->first();
			$user = User::where('id', $request->user_id)->first();
			$boat =  Boat::where('id',$request->boat_id)->first();
			$global= GlobalPreference::first();

			if($boat){
				if($boat->boattype_id = 2){
					$vela = true;
				}
				else{
					$motor = true;
				}
			}

			$request->merge(['first_name' => $user->first_name]);
			$request->merge(['last_name' => $user->last_name]);
			$request->merge(['email' => $user->email]);
			$request->merge(['telephone' => $user->telephone]);
			$request->merge(['customer_id' => $user->customer_id]);
			$request->merge(['boat_id' => $request->boat_id]);

			//manipulación de fechas
			$dateMonthStart = new Carbon($request->date_start);

			$startMonth = $dateMonthStart->startOfMonth()->startOfDay()->format('Y-m-d');

			//Si la reserva es realizada por el socio es una PRE-Reserva
			//if(Auth::user()->role->role_permission('create_reservation')->level <> 'all'){
			//	$request->merge(['status_id' => 2]);
			//}

			//CHECK HAS CREDITS FOR THAT DAY
			$hasCredits = $this->checkCredits($fechaReserva, $request->user_id, $request->customer_id, $request->boat_id, $schedule, $date_time_end);
			if(!$hasCredits['pass']&&!$is24h){
				$message = $hasCredits['message'];
				return redirect('reservations')->withErrors($message);
			}

			// Comprobamos antes de guardar que no existe una reserva para el mismo barco, misma franja horaria
			// $sqlCheck = 'SELECT * FROM reservations WHERE date_start = STR_TO_DATE("'.$date_start.'", "%Y-%m-%d") AND schedule_id = '. $request->schedule_id . ' AND status_id = 1 AND boat_id = '. $request->boat_id;
			$sqlCheck = Reservations::select('*')
				->where('schedule_id', '=', $request->schedule_id)
				->whereIn('status_id', [1,2])
				->where('boat_id', '=', $request->boat_id)
				->whereDate('date_start', '=', $fechaReserva)
				->get();
			$resultados = count($sqlCheck);

			//CHECK TO SET IN WAITING LIST

			$sqlCheckUserWatingList = Reservations::select('*')
				->where('schedule_id', '=', $request->schedule_id)
				->where('status_id', '!=', 3)
				->where('boat_id', '=', $request->boat_id)
				->whereDate('date_start', '=', $fechaReserva)
				->where('user_id', '=', $user->id)
				->get();

			$resultadosWaitingList = count($sqlCheckUserWatingList);


			// Comprobar que no se haya hecho una reserva justo antes de la nuestra.
			// $sqlReservaPrevia = 'SELECT * FROM reservations WHERE date_start = STR_TO_DATE("'.$date_start.'", "%Y-%m-%d") AND schedule_id = '. $request->schedule_id . ' AND status_id != 3 AND boat_id = '. $request->boat_id;
			// $existeReservaPrevia = count(DB::select($sqlReservaPrevia));
			$sqlReservaPrevia = Reservations::select('*')
				->where('schedule_id', '=', $request->schedule_id)
				->where('status_id', '!=', 3)
				->where('boat_id', '=', $request->boat_id)
				->whereDate('date_start', '=', $fechaReserva)
				->get();
			$existeReservaPrevia = count($sqlReservaPrevia);

			// $sql24h = 'SELECT * FROM reservations WHERE date_start = STR_TO_DATE("'.$date_start.'", "%Y-%m-%d") AND boat_id = '.$request->boat_id .' AND status_id = 3 AND customer_id = ' . $request->customer_id;
			// $control24h = count(DB::select($sql24h));

			$sql24h = Reservations::select('*')
				->where('status_id', '=', 2)
				->where('boat_id', '=', $request->boat_id)
				->where('customer_id', '=', $request->customer_id)
				->whereDate('date_start', '=', $fechaReserva)
				->get();
			
			$control24h = count($sql24h);



			if($resultadosWaitingList < 1  && $resultados >= 1){

				$reservation = Reservations::create($request->all());

				$reservation->customer_id = $user->customer_id;

				$reservation->status_id = 4;

				$reservation->save();

				// var_dump(json_decode($reservation));
				// exit();

				return redirect('reservations')->withSuccess('Se ha anotado en lista de espera.');
			}


			if ($resultados < 1 && $existeReservaPrevia < 1 ){
			    $request->date_start = $fechaReserva;
			    $request->date_end = $date_time_end;
				// Inserto la reserva
				$reservation = Reservations::create($request->all());

				$reservaReg = Reservations::where('id', $reservation->id)->first();
				$reservaReg->customer_id = $request->customer_id;

				if ($existeReservaPrevia > 0){
					$reservaReg->status_id = 4;
				}
				
				$reservaReg->date_end = $date_time_end;

				$reservaReg->save();
				//pedro@komunica.es
				//+34607248592
				// Almacenamiento de creditos por la reserva
				if($request->status_id == 1){

					// falta verificar si en el rango de fechas es fin de semana
					//dd($date_start->dayOfWeek,Carbon::SATURDAY);
					//dd($date_start->dayOfWeek,Carbon::SUNDAY);

					// se usa el modelo CreditController para establecer la cantidad de puntos a usar.

					$creditUserInput = array(
						'quantity' => '1',
						'date' => $request->date_start,
						'user_id' => $request->user_id,
						'credit_id' => '1',
						'reservation_id' => $reservation->id,
					);

					// Inserto el credito del usuario
					//$credituser = CreditUser::create($creditUserInput);
				}
				// Si es para la misma fecha o la reserva está dentro de las próximas 24h, insertamos en la tabla de 24h
				if ( ($request->date_start == date('Y-m-d') || $is24h) && $control24h < 1 ) {
				    Bookings24h::insert([['reservation_id' => $reservation->id]]);
				}
				// exit();
				return redirect('reservations')->withSuccess($reservation->name.' has been saved successfully.');

			}else {
				return redirect('reservations')->withErrors('La embarcación ya no está disponible');
			}

		}else{
			abort(403);
		}
	}

	public function show(Reservations $reservation)
	{
		if(Auth::user()->role->role_permission('view_reservation')){
			return view('reservations.show', compact('reservation'));
		}else{
			abort(403);
		}
	}

	public function edit(Reservations $reservation, Request $request)
	{

		if(Auth::user()->role->role_permission('edit_reservation')){
			if(Auth::user()->role->role_permission('edit_reservation')->level == 'all'){
				$users =  User::select(DB::raw('CONCAT(first_name, " ",last_name) AS fullname, id'))
					->lists('fullname', 'id')->toArray();
				$status = Status::get();
			}
			else{
				$users = User::where('id', Auth::user()->id)->select(DB::raw('CONCAT(first_name, " ",last_name) AS fullname, id'))
					->lists('fullname', 'id')->toArray();

			}

			$customer_id = Auth::user()->customer_id;
			$boat = Customer::find($customer_id)->boats()->lists('name', 'id')->toArray();

			$motor = null;
			$vela = null;
			$tipo= Customer::find($customer_id)->boats();
			foreach($tipo as $type){
				if($type->boattype_id == 2){
					$vela = 2;
				}
				elseif($type->boattype_id == 1){
					$motor = 1;
				}
			}
			// $reservation->date_start = $date_start_parse;

			$schedule = Schedule::where('boattype_id',$vela)->orWhere('boattype_id',$motor)->lists('name', 'id')->toArray();

			return view('reservations.edit', compact('reservation','boat','schedule','users','status'));
		}else{
			abort(403);
		}
	}

	public function update(Request $request, Reservations $reservation) #HERE UPDATE RESERVATION
	{

		if(Auth::user()->role->role_permission('edit_reservation')){
			if(Auth::user()->role->role_permission('edit_reservation')->level == 'all'){
				$date_start = Carbon::createFromFormat('d/m/Y',$request->date_start)->format('Y-m-d'); // DATE WAS NOT WELL PARSE
				$request->merge(['date_start' => $date_start]);

				$reservation->update($request->all());
				return redirect('reservations')->withSuccess($reservation->name.' has been updated.');
			}else{
				$date_start = Carbon::createFromFormat('d/m/Y',$request->date_start)->format('Y-m-d'); // DATE WAS NOT WELL PARSE
				$request->merge(['date_start' => $date_start]);
				$request->merge(['status_id' => 2]);
				$reservation->update($request->all());
				return redirect('reservations')->withSuccess($reservation->name.' has been updated.');

			}
		}
		else{
			abort(403);
		}
	}

	public function destroy(Reservations $reservation)
	{

		if(Auth::user()->role->role_permission('delete_reservation')){
			$reservation->delete();
			return redirect('reservations')->withSuccess($reservation->name.' has been deleted.');
		}else{
			abort(403);
		}
	}

	public function boat(Request $request)
	{
		$user = User::where('id', $request->user)->first();
		//$boat =  $user->boats->toArray();
		$customer = Customer::find($user->customer_id);
		$boat = $customer->boats->toArray();

		$boat = json_encode($boat);
		return $boat;
	}

	public function timer(Request $request)
	{

		//$tipo=  User::where('id', $request->user)->with(array('boats' => function($q)use($request)
		//{$q->where('id', $request->boat);
		//}))->get();

		$user = User::where('id', $request->user)->first();
		$customer = Customer::find($user->customer_id);
		$boats = $customer->boats->toArray();

		$motor = null;
		$vela = null;

		foreach ($boats as $boat){
			if($boat['boattype_id'] == 2){
				$vela = 2;
			}
			elseif($boat['boattype_id'] == 1){
				$motor = 1;
			}
		}

		/*
		foreach($tipo as $type){
			foreach($type->boats as $boats){

				if($boats->boattype_id == 2){
					$vela = 2;

				}
				elseif($boats->boattype_id == 1){
					$motor = 1;
				}
			}}
		*/
		$schedule = Schedule::where('boattype_id',$vela)->orWhere('boattype_id',$motor)->get();
		$schedule->toArray();

		$schedule = json_encode($schedule);
		return $schedule;
	}

	public function checkDateIsNotPass($date){
		$pass = true;
		$message = 'Correcto, La Fecha aun no ha pasado.';

		$today = Carbon::now();

		$count = $date->diffInHours($today, false);

		if($count >= 0){
			$message = 'Error, la fecha a reservar ya ha pasado.';
			$pass = false;
		}
		return ['pass' => $pass, 'message' => $message, 'today' => $today, 'count' => $count];
	}

	public function checkCredits($date, $user_id, $customer_id, $boat_id, $schedule, $date_time_end){
		$pass = true;
		$message = 'Correcto, tiene creditos.';

		$credits = CreditRegister::where('date_year', '=', $date->format('Y'))
			// ->where('user_id', '=', $user_id)
			->where('date_month', '=', $date->format('m'))
			->where('customer_id', '=', $customer_id)
			->where('boat_id', '=', $boat_id)
			->first();

		$array_of_holidays = [];
		$holidays = Festive::whereMonth('date', '=', $date->format('m'))
			->whereYear('date', '=', $date->format('Y'))
			->get();

		foreach ($holidays as $key => $value) {
			$formated_date = Carbon::createFromFormat('m/d/Y', $value->date)->format('d/m/Y');
			array_push($array_of_holidays, $formated_date);
		}

		$reservations_done_in_24_hours = Bookings24h::all();

		$array_of_id_reservation_24_hours = [];

		foreach ($reservations_done_in_24_hours as $key => $value) {
			array_push($array_of_id_reservation_24_hours, $value->reservation_id);
		}

		$reservations = [];


		$today = Carbon::now();
		$moreThan24Hours = $today->diffInHours($date, false);

		if(!isset($credits) && empty($credits)  && ($moreThan24Hours > 24 || $moreThan24Hours < 0)){
			$message = 'Error, No tiene creditos asignados.';
			$pass = false;
			return ['pass' => $pass, 'message' => $message, 'credits' => $credits];
		}

		$dayOfWeek = $date->format('w');

		$hasCredits = true;
		switch ($dayOfWeek) {
			case '1':
			case '2':
			case '3':
			case '4':

				if($schedule->id == 2 || $schedule->id == 4){
					if(!in_array($date->format('d/m/Y') ,$array_of_holidays)){
						$array_of_reservations = [];
						$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
							->whereMonth('date_start', '=', $date->format('m'))
							->where('customer_id', '=', $customer_id)
							->where('boat_id', '=', $boat_id)
							->whereIn('schedule_id', [2,4])
							->whereNotIn('id', $array_of_id_reservation_24_hours)
							->where('status_id', '!=', 3)
							->get();
						foreach ($reservations as $key => $value) {
							$is_in_array = in_array($value->date_start ,$array_of_holidays);
							$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
							if(
								($day_of_week == 1
									|| $day_of_week == 2
									|| $day_of_week == 3
									|| $day_of_week == 4
									|| $day_of_week == 0)
								&& !$is_in_array
							){
								array_push($array_of_reservations, $value);
							}
						}

						if(count($array_of_reservations) >= $credits->afternoon || $credits->afternoon <= 0){
							$hasCredits = false;
							$message = 'Error, no tiene creditos para los dias laborables en la tarde ';
						}

					}else{
						$array_of_reservations = [];
						$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
							->whereMonth('date_start', '=', $date->format('m'))
							->where('customer_id', '=', $customer_id)
							->where('boat_id', '=', $boat_id)
							->whereIn('schedule_id', [2,4])
							->whereNotIn('id', $array_of_id_reservation_24_hours)
							->where('status_id', '!=', 3)
							->get();
						foreach ($reservations as $key => $value) {
							$is_in_array = in_array($value->date_start ,$array_of_holidays);
							$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
							if(
								$day_of_week == 5
								|| $day_of_week == 6
								|| $is_in_array
							){
								array_push($array_of_reservations, $value);
							}
						}

						if(count($array_of_reservations) >= $credits->festivo_afternoon || $credits->festivo_afternoon <= 0){
							$hasCredits = false;
							$message = 'Error, no tiene creditos para fines de semana o festivos en la tarde ';
						}
					}
				}else{
					if(!in_array($date->format('d/m/Y') ,$array_of_holidays)){
						$array_of_reservations = [];
						$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
							->whereMonth('date_start', '=', $date->format('m'))
							->where('customer_id', '=', $customer_id)
							->where('boat_id', '=', $boat_id)
							->whereIn('schedule_id', [1,3])
							->whereNotIn('id', $array_of_id_reservation_24_hours)
							->where('status_id', '!=', 3)
							->get();

						foreach ($reservations as $key => $value) {
							$is_in_array = in_array($value->date_start ,$array_of_holidays);
							$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');

							if(
								($day_of_week == 1
									|| $day_of_week == 2
									|| $day_of_week == 3
									|| $day_of_week == 4
									|| $day_of_week == 5)
								&& !$is_in_array
							){
								array_push($array_of_reservations, $value);
							}
						}

						if(count($array_of_reservations) >= $credits->morning || $credits->morning <= 0){
							$hasCredits = false;
							$message = 'Error, no tiene creditos para los dias laborables en la mañana ';
						}
					}else{
						$array_of_reservations = [];
						$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
							->whereMonth('date_start', '=', $date->format('m'))
							->where('customer_id', '=', $customer_id)
							->where('boat_id', '=', $boat_id)
							->whereIn('schedule_id', [1,3])
							->whereNotIn('id', $array_of_id_reservation_24_hours)
							->where('status_id', '!=', 3)
							->get();
						foreach ($reservations as $key => $value) {
							$is_in_array = in_array($value->date_start ,$array_of_holidays);
							$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');

							if(
								$day_of_week == 0
								|| $day_of_week == 6
								|| $is_in_array
							){
								array_push($array_of_reservations, $value);
							}
						}

						if(count($array_of_reservations) >= $credits->festivo_morning || $credits->festivo_morning <= 0){
							$hasCredits = false;
							$message = 'Error, no tiene creditos para los dias laborables en la mañana ';
						}
					}
				}
				break;

			case '5':

				if(($schedule->id == 1 || $schedule->id == 3)){


					if(!in_array($date->format('d/m/Y') ,$array_of_holidays)){

						$array_of_reservations = [];
						$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
							->whereMonth('date_start', '=', $date->format('m'))
							->where('customer_id', '=', $customer_id)
							->where('boat_id', '=', $boat_id)
							->whereIn('schedule_id', [1,3])
							->whereNotIn('id', $array_of_id_reservation_24_hours)
							->where('status_id', '!=', 3)
							->get();

						foreach ($reservations as $key => $value) {
							$is_in_array = in_array($value->date_start ,$array_of_holidays);
							$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
							if(
								($day_of_week == 1
									|| $day_of_week == 2
									|| $day_of_week == 3
									|| $day_of_week == 4
									|| $day_of_week == 5)
								&& !$is_in_array
							){
								array_push($array_of_reservations, $value);
							}
						}

						if(count($array_of_reservations) >= $credits->morning || $credits->morning <= 0){
							$hasCredits = false;
							$message = 'Error, no tiene creditos para los días laborables en la mañana ';
						}

					} else {
						$array_of_reservations = [];
						//return($array_of_id_reservation_24_hours);
						$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
							->whereMonth('date_start', '=', $date->format('m'))
							->where('customer_id', '=', $customer_id)
							->where('boat_id', '=', $boat_id)
							->whereIn('schedule_id', [1,3])
							->whereNotIn('id', $array_of_id_reservation_24_hours)
							->where('status_id', '!=', 3)
							->get();

						foreach ($reservations as $key => $value) {
							$is_in_array = in_array($value->date_start ,$array_of_holidays);
							$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
							if(
								$day_of_week == 6
								|| $day_of_week == 0
								|| $is_in_array
							){
								array_push($array_of_reservations, $value);
							}
						}
						if(count($array_of_reservations) >= $credits->festivo_morning || $credits->festivo_morning <= 0){
							$hasCredits = false;
							$message = 'Error, no tiene creditos para fines de semana o festivos en la mañana ';
						}
					}


				}else{
					$array_of_reservations = [];
					$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
						->whereMonth('date_start', '=', $date->format('m'))
						->where('customer_id', '=', $customer_id)
						->where('boat_id', '=', $boat_id)
						->whereIn('schedule_id', [2,4])
						->whereNotIn('id', $array_of_id_reservation_24_hours)
						->where('status_id', '!=', 3)
						->get();
					foreach ($reservations as $key => $value) {
						$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						$is_in_array = in_array($value->date_start ,$array_of_holidays);

						if(
							$day_of_week == 6
							|| $day_of_week == 5
							|| $is_in_array
						){
							array_push($array_of_reservations, $value);
						}
					}

					if(count($array_of_reservations) >= $credits->festivo_afternoon || $credits->festivo_afternoon <= 0){
						$hasCredits = false;
						$message = 'Error, no tiene creditos para fines de semana o festivos en la tarde ';
					}
				}
				break;

			case '0':
				if($schedule->id == 2 || $schedule->id == 4){
					if(!in_array($date->format('d/m/Y') ,$array_of_holidays)){
						$array_of_reservations = [];
						$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
							->whereMonth('date_start', '=', $date->format('m'))
							->where('customer_id', '=', $customer_id)
							->where('boat_id', '=', $boat_id)
							->whereIn('schedule_id', [2,4])
							->whereNotIn('id', $array_of_id_reservation_24_hours)
							->where('status_id', '!=', 3)
							->get();
						foreach ($reservations as $key => $value) {
							$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
							$is_in_array = in_array($value->date_start ,$array_of_holidays);
							if(
								($day_of_week == 1
									|| $day_of_week == 2
									|| $day_of_week == 3
									|| $day_of_week == 4
									|| $day_of_week == 0)
								&& !$is_in_array
							){
								array_push($array_of_reservations, $value);
							}
						}
						if(count($array_of_reservations) >= $credits->afternoon || $credits->afternoon <= 0){
							$hasCredits = false;
							$message = 'Error, no tiene creditos para los días laborables en la tarde ';
						}
					}else{
						$array_of_reservations = [];
						$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
							->whereMonth('date_start', '=', $date->format('m'))
							->where('customer_id', '=', $customer_id)
							->where('boat_id', '=', $boat_id)
							->whereIn('schedule_id', [2,4])
							->whereNotIn('id', $array_of_id_reservation_24_hours)
							->where('status_id', '!=', 3)
							->get();
						foreach ($reservations as $key => $value) {
							$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
							$is_in_array = in_array($value->date_start ,$array_of_holidays);
							if(
								$day_of_week == 5
								|| $day_of_week == 6
								|| $is_in_array
							){
								array_push($array_of_reservations, $value);
							}
						}

						if(count($array_of_reservations) >= $credits->festivo_afternoon || $credits->festivo_afternoon <= 0){
							$hasCredits = false;
							$message = 'Error, no tiene creditos para los fines de semana o festivos en la tarde. ';
						}
					}
				}else{
					$array_of_reservations = [];
					$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
						->whereMonth('date_start', '=', $date->format('m'))
						->where('customer_id', '=', $customer_id)
						->where('boat_id', '=', $boat_id)
						->whereIn('schedule_id', [1,3])
						->whereNotIn('id', $array_of_id_reservation_24_hours)
						->where('status_id', '!=', 3)
						->get();
					foreach ($reservations as $key => $value) {
						$is_in_array = in_array($value->date_start ,$array_of_holidays);
						$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						if(
							$day_of_week == 6
							|| $day_of_week == 0
							|| $is_in_array
						){
							array_push($array_of_reservations, $value);
						}
					}

					if(count($array_of_reservations) >= $credits->festivo_morning || $credits->festivo_morning <= 0){
						$hasCredits = false;
						$message = 'Error, no tiene creditos para fines de semana o festivos en la mañana ';
					}
				}
				break;

			case '6':
				if($schedule->id == 1 || $schedule->id == 3){
					$array_of_reservations = [];
					$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
						->whereMonth('date_start', '=', $date->format('m'))
						->where('customer_id', '=', $customer_id)
						->where('boat_id', '=', $boat_id)
						->whereIn('schedule_id', [1,3])
						->whereNotIn('id', $array_of_id_reservation_24_hours)
						->where('status_id', '!=', 3)
						->get();

					foreach ($reservations as $key => $value) {
						$is_in_array = in_array($value->date_start ,$array_of_holidays);
						$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						if(
							$day_of_week == 6
							|| $day_of_week == 0
							|| $is_in_array
						){
							array_push($array_of_reservations, $value);
						}
					}

					if(count($array_of_reservations) >= $credits->festivo_morning || $credits->festivo_morning <= 0){
						$hasCredits = false;
						$message = 'Error, no tiene creditos para fines de semana o festivos en la mañana ';
					}
				}else{
					$array_of_reservations = [];
					$reservations = Reservations::whereYear('date_start', '=', $date->format('Y'))
						->whereMonth('date_start', '=', $date->format('m'))
						->where('customer_id', '=', $customer_id)
						->where('boat_id', '=', $boat_id)
						->whereIn('schedule_id', [2,4])
						->whereNotIn('id', $array_of_id_reservation_24_hours)
						->where('status_id', '!=', 3)
						->get();
					foreach ($reservations as $key => $value) {
						$is_in_array = in_array($value->date_start ,$array_of_holidays);
						$day_of_week = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						if(
							$day_of_week == 6
							|| $day_of_week == 5
							|| $is_in_array
						){
							array_push($array_of_reservations, $value);
						}
					}

					if(count($array_of_reservations) >= $credits->festivo_afternoon || $credits->festivo_afternoon <= 0){
						$hasCredits = false;
						$message = 'Error, no tiene creditos para fines de semana o festivos en la tarde ';
					}
				}
				break;
		}

		if(!$hasCredits && ($moreThan24Hours > 24 || $moreThan24Hours <= 0)){
			// $message = 'Error, No tiene creditos para esta fecha.';
			$pass = false;
			return ['pass' => $pass, 'message' => $message, 'credits' => $credits];
		}else if(!$hasCredits && ($moreThan24Hours <= 24 && $moreThan24Hours > 0)){

			if($this->checkHoursToReserve($date_time_end, $user_id, $customer_id, $boat_id, $schedule)['pass']){
				$message = 'Esta reserva no consume creditos por faltar: '.$moreThan24Hours.' horas.' ;
				$pass = true;
				return ['pass' => $pass, 'message' => $message, 'credits' => $credits];
			}else{
				$message = 'Esta reserva fue reservada anteriormente, por lo tanto consume creditos y no tiene creditos para esta fecha.' ;
				$pass = false;
				return ['pass' => $pass, 'message' => $message, 'credits' => $credits];
			}

		}else if(($moreThan24Hours > 24 || $moreThan24Hours <= 0) && $hasCredits){
			$message = 'Correcto, faltan: '.$moreThan24Hours.' horas para esta reserva.';
			$pass = true;
			return ['pass' => $pass, 'message' => $message, 'credits' => $credits];
		}else{
			$message = 'Correcto, tiene creditos para esta fecha.';
			$pass = true;
			return ['pass' => $pass, 'message' => $message, 'credits' => $credits];
		}

	}

	public function checkTwoHolidaysYearly($date_time, $user_id, $customer_id, $boat_id, $schedule){

		$pass = true;

		$message = 'Correcto, aun no tiene 2 festivos reservados.';

		$curret_year = $date_time->format('Y');

		$holidays = Festive::whereYear('date', '=',  $curret_year)->get();

		$holidays_array_dates = [];

		foreach ($holidays as $key => $value) {
			$date = Carbon::createFromFormat("m/d/Y",$value->date)->format('Y-m-d');
			array_push($holidays_array_dates, $date);
		}

		$reservations_in_holidays = Reservations::whereYear('date_start', '=',  $curret_year)
			->where('status_id', '!=', 3)
			->where('customer_id', '=', $customer_id)
			->whereIn('date_start', $holidays_array_dates)
			->where('boat_id', '=', $boat_id)
			->get();

		$isInHoliday = false;

		foreach ($holidays_array_dates as $key => $value) {
			if($value == $date_time->format('Y-m-d')){
				$isInHoliday = true;
			}
		}

		$reservation_holidays_count = count($reservations_in_holidays);

		if($reservation_holidays_count >= 2 && $isInHoliday){
			$pass = false;
			$message = 'Error, ya tiene dos festivos reservados para el año '.$curret_year;
		}
		return ['pass' => $pass, 'message' => $message, 'count' => $reservation_holidays_count];
	}

	public function checkBlockDate($date_time, $user_id, $customer_id, $boat_id, $schedule){
		$pass = true;
		$message = 'Correcto, fecha no bloqueada';
		$blocked_date = Block::where('boat_id', '=', $boat_id)
			->whereDate('day', '=', $date_time->format('Y-m-d'))
			->where('schedule_id', '=', $schedule->id)
			->first();


		if(isset($blocked_date) && !empty($blocked_date)){
			$reason = 'Mantenimiento';

			switch ($blocked_date->reason) {
				case 'F':
					$reason = 'Formación';
					break;
				case 'M':
					$reason = 'Mantenimiento';
					break;
				case 'L':
					$reason = 'Limpieza';
					break;
			}

			$pass = false;
			$message = 'Error, fecha bloqueada por: '.$reason;
		}

		return ['pass' => $pass, 'message' => $message, 'blocked_date' => $blocked_date];
	}

	public function checkMaxMonth($date_time, $user_id, $customer_id, $boat_id, $schedule, $date_time_end){
		$pass = true;
		$message = 'Correcto, no ha reservado mas de los fin de semana permitidos';
		$maxWeekend = 4;
		$maxWeekDays = 10;
		$weekends = [];
		$array_of_week_days = [];
		$current_day_of_the_week = $date_time->format('w');


		//CHECK RESERVATIONS JULY AND AGUST
		if($date_time->format('m') == 6 || $date_time->format('m') == 7){
			$maxWeekend = 4;
			$maxWeekDays = 10;
		}


		$days = Reservations::where('customer_id', '=', $customer_id)
			->where('boat_id', '=', $boat_id)
			->whereYear('date_start', '=', $date_time->format('Y'))
			->whereMonth('date_start', '=', $date_time->format('m'))
			// ->whereIn('schedule_id', [])
			->where('status_id', '=', 2)
			->get();

		switch ($current_day_of_the_week) {
			case '1':
			case '2':
			case '3':
			case '4':
				//ALL DAY IS WORK TIME, MONDAY, TUEASDAY, WEDNESDAY, THURSDAY
				$array_of_week_days = [];

				foreach ($days as $key => $value) {
					$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
					switch ($day_of_the_week_reservation) {
						case '1':
						case '2':
						case '3':
						case '4':
							array_push($array_of_week_days, $value);
							break;
						case '5':
							if($value->schedule_id == 1 || $value->schedule_id == 3){
								array_push($array_of_week_days, $value);
							}
							break;
						case '0':
							if($value->schedule_id == 2 || $value->schedule_id == 4){
								array_push($array_of_week_days, $value);
							}
							break;
					}

				}

				break;

			case '0':
				//WEEKEND HALF DAY (MORNINGS) :  SUNDAY
				$weekends = [];
				if($schedule->id == 1 || $schedule->id == 3){
					foreach ($days as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '6':
								array_push($weekends, $value);
								break;
							case '0':
								if($value->schedule_id == 1 || $value->schedule_id == 3){
									array_push($weekends, $value);
								}
								break;
							case '5':
								if($value->schedule_id == 2 || $value->schedule_id == 4){
									array_push($weekends, $value);
								}
								break;
						}
					}
				}else{
					foreach ($days as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '1':
							case '2':
							case '3':
							case '4':
								array_push($array_of_week_days, $value);
								break;
							case '5':
								if($value->schedule_id == 1 || $value->schedule_id == 3){
									array_push($array_of_week_days, $value);
								}
								break;
							case '0':
								if($value->schedule_id == 2 || $value->schedule_id == 4){
									array_push($array_of_week_days, $value);
								}
								break;
						}

					}
				}
				break;
			case '5':
				//WEEKEND HALF DAY (NIGHT) : FRIDAY
				$weekends = [];
				if($schedule->id == 2 || $schedule->id == 4){
					foreach ($days as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '6':
								array_push($weekends, $value);
								break;
							case '0':
								if($value->schedule_id == 1 || $value->schedule_id == 3){
									array_push($weekends, $value);
								}
								break;
							case '5':
								if($value->schedule_id == 2 || $value->schedule_id == 4){
									array_push($weekends, $value);
								}
								break;
						}
					}
				}else{
					foreach ($days as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '1':
							case '2':
							case '3':
							case '4':
								array_push($array_of_week_days, $value);
								break;
							case '5':
								if($value->schedule_id == 1 || $value->schedule_id == 3){
									array_push($array_of_week_days, $value);
								}
								break;
							case '0':
								if($value->schedule_id == 2 || $value->schedule_id == 4){
									array_push($array_of_week_days, $value);
								}
								break;
						}

					}
				}
				break;
			case '6':
				// WEEKEND ALL DAY: SATURDAY
				$weekends = [];
				foreach ($days as $key => $value) {
					$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
					switch ($day_of_the_week_reservation) {
						case '6':
							array_push($weekends, $value);
							break;
						case '0':
							if($value->schedule_id == 1 || $value->schedule_id == 3){
								array_push($weekends, $value);
							}
							break;
						case '5':
							if($value->schedule_id == 2 || $value->schedule_id == 4){
								array_push($weekends, $value);
							}
							break;
					}
				}
				break;
		}

		$count_weekends = count($weekends);
		$is24Hours = $this->checkHoursToReserve($date_time_end, $user_id, $customer_id, $boat_id, $schedule)['pass'];

		if($count_weekends >= $maxWeekend && !$is24Hours){
			$pass = false;
			$message = 'Error, ya ha reservado mas de los '.$maxWeekend.' fines de semana permitidos Mensuales.';
		}

		$count_week_days = count($array_of_week_days);

		if($count_week_days >= $maxWeekDays && !$is24Hours){
			$pass = false;
			$message = 'Error, ya ha reservado mas de los '.$maxWeekDays.' días laborables permitidos Mensuales.';
		}

		return ['pass' => $pass, 'message' => $message, 'weekends' => $weekends];
	}

	public function checkMaxByBlock($date_time, $user_id, $customer_id, $boat_id, $schedule, $date_time_end){
		$pass = true;
		$message = 'Correcto, no ha reservado mas de permitido por bloque.';
		$maxWeekend = 8;
		$maxWeekDays = 16;
		$maxWeekendMorning = 4;
		$maxWeekendAfternoon = 4;
		$weekends = [];
		$array_of_week_days = [];
		$current_day_of_the_week = $date_time->format('w');
		$current_month = $date_time->format('m');
		$array_of_current_block_months = [];

		switch ($current_month) {
			case '01':
			case '02':
			case '03':
				$array_of_current_block_months = ['01', '02', '03'];
				break;

			case '04':
			case '05':
			case '06':
				$array_of_current_block_months = ['04', '05', '06'];
				break;

			case '07':
			case '08':
				$array_of_current_block_months = ['07', '08'];
				break;

			case '09':
			case '10':
			case '11':
			case '12':
				$array_of_current_block_months = ['09', '10', '11', '12'];
				break;
		}

		//CHECK RESERVATIONS JULY AND AGUST
		if($date_time->format('m') == 7 || $date_time->format('m') == 8){
			$maxWeekendMorning = 2;
			$maxWeekendAfternoon = 2;
			$maxWeekend = 4;
			$maxWeekDays = 14;
		}

		$days = Reservations::where('customer_id', '=', $customer_id)
			->where('boat_id', '=', $boat_id)
			->whereYear('date_start', '=', $date_time->format('Y'))
			->whereIn(DB::raw('MONTH(date_start)'), $array_of_current_block_months)
			->where('status_id', '=', 2)
			->get();

		switch ($current_day_of_the_week) {
			case '1':
			case '2':
			case '3':
			case '4':
				//ALL DAY IS WORK TIME, MONDAY, TUEASDAY, WEDNESDAY, THURSDAY
				$array_of_week_days = [];

				foreach ($days as $key => $value) {
					$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
					switch ($day_of_the_week_reservation) {
						case '1':
						case '2':
						case '3':
						case '4':
							array_push($array_of_week_days, $value);
							break;
						case '5':
							if($value->schedule_id == 1 || $value->schedule_id == 3){
								array_push($array_of_week_days, $value);
							}
							break;
						case '0':
							if($value->schedule_id == 2 || $value->schedule_id == 4){
								array_push($array_of_week_days, $value);
							}
							break;
					}

				}

				break;

			case '0':
				//WEEKEND HALF DAY (MORNINGS) :  SUNDAY
				$weekends = [];
				if($schedule->id == 1 || $schedule->id == 3){
					foreach ($days as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '6':
								array_push($weekends, $value);
								break;
							case '0':
								if($value->schedule_id == 1 || $value->schedule_id == 3){
									array_push($weekends, $value);
								}
								break;
							case '5':
								if($value->schedule_id == 2 || $value->schedule_id == 4){
									array_push($weekends, $value);
								}
								break;
						}
					}
				}else{
					foreach ($days as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '1':
							case '2':
							case '3':
							case '4':
								array_push($array_of_week_days, $value);
								break;
							case '5':
								if($value->schedule_id == 1 || $value->schedule_id == 3){
									array_push($array_of_week_days, $value);
								}
								break;
							case '0':
								if($value->schedule_id == 2 || $value->schedule_id == 4){
									array_push($array_of_week_days, $value);
								}
								break;
						}

					}
				}
				break;
			case '5':
				//WEEKEND HALF DAY (NIGHT) : FRIDAY
				$weekends = [];
				if($schedule->id == 2 || $schedule->id == 4){
					foreach ($days as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '6':
								array_push($weekends, $value);
								break;
							case '0':
								if($value->schedule_id == 1 || $value->schedule_id == 3){
									array_push($weekends, $value);
								}
								break;
							case '5':
								if($value->schedule_id == 2 || $value->schedule_id == 4){
									array_push($weekends, $value);
								}
								break;
						}
					}
				}else{
					foreach ($days as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '1':
							case '2':
							case '3':
							case '4':
								array_push($array_of_week_days, $value);
								break;
							case '5':
								if($value->schedule_id == 1 || $value->schedule_id == 3){
									array_push($array_of_week_days, $value);
								}
								break;
							case '0':
								if($value->schedule_id == 2 || $value->schedule_id == 4){
									array_push($array_of_week_days, $value);
								}
								break;
						}

					}
				}
				break;
			case '6':
				// WEEKEND ALL DAY: SATURDAY
				$weekends = [];
				foreach ($days as $key => $value) {
					$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
					switch ($day_of_the_week_reservation) {
						case '6':
							array_push($weekends, $value);
							break;
						case '0':
							if($value->schedule_id == 1 || $value->schedule_id == 3){
								array_push($weekends, $value);
							}
							break;
						case '5':
							if($value->schedule_id == 2 || $value->schedule_id == 4){
								array_push($weekends, $value);
							}
							break;
					}
				}
				break;
		}

		$is24Hours = $this->checkHoursToReserve($date_time_end, $user_id, $customer_id, $boat_id, $schedule)['pass'];

		$count_weekends = count($weekends);

		$array_of_weekends_morning = [];
		$array_of_weekends_afternoon = [];

		foreach ($weekends as $key => $value) {
			if($value->schedule_id == 1 || $value->schedule_id == 3){
				array_push($array_of_weekends_morning, $value);
			}else{
				array_push($array_of_weekends_afternoon, $value);
			}
		}

		if(count($array_of_weekends_morning) >= $maxWeekendMorning && !$is24Hours && ($schedule->id == 1 || $schedule->id == 3) ){
			$pass = false;
			$message = 'Error, ya ha reservado mas de los '.$maxWeekendMorning.' fines de semana de mañana permitidos permitidos por bloque.';
		}

		if(count($array_of_weekends_afternoon) >= $maxWeekendAfternoon && !$is24Hours && ($schedule->id == 2 || $schedule->id == 4)){
			$pass = false;
			$message = 'Error, ya ha reservado mas de los '.$maxWeekendAfternoon.' fines de semana de tarde permitidos por bloque.';
		}

		if($count_weekends >= $maxWeekend && !$is24Hours){
			$pass = false;
			$message = 'Error, ya ha reservado mas de los '.$maxWeekend.' fines de semana permitidos por bloque.';
		}

		$count_week_days = count($array_of_week_days);

		if($count_week_days >= $maxWeekDays && !$is24Hours){
			$pass = false;
			$message = 'Error, ya ha reservado mas de los '.$maxWeekDays.' días laborables permitidos por bloque.';
		}

		return ['pass' => $pass, 'message' => $message, 'weekends' => $weekends];
	}

	public function checkHoursToReserve($date_time, $user_id, $customer_id, $boat_id, $schedule){

		$pass = true;
		$message = "NO MESSAGE";

		$now = Carbon::now();

		$tomorrow = Carbon::now()->addDay();

		$date_start = Carbon::createFromFormat('Y-m-d', $date_time->format('Y-m-d'));

		$date_time_copy = Carbon::createFromFormat('Y-m-d H:i:s', $date_time->format('Y-m-d').' '.$schedule->start_hour);

		if($schedule->id%2 == 0){
			$date_start = $date_start->subDay();
			$tomorrow->addDay();
		}

		switch ($schedule->id) {
			case 2:
			case 4:
				$date_time_copy = Carbon::createFromFormat('Y-m-d H:i:s', $date_time_copy->subDay()->format('Y-m-d').' '.$schedule->start_hour);
				break;
			default:
				$date_time_copy = Carbon::createFromFormat('Y-m-d H:i:s', $date_time_copy->format('Y-m-d').' '.$schedule->start_hour);
				break;
		}

		$diff = $date_time_copy->diffInSeconds(Carbon::now());
		$between_24_hours = ($diff < 86400) ? true : false;


		$reservations = Reservations::where('boat_id', '=', $boat_id)
			->where('customer_id', '=', $customer_id)
			->where('schedule_id', '=', $schedule->id)
			->where('status_id', '=', 3)
			->whereDate('date_start', '=', $date_start->format('Y-m-d'))
			->get();

		$has_not_reserve_before = count($reservations) > 0 ?  false : true;


		if($between_24_hours && $has_not_reserve_before){
			$pass = true;
			$message = 'Esta reservación esta dentro de las siguientes 24 horas, por lo tanto no consume creditos.';
		}else if($between_24_hours && !$has_not_reserve_before){

			$pass = false;
			$message = 'Esta reservación esta dentro de las siguientes 24 horas, pero ya fue reservada y cancelada con anterioridad por lo tanto si consumira creditos.';
		}else if(!$between_24_hours){
			$pass = false;
			$message = ' ';
		}

		return ['pass' => $pass, 'message' => $message, 'hours' => $tomorrow];
	}

	public function checkSchedule($date_time, $user_id, $customer_id, $boat_id, $schedule, $user_modality, $date_time_end){
		$pass = true;
		$message = ' ';
		$array_of_reservations = [];

		$max_reservation = 0;

		$day_of_the_week = $date_time->format('w');

		$array_of_month_low = [1,2,3,4,5,6,9,10,11,12];
		$array_of_month_high = [6,7];

		$reservations = Reservations::where('boat_id', '=', $boat_id)
			->where('customer_id', '=', $customer_id)
			->where('schedule_id', '=', $schedule->id)
			->whereMonth('date_start', '=', $date_time->format('m'))
			->whereYear('date_start', '=', $date_time->format('Y'))
			->where('status_id', '!=', 3)
			->get();

		switch ($day_of_the_week) {
			case '1':
			case '2':
			case '3':
			case '4':
				if($schedule->id == 1 || $schedule->id == 3){
					//WORK DAY
					if(in_array($date_time->format('m'), $array_of_month_low)){
						$max_reservation = ($user_modality == 1 ? 4 : 8 );
					}else{
						$max_reservation = ($user_modality == 1 ? 2 : 5 );
					}

					foreach ($reservations as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '1':
							case '2':
							case '3':
							case '4':
							case '5':
								array_push($array_of_reservations, $value);
								break;
						}
					}

				}else{
					//WORK DAY
					if(in_array($date_time->format('m'), $array_of_month_low)){
						$max_reservation = ($user_modality == 1 ? 4 : 8 );
					}else{
						$max_reservation = ($user_modality == 1 ? 2 : 5 );
					}

					foreach ($reservations as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '1':
							case '2':
							case '3':
							case '4':
							case '0':
								array_push($array_of_reservations, $value);
								break;
						}
					}
				}
				break;

			case '5':
				if($schedule->id == 1 || $schedule->id == 3){
					//WORK DAY
					if(in_array($date_time->format('m'), $array_of_month_low)){
						$max_reservation = ($user_modality == 1 ? 4 : 8 );
					}else{
						$max_reservation = ($user_modality == 1 ? 2 : 5 );
					}

					foreach ($reservations as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '1':
							case '2':
							case '3':
							case '4':
							case '5':
								array_push($array_of_reservations, $value);
								break;
						}
					}

				}else{
					//WEEKEND
					if(in_array($date_time->format('m'), $array_of_month_low)){
						$max_reservation = ($user_modality == 1 ? 2 : 4 );
					}else{
						$max_reservation = ($user_modality == 1 ? 1 : 2 );
					}

					foreach ($reservations as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '5':
							case '6':
								array_push($array_of_reservations, $value);
								break;
						}
					}
				}
				break;

			case '6':
				//WEEKEND
				if(in_array($date_time->format('m'), $array_of_month_low)){
					$max_reservation = ($user_modality == 1 ? 2 : 4 );
				}else{
					$max_reservation = ($user_modality == 1 ? 1 : 2 );
				}

				if($schedule->id == 1 || $schedule->id == 2){
					foreach ($reservations as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '6':
							case '0':
								array_push($array_of_reservations, $value);
								break;
						}
					}
				}else{
					foreach ($reservations as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '5':
							case '6':
								array_push($array_of_reservations, $value);
								break;
						}
					}
				}

				break;

			case '0':
				if($schedule->id == 1 || $schedule->id == 3){
					//WEEKEND
					if(in_array($date_time->format('m'), $array_of_month_low)){
						$max_reservation = ($user_modality == 1 ? 2 : 4 );
					}else{
						$max_reservation = ($user_modality == 1 ? 1 : 2 );
					}

					foreach ($reservations as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '0':
							case '6':
								array_push($array_of_reservations, $value);
								break;
						}
					}

				}else{
					//WORK DAY
					if(in_array($date_time->format('m'), $array_of_month_low)){
						$max_reservation = ($user_modality == 1 ? 4 : 8 );
					}else{
						$max_reservation = ($user_modality == 1 ? 2 : 5 );
					}

					foreach ($reservations as $key => $value) {
						$day_of_the_week_reservation = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('w');
						switch ($day_of_the_week_reservation) {
							case '1':
							case '2':
							case '3':
							case '4':
							case '0':
								array_push($array_of_reservations, $value);
								break;
						}
					}

				}
				break;
		}

		$id24Hours = $this->checkHoursToReserve($date_time_end, $user_id, $customer_id, $boat_id, $schedule);

		if(count($array_of_reservations) >= $max_reservation && !$id24Hours['pass']){
			$pass = false;
			$message = 'Error, ya a superado el limite de '.$max_reservation.' pre-reservas en el mes '.$date_time->format('M').'.';
		} else if(count($array_of_reservations) >= $max_reservation && $id24Hours['pass']){
			$pass = true;
			$message = $id24Hours['message'];
		}else if(count($array_of_reservations) < $max_reservation && $id24Hours['pass']){
			$pass = true;
			$message = $id24Hours['message'];
		}else if(count($array_of_reservations) < $max_reservation && !$id24Hours['pass']){
			$pass = true;
			$message = ' ';
		}


		return ['pass' => $pass, 'message'=> $message, 'array_of_reservations' => $array_of_reservations];
	}

	public function calendar(Request $request)
	{
		//DEFINE ALL VAR WE NEED TO SET RULES

		$reference_number = strtoupper(uniqid('RS'));

		$customer = Customer::find(Auth::user()->customer_id);

		$users = Customer::with('boats')->where('id',$customer->id)->first();

		$date = DateTime::createFromFormat('d-m-Y', $request->date_start);

		$date_start = Carbon::createFromFormat('d-m-Y',$request->date_start)->format('d/m/Y');

		$schedule = $this->getScheduleValue($request->schedule);

		$date_time = Carbon::createFromFormat('d-m-Y H:i:s', $request->date_start.' '.$schedule->start_hour);

		$date_time_end = Carbon::createFromFormat('d-m-Y H:i:s', $request->date_start.' '.$schedule->end_hour);

		if($schedule->id%2 == 0){
			$date_time_end->addDay();
			// var_dump($date_time_end);
		}

		$boat = Boat::find($request->boat_id);

		$valid = true;

		$holiday = 0;

		$message = '';

		$register_credits = CreditRegister::where('customer_id', '=', $customer->id)
			->where('date_year', '=', $date_time->format('Y'))
			->where('boat_id', '=', $boat->id)
			// ->where('date_month', '=', $date_time->format('m'))
			->get();

		$total_credist_year = 0;

		foreach ($register_credits as $key => $value) {
			$total_credist = $value->festivo_morning + $value->festivo_afternoon + $value->morning + $value->afternoon;
			$total_credist_year = $total_credist_year + $total_credist;
		}

		$user_modality = (($total_credist_year/count($register_credits)) <= 3) ? 1 : 2 ; // 1 =  3 SALIDAS AND 2 = 7 SALIDAS THIS IS STILL NEEDS TO BE CHECKED

		//CHECK IF DATE HAS NOT PASS
		$DateInPast = $this->checkDateIsNotPass($date_time_end);

		if(!$DateInPast['pass']){
			$valid = false;
			alert()->message('Reserva', $DateInPast['message']);
			$message = $DateInPast['message'];
			return view('reservations.calendar', compact('date_start','request','users','boat','schedule','reference_number','valid', 'holiday','customer', 'message'));
		}
		// CHECK 24 HOURS OR 24 HOURS + RESERVED BEFORE
		$lessThanADay = $this->checkHoursToReserve($date_time_end, $request->user_id, $customer->id, $request->boat_id, $schedule);

		if($lessThanADay['pass']){
			$message = $lessThanADay['message'];
		}else{
			$message = $lessThanADay['message'];
		}

		//CHECK HAS CREDITS FOR THAT DAY
		$hasCredits = $this->checkCredits($date_time, $request->user_id, $customer->id, $request->boat_id, $schedule, $date_time_end);

		if(!$hasCredits['pass']&&!$lessThanADay){
			$valid = false;
			alert()->message('Reserva', $hasCredits['message']);
			$message = $hasCredits['message'].'HOLA';
			return view('reservations.calendar', compact('date_start','request','users','boat','schedule','reference_number','valid', 'holiday','customer', 'message'));
		}

		//CHECK IF HAS MORE THAN TWO RESERVES IN HOLIDAYS THIS YEAR
		$moreThanTwoHolidays = $this->checkTwoHolidaysYearly($date_time, $request->user_id, $customer->id, $request->boat_id, $schedule);

		if(!$moreThanTwoHolidays['pass']){
			$valid = false;
			alert()->message('Reserva', $moreThanTwoHolidays['message']);
			$message = $moreThanTwoHolidays['message'];
			return view('reservations.calendar', compact('date_start','request','users','boat','schedule','reference_number','valid', 'holiday','customer', 'message'));
		}

		//CHECK IF DATE IS BLOCKED BY ADMIN
		$blockedDay = $this->checkBlockDate($date_time, $request->user_id, $customer->id, $request->boat_id, $schedule);

		if(!$blockedDay['pass']){
			$valid = false;
			alert()->message('Reserva', $blockedDay['message']);
			$message = $blockedDay['message'];
			return view('reservations.calendar', compact('date_start','request','users','boat','schedule','reference_number','valid', 'holiday','customer', 'message'));
		}

		// CHECK MAX MOMNTHLY WEEKENDS
		$maxMonth = $this->checkMaxMonth($date_time, $request->user_id, $customer->id, $request->boat_id, $schedule, $date_time_end);

		if(!$maxMonth['pass']){
			$valid = false;
			alert()->message('Reserva', $maxMonth['message']);
			$message = $maxMonth['message'];
			return view('reservations.calendar', compact('date_start','request','users','boat','schedule','reference_number','valid', 'holiday','customer', 'message'));
		}

		$maxByBlock = $this->checkMaxByBlock($date_time, $request->user_id, $customer->id, $request->boat_id, $schedule, $date_time_end);

		if(!$maxByBlock['pass']){
			$valid = false;
			alert()->message('Reserva', $maxByBlock['message']);
			$message = $maxByBlock['message'];
			return view('reservations.calendar', compact('date_start','request','users','boat','schedule','reference_number','valid', 'holiday','customer', 'message'));
		}



		$isScheduleFree = $this->checkSchedule($date_time, $request->user_id, $customer->id, $request->boat_id, $schedule, $user_modality, $date_time_end);

		if(!$isScheduleFree['pass']){
			$valid = false;
			alert()->message('Reserva', $isScheduleFree['message']);
			$message = $isScheduleFree['message'];
			return view('reservations.calendar', compact('date_start','request','users','boat','schedule','reference_number','valid', 'holiday','customer', 'message'));
		}


		if ($valid)
			alert()->message('Reserva', 'Desea confirmar o cancelar?');
		else

			alert()->message('Reserva', $message);

		return view('reservations.calendar', compact('date_start','request','users','boat','schedule','reference_number','valid', 'holiday','customer', 'message'));

	}

	public function cancel(Request $request)
	{
		return view('reservations.calendar', compact('request'));

	}

	public function busqueda(Request $request)
	{

		$array_of_grouped_def = [];

		$reservations = Reservations::query();

		if (!empty($request->date_start)) {

			$date_start = Carbon::createFromFormat('d/m/Y',$request->date_start)->format('Y-m-d');
			$reservations->where(function ($query) use ($request,$date_start) {
				$query->where('date_start',$date_start);
			});
		}


		if (!empty($request->schedule_id)) {
			$reservations->where(function ($query) use ($request) {
				$query->where('schedule_id',$request->schedule_id);
			});
		}

		if (!empty($request->status_id)) {
			$reservations->where(function ($query) use ($request) {
				$query->where('status_id',$request->status_id);
			});
		}

		if (!empty($request->boat_id)) {

			$reservations->where(function ($query) use ($request) {
				$query->where('boat_id',$request->boat_id);
			});

		}


		$reservations = $reservations->paginate(30);

		$reservations->appends(request()->except('page'))->links();

		$estado = ["" => ""] + Status::lists('name', 'id')->toArray();
		$status = Status::get();
		$barcos = ["" => ""] + Boat::lists('name', 'id')->toArray();
		$turno = ["" => ""] + Schedule::groupBy('name')->lists('name', 'id')->toArray();
		return view('reservations.index', compact('reservations','status','turno','estado','barcos', 'array_of_grouped_def'));
	}

	public function confirmation(Request $request)
	{

		$reservation = Reservations::find($request->reservation_id);

		$now = Carbon::now();
		$fechaReserva = Carbon::createFromFormat('m/d/Y',$reservation->date_start)->format('Y-m-d');

		//if ( $fechaReserva >= $now ) {
		// CONTROL para evitar confirmar 2 veces un mismo barco
		$sqlDuplicados = 'SELECT * FROM reservations WHERE date_start = STR_TO_DATE("'.$fechaReserva .'","%Y-%m-%d") AND boat_id = '.$reservation->boat_id .' AND schedule_id = '.$reservation->schedule_id.' AND status_id IN (1,2) AND id != '.$reservation->id;
		$isDuplicado = count(DB::select($sqlDuplicados));

		if ($isDuplicado < 1){
			$reservation->status_id = 1;
			//dd($reservation);
		}else{
			$reservation->status_id = 4;
			//dd($reservation);
		}
		$reservation->save();

		$this->sendMailReservation($reservation);

		return redirect('reservations')->withSuccess('Reservation has been updated.');

		// }else{
		//     return redirect('reservations')->withError('La fecha de la reserva es menor que la fecha actual.');
		// }
	}

	public function confirmationGroup(Request $request)
	{
		foreach ($request->all() as $key => $value) {
			if(is_numeric($value)){
				$reservation = Reservations::find($value);
				$now = Carbon::now();
				$fechaReserva = Carbon::createFromFormat('m/d/Y',$reservation->date_start)->format('Y-m-d');
				//if ( $fechaReserva >= $now ) {
				// CONTROL para evitar confirmar 2 veces un mismo barco
				$sqlDuplicados = 'SELECT * FROM reservations WHERE date_start = STR_TO_DATE("'.$fechaReserva .'","%Y-%m-%d") AND boat_id = '.$reservation->boat_id .' AND schedule_id = '.$reservation->schedule_id.' AND status_id IN (1,2) AND id != '.$reservation->id;
				$isDuplicado = count(DB::select($sqlDuplicados));

				if ($isDuplicado < 1){
					$reservation->status_id = 1;
					//dd($reservation);
				}else{
					$reservation->status_id = 4;
					//dd($reservation);
				}
				$reservation->save();

				$this->sendMailReservation($reservation);


				// }else{
				//     return redirect('reservations')->withError('La fecha de la reserva es menor que la fecha actual.');
				// }
			}
		}
		return redirect('reservations')->withSuccess('Reservation has been updated.');
	}

	protected function sendMailReservation(Reservations $reservation)
	{

		$query = Reservations::select('reservations.id', 'reservations.reference_number',
			'reservations.first_name','reservations.last_name', 'reservations.email', 'reservations.date_start',
			'schedules.name as schedules','boat.name as boat')
			->join('schedules', 'reservations.schedule_id', '=', 'schedules.id')
			->join('boat', 'reservations.boat_id', '=', 'boat.id')
			->where ('reservations.id',$reservation->id);


		$reservation=$query->first()->toArray();
		/*
		Mail::send('email.reservation', $reservation, function ($m) use ($reservation) {

			$m->from('info@skippersailingclub.com', 'SKIPPER');
			$m->to($reservation['email'])->subject('Confirmación de reserva | SKIPPER SAILING CLUB');
			$m->from('info@skippersailingclub.com', 'SKIPPER');
			$m->to($reservation['email'])->subject('Reserva | SKIPPER | NÚMERO DE RESERVA:' . $reservation['reference_number']);
		});
		*/
	}

	public function cancellationGroup(Request $request)
	{
		foreach ($request->all() as $key => $value) {
			if(is_numeric($value)){
				$reservation = Reservations::find($value);
				$reservation->status_id = 3;
				$reservation->save();

				$fechaReserva = Carbon::createFromFormat('m/d/Y',$reservation->date_start)->format('Y-m-d');
				$scheduleReserva = $reservation->schedule_id;
				$barcoReserva = $reservation->boat_id;

				$this->checkWaitingReservation($reservation);
			}
		}
		return redirect('reservations')->withSuccess('Reservation has been updated.');
	}

	public function cancellation(Request $request)
	{

		$reservation = Reservations::find($request->reservation_id);
		$reservation->status_id = 3;
		$reservation->save();

		$fechaReserva = Carbon::createFromFormat('m/d/Y',$reservation->date_start)->format('Y-m-d');
		$scheduleReserva = $reservation->schedule_id;
		$barcoReserva = $reservation->boat_id;

		$this->checkWaitingReservation($reservation);

		return redirect('reservations')->withSuccess('Reservation has been updated.');
	}


	public function cancelFromMail() {
		$reference = Input::get('number');
		$reservation = Reservations::where('reference_number', '=', $reference)->where('status_id', '=', 2)->first();

		if(!empty($reservation)) {
			$reservation->status_id = 3;
			$reservation->update();
			$this->checkWaitingReservation($reservation);
			$message = 'Reservation has been cancelled';
			$is_error = false;
		} else {
			$message = 'Reservation not found';
			$is_error = true;
		}
		return view('welcome', compact('is_error', 'message'));

	}

	public function confirmFromMail() {
		$reference = Input::get('number');
		$reservation = Reservations::where('reference_number', '=', $reference)->where('status_id', '=', 2)->first();

		if(!empty($reservation)) {
			$reservation->status_id = 1;
			$reservation->update();
			$this->checkWaitingReservation($reservation);
			$message = 'Reservation has been confirmed';
			$is_error = false;
		} else {
			$message = 'Reservation not found';
			$is_error = true;
		}
		return view('welcome', compact('is_error', 'message'));

	}

	public function checkin (Request $request)
	{
		$reservation = $request->reservation;
		$questions = DB::table('questions')->join('answers', 'questions.id', '=', 'answers.question_id')->select( 'questions.id as questionId', 'questions.question', 'questions.question_type', 'answers.id as answerId', 'answers.answer' )->where('questions.question_type', '=', 'I')->get();

		$inspections = DB::table('inspections')->join('answers', 'inspections.answer_id', '=', 'answers.id')->join('questions', 'questions.id', '=', 'answers.question_id')->select('answers.id as answerId')->distinct()->where('inspections.reservation_id','=',$reservation)->where('questions.question_type', '=', 'I')->pluck('answerId');

		return view('reservations.checkin', compact('reservation','questions','inspections'));

	}

	public function checkinGroup (Request $request)
	{
		$reservation_array = explode('-', $request->reservation);
		$reservation = $request->reservation;

		$questions = DB::table('questions')->join('answers', 'questions.id', '=', 'answers.question_id')->select( 'questions.id as questionId', 'questions.question', 'questions.question_type', 'answers.id as answerId', 'answers.answer' )->where('questions.question_type', '=', 'I')->get();

		$inspections = DB::table('inspections')->join('answers', 'inspections.answer_id', '=', 'answers.id')->join('questions', 'questions.id', '=', 'answers.question_id')->select('answers.id as answerId')->distinct()->whereIn('inspections.reservation_id',$reservation_array)->where('questions.question_type', '=', 'I')->pluck('answerId');

		return view('reservations.checkin', compact('reservation','questions','inspections'));
	}

	public function savecheckin(Request $request)
	{
		if(is_numeric($request->reservation)){
			$reservation = $request->reservation;
			$parametros = $request->all();
			foreach($parametros as $key=>$value){
				if ($key != '_token' && $key != 'reservation'){
					$inspection = new Inspection();
					$inspection->user_id = Auth::user()->id;
					$inspection->answer_id = $value;
					$inspection->reservation_id = $reservation;
					$inspection->save();
				}
			}
		}else{
			$reservation_array = explode('-', $request->reservation);
			$params = $request->all();
			foreach ($reservation_array as $key_reservation => $value_reservation) {
				foreach($params as $key_params=>$value_params){
					if ($key_params != '_token' && $key_params != 'reservation'){
						$inspection = new Inspection();
						$inspection->user_id = Auth::user()->id;
						$inspection->answer_id = $value_params;
						$inspection->reservation_id = $value_reservation;
						$inspection->save();
					}
				}
			}
		}
		return redirect('reservations')->withSuccess('Checkin se ha guardado.');
	}

	public function checkout (Request $request)
	{

		$reservation = $request->reservation;
		$questions = DB::table('questions')->join('answers', 'questions.id', '=', 'answers.question_id')->select( 'questions.id as questionId', 'questions.question', 'questions.question_type', 'answers.id as answerId', 'answers.answer' )->where('questions.question_type', '=', 'O')->get();

		$inspections = DB::table('inspections')->join('answers', 'inspections.answer_id', '=', 'answers.id')->join('questions', 'questions.id', '=', 'answers.question_id')->select('answers.id as answerId')->distinct()->where('inspections.reservation_id','=',$reservation)->where('questions.question_type', '=', 'O')->pluck('answerId');

		return view('reservations.checkout', compact('reservation','questions', 'inspections'));

	}

	public function checkoutGroup (Request $request)
	{
		$reservation = $request->reservation;
		$reservation_array = explode('-', $request->reservation);
		$questions = DB::table('questions')->join('answers', 'questions.id', '=', 'answers.question_id')->select( 'questions.id as questionId', 'questions.question', 'questions.question_type', 'answers.id as answerId', 'answers.answer' )->where('questions.question_type', '=', 'O')->get();

		$inspections = DB::table('inspections')->join('answers', 'inspections.answer_id', '=', 'answers.id')->join('questions', 'questions.id', '=', 'answers.question_id')->select('answers.id as answerId')->distinct()->whereIn('inspections.reservation_id',$reservation_array)->where('questions.question_type', '=', 'O')->pluck('answerId');

		return view('reservations.checkout', compact('reservation','questions', 'inspections'));
	}

	public function savecheckout(Request $request)
	{
		$params = $request->all();
		if(is_numeric($request->reservation)){
			$reservation = $request->reservation;
			foreach($params as $key=>$value){
				if ($key != '_token' && $key != 'reservation'){
					$inspection = new Inspection();
					$inspection->user_id = Auth::user()->id;
					$inspection->answer_id = $value;
					$inspection->reservation_id = $reservation;
					$inspection->save();
				}
			}
		}else{
			$reservation = explode('-', $request->reservation);
			foreach ($reservation as $key_reservation => $value_reservation) {
				foreach($params as $key_params=>$value_params){
					if ($key_params != '_token' && $key_params != 'reservation'){
						$inspection = new Inspection();
						$inspection->user_id = Auth::user()->id;
						$inspection->answer_id = $value_params;
						$inspection->reservation_id = $value_reservation;
						$inspection->save();
					}
				}
			}
		}
		return redirect('reservations')->withSuccess('Checkout se ha guardado.');
	}

	public function getCredits(Request $request){

		return 'getCredits';
	}

	public function checkWaitingReservation($reservation){

		$date_start = Carbon::createFromFormat('d/m/Y', $reservation->date_start)->format('Y-m-d');

		$reservationInLine = Reservations::where('status_id', '=', 4)
			->with('user')
			->with('schedule')
			->with('boat')
			->where('schedule_id', '=', $reservation->schedule_id)
			->where('user_id', '!=', $reservation->user_id)
			->where('boat_id', '=', $reservation->boat_id)
			->whereDate('date_start', '=', $date_start)
			->orderBy('created_at')
			->first();

		if(isset($reservationInLine) && !empty($reservationInLine)){
			$reservationInLine->status_id = 2;
			$reservationInLine->update();

			$date_start = Carbon::createFromFormat('d/m/Y H:i:s', $reservationInLine->date_start.' '.$reservationInLine->schedule->start_hour);

			$test_sms = 'Su reserva para el '. $date_start->format('d-m-Y H:i') .' ha salido de lista de espera. Podrá ser confirmada a partir de 72 horas antes de la salida.';

			$this->sendSMS($reservationInLine->telephone, $test_sms);

			$text_email = ('<table width="840" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
                          <tbody>
                            <tr>
                                <td height="15" colspan="3"></td>
                            </tr>
                            <tr>
                              <td width="25"></td>
                                <td>
                                  <table cellpadding="0" cellspacing="0" width="100%">
                                    <tbody>
                                      <tr>
                                        <td>
                                          <img
                                                src="http://skipper.komunica.es/cron/logo.gif"
                                                width="200" height="109" class="CToWUd">
                                        </td>
                                      </tr>
                                      <tr>
                                          <td height="10"></td>
                                      </tr>
                                      <tr>
                                          <td>Apreciado Sr./Sra. '.$reservationInLine->first_name.' '. $reservationInLine->last_name .',<br>Skipper Sailing Club le communica que su reserva
                                              correspondiente a:<br><b>Fecha inicio</b>: '.$date_start->format('d-m-Y').' con horario de '.utf8_encode($reservationInLine->schedule->name).'<br><b>Fecha fin</b>: '.$date_start->format('d-m-Y').'<br><br>Para su barco asignado:<br><b>Barco</b>: '.$reservationInLine->boat->name.'<br><br>Ha salido
                                              de la lista de espera y podrá ser reservada a partir de las 72 horas antes de la salida.
                                              Skipper Sailing Club le enviará un recordatorio para poder reservarla.
                                          </td><br>
                                              <br>Atentamente,
                                              Skipper Sailing Club
                                          </td>
                                      </tr>
                                      <tr>
                                          <td height="10"></td>
                                      </tr>
                                      <tr>
                                          <td style="font-family:Arial,Helvetica,sans-serif;font-size:9px;font-weight:normal;color:rgb(153,153,153);padding:5px;text-align:center">
                                              Direccion: Calle Bernarregui, 8. Palma de Mallorca | Telefono <a href="tel:610%2061%2095%2047" target="_blank">610 619 547</a> |
                                              Email: <a href="mailto:bookings@skippersailingclub.com" style="font-family:Arial,Helvetica,sans-serif;font-size:9px;font-weight:normal;color:rgb(153,153,153);text-align:center;text-decoration:none"
                                                        target="_blank">bookings@skippersailingclub.com</a>
                                          </td>
                                      </tr>
                                      <tr>
                                          <td height="10"></td>
                                      </tr>
                                      <tr>
                                          <td style="font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:bold;padding:5px;text-align:center;background-color:rgb(204,204,204)">
                                              SKIPPER SAILING CLUB
                                          </td>
                                      </tr>
                                    </tbody>
                                  </table>
                                </td>
                              <td width="25"></td>
                            </tr>
                            <tr></tr>
                          </tbody>
                       </table>');

			$mailin3 = new MailinCustome('juan.garcia.mir@gmail.com', 'DnMLSq8aGA1czXOm');
			$mailin3->addTo($reservationInLine->email, $reservationInLine->first_name)->
			setFrom('bookings@skippersailingclub.com', 'Skipper')->
			setReplyTo('bookings@skippersailingclub.com','Skipper')->
			setSubject('Recordatorio salida de lista de espera de su reserva en Skipper Sailing Club')->
			setHtml($text_email);
			$resultEmail = $mailin3->send();

		}

	}

	private function sendSMS($telephone, $text){
		$message = new \Esendex\Model\DispatchMessage(
			"Skipper", $telephone, $text,
			\Esendex\Model\Message::SmsType );

		$authentication = new \Esendex\Authentication\LoginAuthentication(
			"EX0094931", "pedro@komunica.es", "Skippersailing2018" );
		$service = new \Esendex\DispatchService($authentication);
		$response = $service->send($message);

		$resultSMS = $response->id();

		return $resultSMS;
	}

}
