<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

// use Mail;
// use App\Mail\mailTest;

use Carbon\Carbon;

use App\Bookings24h;
use App\MailinCustome;
use App\Notifications;
use App\Reminder;
use App\Reservations;
use Illuminate\Support\Facades\DB;

// include_once 'MailinCustome.php';


require_once  'esendex/autoload.php';


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

	public function index(){
		$statusCode = 200;
		$response = ["result"=> true, 'data'=> null, 'message'=>'Index CronController.'];
		return response()->json($response, $statusCode);
	}

	public function checkReservations24h(){
		$now = Carbon::now();

		$reservations = Reservations::select('reservations.*')
			->where('status_id', '=', 2)
			->with('schedule')
			->join('bookings24h', 'bookings24h.reservation_id', '=', 'reservations.id')
			->whereDate('date_start', '>=', $now->format('Y-m-d'))
			->get();

		foreach ($reservations as $key => $value) {
			$date_time = Carbon::createFromFormat('Y-m-d H:i:s', $value->createdAtRealTime())->addMinutes(30);

			if($now->greaterThanOrEqualTo($date_time)){

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

				$reservations[$key]->status_id = 3;
				$reservations[$key]->update();

				$text_sms = 'su reservacion de '.$date->format('d-m-Y').' ha sido cancelada por no confirmar antes de los 30 min.';

				$this->sendSMS($value->telephone, $text_sms);

				$email_subject = 'Cancelación reserva 30min Skipper Sailing Club';

				$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. '.$value->first_name.' '. $value->last_name .',<br>Skipper Sailing Club le notifica que su reserva
                                                correspondiente a:<br><b>Fecha inicio</b>: '.$date->format('d-m-Y').' con horario de '.utf8_encode($value->schedule->name).'<br><b>Fecha fin</b>: '.$date->format('d-m-Y').' <br><br>Para su barco asignado:<br><b>Barco</b>: '.$value->boat->name.'<br><br>
                                                ha sido CANCELADA.
                                                <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
                                                TEST 3 Canceled
                                            </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($value->email, $value->first_name)->
				setFrom('bookings@skippersailingclub.com', 'Skipper')->
				setReplyTo('bookings@skippersailingclub.com','Skipper')->
				setSubject($email_subject)->
				setHtml($text_email);
				$resultEmail = $mailin3->send();


				$this->checkWaitingReservationCron($value, 1);
			}
		}

		$statusCode = 200;
		$response = ["result"=> true, 'data'=> $reservations, 'message'=>'checkReservations24h'];
		return response()->json($response, $statusCode);
	}

	public function checkReservationHasPass(){
		$now = Carbon::now();

		$reservations_in_pass = Reservations::whereDate('date_start', '<', $now->format('Y-m-d'))
			->whereIn('status_id', [2, 4])
			// ->get();
			->update(['status_id' => '3']);

		$statusCode = 200;
		$response = [
			'result'=> true,
			'data'=> $reservations_in_pass,
			'message'=>'Reservations that has pass and are not cancelled.'
		];
		return response()->json($response, $statusCode);
	}

	public function mailTest(){



		// $mail = Mail::send('emails.reminder',[],  function ($m) {
		//       $m->from(env('MAIL_USERNAME','http://skipper.komunica.es' ), 'Your Application');
		//
		//       $m->to('erick@teixweb.com', 'ERICK')->subject('Your Reminder!');
		//   });

		$statusCode = 200;
		$response = ["result"=> true, 'data'=> $mail, 'message'=>'Index CronController.'];
		return response()->json($response, $statusCode);
	}

	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;
	}

	private function checkIfThereIsANotification($reservation_id, $hours){

		$hours = $hours == '30min' ? $hours = '24h' : $hours;

		switch ($hours) {
			case '72h':
				$notification = Notifications::where('reservation_id', '=', $reservation_id)->where('72h', '=', 1)->get();
				break;
			case '48h':
				$notification = Notifications::where('reservation_id', '=', $reservation_id)->where('48h', '=', 1)->get();
				break;
			case '24h':
				$notification = Notifications::where('reservation_id', '=', $reservation_id)->where('24h', '=', 1)->get();
				break;
			case '30min':
				$notification = Notifications::where('reservation_id', '=', $reservation_id)->where('24h', '=', 2)->get();
				break;
			case '0h':
				$notification = Notifications::where('reservation_id', '=', $reservation_id)->where('24h', '=', 9)->get();
				break;
			default:
				$notification = Notifications::where('reservation_id', '=', $reservation_id)->where('24h', '=', 1)->get();
				break;

		}

		return $notification->isEmpty();
	}

	public function sendReminders(){

		$now = Carbon::now();

		$confirmLink = 'http://skipper.komunica.es/public/api/confirmReservation?number=';

		$resultSMS = '';

		$text = '';

		$email = '';

		$text_email = '';

		$reservations = Reservations::select('reservations.*', 'reminder.reminderType', 'reminder.reminderDisp', 'reminder.reminderDate', 'reminder.id as reminder_id')
			->with('boat')
			->with('schedule')
			->join('reminder', 'reminder.reservation_id', '=', 'reservations.id')
			->where('status_id', '=', 2)
			->where('reminder.sended', '!=', 1)
			->whereDate('reservations.date_start', '>=', $now->format('Y-m-d'))
			->whereDate('reminder.reminderDate', '>=', $now->format('Y-m-d H:i:s'))
			->get();

		foreach ($reservations as $key => $value) {
			$date_start = Carbon::createFromFormat('d/m/Y', $value->date_start)->format('d-m-Y');
			$text = ' ';
			if ($value->reminderType == '24h') {
				$reservations[$key]->status_id = 3;
				$reservations[$key]->update();
			}
			if(($value->reminderDisp == 'both' || $value->reminderDisp == 'sms') && $value->telephone != ''){

				switch ($value->reminderType) {
					case 'now':
					case '24h':
						$text = 'Su reserva para el '. $date_start .' ha sido cancelada';
						break;
					case 'c24':
						$text = 'Recuerde: dispone de 30 minutos para confirmar su reserva del ' . $date_start . ' '. $value->schedule->name . ' clickando en '.$confirmLink.$value->reference_number;
						break;
					default:
						$text = 'Recuerde: debe confirmar su reserva del ' . $date_start . ' '. $value->schedule->name . ' desde la web o clickando en '.$confirmLink.$value->reference_number;
						break;
				}

				$resultSMS = $this->sendSMS($value->telephone, $text);
			}

			if ($value->reminderDisp == 'both' || $value->reminderDisp == 'email') {

				switch ($value->reminderType) {
					case 'now':
					case '24h':
						$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. '.$value->first_name.' '. $value->last_name .',<br>Skipper Sailing Club le notifica que su reserva
                                                correspondiente a:<br><b>Fecha inicio</b>: '.$date_start.' con horario de '.utf8_encode($value->schedule->name).'<br><b>Fecha fin</b>: '.$date_start->format('d-m-Y').' <br><br>Para su barco asignado:<br><b>Barco</b>: '.$value->boat->name.'<br><br>
                                                ha sido CANCELADA.
                                                <br><br>Atentamente,
                                                Skipper Sailing Clu
                                                </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
                                                    TEST 2 24H sendReminders
                                                </td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </td>
                                    <td width="25"></td>
                                </tr>
                                <tr></tr>
                              </tbody>
                            </table>';
						break;
					default:
						$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. '.$value->first_name.' '. $value->last_name .',<br>Skipper Sailing Club le recuerda que su reserva
                                                  correspondiente a:<br><b>Fecha inicio</b>: '.$date_start.' con horario de '.utf8_encode($value->schedule->name).'<br><b>Fecha fin</b>: '.$date_start.'<br><b>Salidas consumidas</b>: <br><br>Para su barco asignado:<br><b>Barco</b>: '.$value->boat->name.'<br><br>Rogamos
                                                  CONFIRME su(s) reserva(s) clickando <a href="http://skipper.komunica.es/public/api/confirmReservation?number='.$value->reference_number.'" target="_blank">aquí</a>.
                                                  <br>Si
                                                  confirma esta reserva, se le descontarán las salidas correspondientes.<br>Si desea
                                                  CANCELARLA(S), haga click <a href="http://skipper.komunica.es/canRes.php?number='.$value->reference_number.'" target="_blank">aquí</a><br>
                                                  <br>Si no confirma su reserva en un plazo de 24 horas, su reserva será cancelada.<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
                                                  TEST 2 Default sendReminders
                                              </td>
                                          </tr>
                                        </tbody>
                                      </table>
                                    </td>
                                  <td width="25"></td>
                                </tr>
                                <tr></tr>
                              </tbody>
                            </table>';
						break;
				}

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

			}

			$reminder = Reminder::find($value->reminder_id);
			$reminder->sended = 1;
			$reminder->update();
		}

		$statusCode = 200;
		$response = ["result"=> true, 'data'=> $reservations, 'message'=>'sendReminders', 'sms' => $resultSMS, 'text' => $text, 'email' => $email ];
		return response()->json($response, $statusCode);
	}

	public function checkSend(){

		$now = Carbon::now();

		$confirmLink = 'http://skipper.komunica.es/public/api/confirmReservation?number=';

		$resultSMS = '';

		$resultEmail = '';

		$diference = 0;

		$text = '';

		$email = '';

		$text_email = '';

		$hours = '';

		$notification = '';

		$HasOne = false;

		$email_subject = 'Recordatorio reserva Skipper Sailing Club';

		$reservations = Reservations::select('reservations.*')
			->with('boat')
			->with('schedule')
			->with('user')
			->where('status_id', '=', 2)
			->whereDate('reservations.date_start', '>=', $now->format('Y-m-d'))
			->get();

		foreach ($reservations as $key => $value) {
			$hours = '';
			$resultSMS = '';
			$resultEmail = '';
			$email_subject = '';
			$text_email = '';

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

			$diference = $now->diffInHours($date_start, false);


			$created_at = Carbon::createFromTimeStamp(strtotime($value->created_at) );

			$diference_created_at = $created_at->diffInMinutes($now, false);
			$minute_difference = $now->diffInMinutes($date_start, false);


			$text = 'Recuerde: debe confirmar su reserva del ' . $date_start->format('d-m-Y') . ' ' . $value->schedule->name . ' desde la web o clickando en '.$confirmLink.$value->reference_number;

			$discount_credit_email = 'confirma esta reserva, se le descontarán las salidas correspondientes.';

			$notification = new Notifications();

			$booking24 = Bookings24h::where('reservation_id', '=', $value->id)->get();
			$existing_notification = Notifications::where('reservation_id', '=', $value->id)->get();
			$canceled = false;

			if ($diference > 72 && $diference <= 96) {
				$hours = '72h';
				$email_subject = 'Recordatorio reserva 72h Skipper Sailing Club';
				$notification['72h'] = 1;
			}elseif($diference > 48 && $diference <= 72){
				$hours = '48h';
				$email_subject = 'Recordatorio reserva 48h Skipper Sailing Club';
				$notification['48h'] = 1;
			}elseif($diference > 24 && $diference <= 48 && $booking24->isEmpty()){
				$hours = '24h';
				$email_subject = 'Recordatorio reserva 24h Skipper Sailing Club';
				$notification['24h'] = 1;
			}elseif($diference <= 24 && !$booking24->isEmpty()){
				if ($existing_notification->isEmpty()) {
					$hours = '30min';
					$email_subject = 'Recordatorio reserva 30min Skipper Sailing Club';
					$notification['24h'] = 2;
					$discount_credit_email = 'confirma esta reserva, no se le descontarán las salidas correspondientes.';
				} elseif ($existing_notification[0]['24h'] == 2) {
					$sended = Carbon::createFromTimeStamp(strtotime( $existing_notification[0]->sended));
					$minute_difference = $sended->diffInMinutes($now, false);
					if ($minute_difference > 30) {
						$canceled = true;
					}

				}

			} elseif($diference <= 24 && $booking24->isEmpty()) {
				$canceled = true;
			}
			if (!$canceled && $hours != '72h') {
				$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. '.$value->first_name.' '. $value->last_name .',<br>Skipper Sailing Club le recuerda que dispone de '.$hours.' para confirmar su reserva
                                    correspondiente a:<br><b>Fecha inicio</b>: '.$date_start->format('d-m-Y').' con horario de '.utf8_encode($value->schedule->name).'<br><b>Fecha fin</b>: '.$date_start.'<br><br>Para su barco asignado:<br><b>Barco</b>: '.$value->boat->name.'<br><br>Rogamos
                                    CONFIRME su(s) reserva(s) clickando <a href="http://skipper.komunica.es/public/api/confirmReservation?number='.$value->reference_number.'" target="_blank">aquí</a>.
                                    <br>Si
                                    '.$discount_credit_email.'<br>Si desea
                                    CANCELARLA(S), haga click <a href="http://skipper.komunica.es/public/api/cancelReservation?number='.$value->reference_number.'" target="_blank">aqui</a><br>
                                    <br>Si no confirma su reserva en un plazo de '.$hours.', su reserva será cancelada.<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>';
			} else if (!$canceled && $hours = '72h') {
				$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. '.$value->first_name.' '. $value->last_name .',<br>Skipper Sailing Club le recuerda que faltan '.$hours.' para su reserva
                                    correspondiente a:<br><b>Fecha inicio</b>: '.$date_start->format('d-m-Y').' con horario de '.utf8_encode($value->schedule->name).'<br><b>Fecha fin</b>: '.$date_start.'<br><br>Para su barco asignado:<br><b>Barco</b>: '.$value->boat->name.'<br><br>Podrá confirmar su reserva en un plazo entre 72 y 24 horas antes del inicio de la misma. 
                                        <br> Se le enviara un email con los detalles para poder confirmarla.
                                    <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>';
				$text = 'Recuerde: debe confirmar su reserva del ' . $date_start->format('d-m-Y') . ' ' . $value->schedule->name . ' Podrá confirmar su reserva en un plazo entre 72 y 24 horas antes del inicio de la misma';

			} else {
				$hours = '0h';
				$notification['24h'] = 9;
				$text = 'Su reserva del ' . $date_start->format('d-m-Y') . ' ' . $value->schedule->name .'Ha sido cancelada';
				$email_subject = 'Su reserva ha sido cancelada';
				$reservations[$key]->status_id = 3;
				$reservations[$key]->update();
				$this->checkWaitingReservationCron($value, 1);
				$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. '.$value->first_name.' '. $value->last_name .',<br>Skipper Sailing Club le notifica que su reserva
                                                correspondiente a:<br><b>Fecha inicio</b>: '.$date_start->format('d-m-Y').' con horario de '.utf8_encode($value->schedule->name).'<br><b>Fecha fin</b>: '.$date_start.' <br><br>Para su barco asignado:<br><b>Barco</b>: '.$value->boat->name.'<br><br>
                                                ha sido CANCELADA.
                                                <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>';
			}


			$HasOne = $this->checkIfThereIsANotification($value->id, $hours);

			if( $value->user->sendsms > 0 && $value->telephone != '' && $HasOne && $hours != ''){
				$resultSMS = 'ENTER SMS';
				$resultSMS = $this->sendSMS($value->telephone, $text);
			}

			if ($value->user->sendemail > 0 && $value->email != '' && $HasOne && $hours != '') {
				$resultEmail = 'ENTER EMAIL';
				$mailin3 = new MailinCustome('juan.garcia.mir@gmail.com', 'DnMLSq8aGA1czXOm');
				$mailin3->addTo($value->email, $value->first_name)->
				setFrom('bookings@skippersailingclub.com', 'Skipper')->
				setReplyTo('bookings@skippersailingclub.com','Skipper')->
				setSubject($email_subject)->
				setHtml($text_email);
				$resultEmail = $mailin3->send();
			}

			$notification->description = $text_email;
			$notification->phone = $value->telephone;
			$notification->result = $resultSMS;
			$notification->resultEmail = $resultEmail;
			$notification->reservation_id = $value->id;

			if($HasOne && $hours != ''){
				$notification->save();
			}
		}

		$statusCode = 200;
		$response = [
			"result"=> true,
			'reservations'=> $reservations,
			'message'=>'sendReminders',
			'notification' => $notification,
			'now'=> $now,
			'HasOne'=> $HasOne,
			'resultEmail' => $resultEmail,
			'resultSMS' => $resultSMS,
			'hours' => $hours,
			'booking24' => $booking24
		];

		return response()->json($response, $statusCode);
	}

	public function checkWaitingReservationCron($reservation, $is_24){

		$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();
			if ($is_24) {
				DB::table('bookings24h')->insert(['reservation_id' => $reservationInLine->id]);
			}
			$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();

		}
	}
}
