<?php

	require_once 'class.db.php';

	include_once 'Mailin.php';

	require_once __DIR__ . '/esendex/autoload.php';

	try{

		DataBase::getInstancia();

		// 72Horas
		$debug = '';
		$sql = 'SELECT reservations.id, reservations.first_name, reservations.last_name, DATE_FORMAT(reservations.date_start, \'%d-%m-%Y\') as dateStart, reservations.reference_number, reservations.telephone, reservations.email, reservations.date_start, boat.name as boatName, schedules.name as scheduleName, users.sendsms, users.sendemail
			  FROM reservations INNER JOIN boat ON reservations.boat_id = boat.id
			       INNER JOIN schedules ON schedules.id = reservations.schedule_id
                               INNER JOIN users ON users.id = reservations.user_id
			 WHERE (to_seconds(date_start) - to_seconds(CURDATE()) BETWEEN 172801 AND 259200)
                           AND reservations.id NOT IN (SELECT reservation_id FROM notifications WHERE 72h = 1 and sended > DATE_SUB(CURDATE(), INTERVAL 1 DAY))
			   AND reservations.status_id = 2 AND reservations.date_start > CURDATE()';

		$resultados = DataBase::execute_query($sql, 'S');
		echo('<br />');
		print_r($resultados);
		echo('<br />');
		
		if (count($resultados) > 0) {
    	foreach ($resultados as $r) {

				$result = '';
				$resultEmail = '';

				if ($r['telephone'] != '' && $r['sendsms'] > 0){

					$confirmLink = 'http://skipper.komunica.es/conRes.php?number='.$r['reference_number'];

					$texto = 'Recuerde: debe confirmar su reserva del ' . $r['dateStart'] . ' ' . $r['scheduleName'] . ' desde la web o clickando en '.$confirmLink;

					$message = new \Esendex\Model\DispatchMessage(
                        "Skipper", $r['telephone'], $texto,
                        \Esendex\Model\Message::SmsType );

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

                    $debug .= $response->id();
        			$result = $response->id();
				}

        if ( $r['email'] != '' && $r['sendemail'] > 0 ){

              $texto = '<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. '.$r['first_name'].' '. $r['last_name'] .',<br>Skipper Sailing Club le recuerda que su reserva
                                              correspondiente a:<br><b>Fecha inicio</b>: '.$r['dateStart'].' con horario de '.utf8_encode($r['scheduleName']).'<br><b>Fecha fin</b>: '.$r['dateStart'].'<br><b>Salidas consumidas</b>: <br><br>Para su barco asignado:<br><b>Barco</b>: '.$r['boatName'].'<br><br>Rogamos
                                              CONFIRME su(s) reserva(s) clickando <a href="http://skipper.komunica.es/conRes.php?number='.$r['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='.$r['reference_number'].'" target="_blank">aquí</a><br>
                                              <br>Si no confirma su reserva en un plazo de 72 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
                                          </td>
                                      </tr>
                                      </tbody>
                                  </table>
                              </td>
                              <td width="25"></td>
                          </tr>
                          <tr></tr>
                          </tbody>
                      </table>';

                  $mailin = new Mailin('juan.garcia.mir@gmail.com', 'DnMLSq8aGA1czXOm');
                  $mailin->
                  addTo($r['email'], $r['first_name'])->
                  setFrom('bookings@skippersailingclub.com', 'Skipper')->
                  setReplyTo('juan.garcia.mir@gmail.com','Juan Antonio García')->
                  setSubject('Recordatorio reserva 72h Skipper Sailing Club')->
                  setHtml($texto);
                  $resultEmail = $mailin->send();

        }

        $sql = 'INSERT INTO notifications ( description, phone, result, resultEmail, reservation_id, 72h) VALUES ( \''.$texto.'\', \''.$r['telephone'].'\',\''.$result.'\', \''.$resultEmail.'\' ,'.$r['id'].' , 1 )';
        DataBase::execute_query($sql, 'S');
			}
    }



		// 48Horas

		$sql = 'SELECT reservations.id, reservations.first_name, reservations.last_name, DATE_FORMAT(reservations.date_start, \'%d-%m-%Y\') as dateStart, reservations.reference_number, reservations.telephone, reservations.email, reservations.date_start, boat.name as boatName, schedules.name as scheduleName, users.sendsms, users.sendemail
					  FROM reservations INNER JOIN boat ON reservations.boat_id = boat.id
					       INNER JOIN schedules ON schedules.id = reservations.schedule_id
				               INNER JOIN users ON users.id = reservations.user_id
					 WHERE (to_seconds(date_start) - to_seconds(CURDATE()) BETWEEN 86401 AND 172800)
 					   AND reservations.id NOT IN (SELECT reservation_id FROM notifications WHERE 48h = 1 and sended > DATE_SUB(CURDATE(), INTERVAL 1 DAY))
					   AND reservations.status_id = 2 AND reservations.date_start > CURDATE()';

		$resultados = DataBase::execute_query($sql, 'S');

		if (count($resultados) > 0) {
    	foreach ($resultados as $r) {

				$result = '';
				$resultEmail = '';

				if ($r['telephone'] != '' && $r['sendsms'] > 0){

					$confirmLink = 'http://skipper.komunica.es/conRes.php?number='.$r['reference_number'];

					$texto = 'Recuerde: debe confirmar su reserva del '. $r['dateStart'] . ' ' . $r['scheduleName'] . ' desde la web o clickando en '.$confirmLink;

        			$message = new \Esendex\Model\DispatchMessage(
                        "Skipper", $r['telephone'], $texto,
                        \Esendex\Model\Message::SmsType );

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

                    $debug .= print_r($response,true);
        			$result = $response->id();
				}

        if ( $r['email'] != '' && $r['sendemail'] > 0 ){

              $texto = '<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. '.$r['first_name'].' '. $r['last_name'] .',<br>Skipper Sailing Club le recuerda que su reserva
                                              correspondiente a:<br><b>Fecha inicio</b>: '.$r['dateStart'].' con horario de '.utf8_encode($r['scheduleName']).'<br><b>Fecha fin</b>: '.$r['dateStart'].'<br><b>Salidas consumidas</b>: <br><br>Para su barco asignado:<br><b>Barco</b>: '.$r['boatName'].'<br><br>Rogamos
                                              CONFIRME su(s) reserva(s) clickando <a href="http://skipper.komunica.es/conRes.php?number='.$r['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='.$r['reference_number'].'" target="_blank">aquí</a><br>
                                              <br>Si no confirma su reserva en un plazo de 48 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
                                          </td>
                                      </tr>
                                      </tbody>
                                  </table>
                              </td>
                              <td width="25"></td>
                          </tr>
                          <tr></tr>
                          </tbody>
                      </table>';

              $mailin2 = new Mailin('juan.garcia.mir@gmail.com', 'DnMLSq8aGA1czXOm');
              $mailin2->
              addTo($r['email'], $r['first_name'])->
              setFrom('bookings@skippersailingclub.com', 'Skipper')->
              setReplyTo('juan.garcia.mir@gmail.com','Juan Antonio García')->
              setSubject('Recordatorio reserva 48h Skipper Sailing Club')->
              setHtml($texto);
              $resultEmail = $mailin2->send();
          }

			    $sql = 'INSERT INTO notifications ( description, phone, result, resultEmail, reservation_id, 48h) VALUES ( \''.$texto.'\', \''.$r['telephone'].'\',\''.$result.'\', \''.$resultEmail.'\' ,'.$r['id'].' , 1 )';
          DataBase::execute_query($sql, 'S');

       }
    	}




        // 24Horas - Reserva de último momento

		$sql = 'SELECT reservations.id, reservations.first_name, reservations.last_name, DATE_FORMAT(reservations.date_start, \'%d-%m-%Y\') as dateStart, reservations.reference_number, reservations.telephone, reservations.email, reservations.date_start, boat.name as boatName, schedules.name as scheduleName, users.sendsms, users.sendemail
					  FROM reservations INNER JOIN boat ON reservations.boat_id = boat.id
					       INNER JOIN schedules ON schedules.id = reservations.schedule_id
				               INNER JOIN users ON users.id = reservations.user_id
					 WHERE (to_seconds(date_start) - to_seconds(CURDATE()) BETWEEN 0 AND 86400) AND (to_seconds(NOW()) - to_seconds(reservations.created_at) BETWEEN 0 AND 86400)
				           AND reservations.id NOT IN (SELECT reservation_id FROM notifications WHERE 24h = 1 and sended > DATE_SUB(CURDATE(), INTERVAL 1 DAY))
					   AND reservations.status_id = 2 AND reservations.date_start >= CURDATE()';

		$resultados = DataBase::execute_query($sql, 'S');

		if (count($resultados) > 0) {
    	foreach ($resultados as $r) {

					$result = '';
					$resultEmail = '';

					if ($r['telephone'] != '' && $r['sendsms'] > 0){

						$confirmLink = 'http://skipper.komunica.es/conRes.php?number='.$r['reference_number'];

						$texto = 'Recuerde: debe confirmar su reserva del ' . $r['dateStart'] . ' '. $r['scheduleName'] . ' desde la web o clickando en '.$confirmLink;

		        		$message = new \Esendex\Model\DispatchMessage(
		                      "Skipper", $r['telephone'], $texto,
		                      \Esendex\Model\Message::SmsType );

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

		                  $debug .= print_r($response,true);
		      			$result = $response->id();
					}

		      if ( $r['email'] != '' && $r['sendemail'] > 0 ){

		            $texto = '<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. '.$r['first_name'].' '. $r['last_name'] .',<br>Skipper Sailing Club le recuerda que su reserva
		                                            correspondiente a:<br><b>Fecha inicio</b>: '.$r['dateStart'].' con horario de '.utf8_encode($r['scheduleName']).'<br><b>Fecha fin</b>: '.$r['dateStart'].'<br><b>Salidas consumidas</b>: <br><br>Para su barco asignado:<br><b>Barco</b>: '.$r['boatName'].'<br><br>Rogamos
		                                            CONFIRME su(s) reserva(s) clickando <a href="http://skipper.komunica.es/conRes.php?number='.$r['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='.$r['reference_number'].'" target="_blank">aquí</a><br>
		                                            <br>Si no confirma su reserva en un plazo de 30 minutos, 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>';

		            $mailin3 = new Mailin('juan.garcia.mir@gmail.com', 'DnMLSq8aGA1czXOm');
		            $mailin3->
		            addTo($r['email'], $r['first_name'])->
		            setFrom('bookings@skippersailingclub.com', 'Skipper')->
		            setReplyTo('juan.garcia.mir@gmail.com','Juan Antonio García')->
		            setSubject('Recordatorio reserva 30min Skipper Sailing Club')->
		            setHtml($texto);
		            $resultEmail = $mailin3->send();
		        }

			    $sql = 'INSERT INTO notifications ( description, phone, result, resultEmail, reservation_id, 24h) VALUES ( \''.$texto.'\', \''.$r['telephone'].'\',\''.$result.'\', \''.$resultEmail.'\' ,'.$r['id'].' , 1 )';
			    DataBase::execute_query($sql, 'S');

        }
      }


	        // Si pasan 30 minutos desde la reserva de 24h, se cancela

	        $sql = 'SELECT reservations.id, reservations.first_name, reservations.last_name, DATE_FORMAT(reservations.date_start, \'%d-%m-%Y\') as dateStart, reservations.reference_number, reservations.telephone, reservations.email, reservations.date_start, boat.name as boatName, schedules.name as scheduleName, users.sendsms, users.sendemail
	                  FROM reservations INNER JOIN boat ON reservations.boat_id = boat.id
					       INNER JOIN schedules ON schedules.id = reservations.schedule_id
				               INNER JOIN users ON users.id = reservations.user_id
	                 WHERE reservations.id IN (SELECT reservation_id FROM `bookings24h` WHERE created_at < DATE_ADD(NOW(), INTERVAL -30 MINUTE))';

	        $resultados = DataBase::execute_query($sql, 'S');

	        if (count($resultados) > 0) {
                foreach ($resultados as $r) {

                    $result = '';
        			$resultEmail = '';

        			if ($r['id'] > 0){
        			    $sql = 'UPDATE reservations SET status_id = 3 WHERE id = '.$r['id'];
        			    DataBase::execute_query($sql, 'S');

									//HERE IS A ERROR
        			    $sql = 'DELETE FROM bookings24h WHERE reservation_id = '.$r['id'];
        			    //DataBase::execute_query($sql, 'S');
        			}

        			if ($r['telephone'] != '' && $r['sendsms'] > 0){

    			    	$texto = 'Su reserva para el '. $r['date_start'] .' ha sido cancelada';

        			    $message = new \Esendex\Model\DispatchMessage(
                            "Skipper", $r['telephone'], $texto,
                            \Esendex\Model\Message::SmsType );

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

                        $debug .= print_r($response,true);
            			$result = $response->id();
        			}


        			if ( $r['email'] != '' && $r['sendemail'] > 0 ){

                    $texto = '<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. '.$r['first_name'].' '. $r['last_name'] .',<br>Skipper Sailing Club ha cancelado su reserva
                                            correspondiente a:<br><b>Fecha inicio</b>: '.$r['dateStart'].' con horario de '.utf8_encode($r['scheduleName']).'<br><b>Fecha fin</b>: '.$r['dateStart'].'<br><b>Salidas consumidas</b>: <br><br>Para su barco asignado:<br><b>Barco</b>: '.$r['boatName'].'<br><br>El motivo de la cancelación es debido a que no hemos recibido ninguna confirmación entre los proximos 30min desde que se hizo la pre-reserva.
                                        </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>';

                        $mailin15 = new Mailin('juan.garcia.mir@gmail.com', 'DnMLSq8aGA1czXOm');
                            $mailin15->addTo($r['email'], $r['first_name'])->
                            setFrom('bookings@skippersailingclub.com', 'Skipper')->
                            setReplyTo('juan.garcia.mir@gmail.com','Juan Antonio García')->
                            setSubject('Recordatorio reserva 24h Skipper Sailing Club')->
                            setHtml($texto);
                            $resultEmail = $mailin15->send();
                    }

                }
	        }


		    // 24Horas ( NO de último momento)

    		$sql = 'SELECT reservations.id, reservations.first_name, reservations.last_name, DATE_FORMAT(reservations.date_start, \'%d-%m-%Y\') as dateStart, reservations.reference_number, reservations.telephone, reservations.email, reservations.date_start, boat.name as boatName, schedules.name as scheduleName, users.sendsms, users.sendemail
    					  FROM reservations INNER JOIN boat ON reservations.boat_id = boat.id
    					       INNER JOIN schedules ON schedules.id = reservations.schedule_id
    				               INNER JOIN users ON users.id = reservations.user_id
    					 WHERE (to_seconds(date_start) - to_seconds(CURDATE()) BETWEEN 0 AND 86400)
    					 AND (to_seconds(NOW()) - to_seconds(reservations.created_at) > 1800)
    				           AND reservations.id NOT IN (SELECT reservation_id FROM notifications WHERE 24h = 1 and sended > DATE_SUB(CURDATE(), INTERVAL 1 DAY))
    					   AND reservations.status_id = 2 AND reservations.date_start >= CURDATE()';


	        $resultados = DataBase::execute_query($sql, 'S');

		    if (count($resultados) > 0) {
                foreach ($resultados as $r) {

        			$result = '';
        			$resultEmail = '';

        			if ($r['id'] > 0){
        			    $sql = 'UPDATE reservations SET status_id = 3 WHERE id = '.$r['id'];
        			    DataBase::execute_query($sql, 'S');
        			}

        			if ($r['telephone'] != '' && $r['sendsms'] > 0){

        			    $texto = 'Su reserva para el '. $r['date_start'] .' ha sido cancelada';

            			$message = new \Esendex\Model\DispatchMessage(
                                "Skipper", $r['telephone'], $texto,
                                \Esendex\Model\Message::SmsType );

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

                            $debug .= print_r($response,true);
                			$result = $response->id();

        			}


        			if ( $r['email'] != '' && $r['sendemail'] > 0 ){

                        $texto = '<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. '.$r['first_name'].' '. $r['last_name'] .',<br>Skipper Sailing Club ha cancelado su reserva
                                                correspondiente a:<br><b>Fecha inicio</b>: '.$r['dateStart'].' con horario de '.utf8_encode($r['scheduleName']).'<br><b>Fecha fin</b>: '.$r['dateStart'].'<br><b>Salidas consumidas</b>: <br><br>Para su barco asignado:<br><b>Barco</b>: '.$r['boatName'].'<br><br>El motivo de la cancelación es debido a que no hemos recibido ninguna confirmación entre las 72h y las 24h. antes de la fecha de la reserva.
                                            </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>';

                        $mailin4 = new Mailin('juan.garcia.mir@gmail.com', 'DnMLSq8aGA1czXOm');
                            $mailin4->
                            addTo($r['email'], $r['first_name'])->
                            setFrom('bookings@skippersailingclub.com', 'Skipper')->
                            setReplyTo('juan.garcia.mir@gmail.com','Juan Antonio García')->
                            setSubject('Recordatorio reserva 24h Skipper Sailing Club')->
                            setHtml($texto);
                            $resultEmail = $mailin4->send();
                    }

    			    $sql = 'INSERT INTO notifications ( description, phone, result, resultEmail, reservation_id, 24h) VALUES ( \''.$texto.'\', \''.$r['telephone'].'\',\''.$result.'\', \''.$resultEmail.'\' ,'.$r['id'].' , 1 )';
    				DataBase::execute_query($sql, 'S');

                }
            }


            $sql = 'UPDATE reservations SET status_id = 3 WHERE status_id NOT IN (1,3) AND (to_seconds(date_start) - to_seconds(CURDATE())) < 0';
            DataBase::execute_query($sql, 'S');


            /* ---------------------- INCIDENCE SEND ------------------------ */

            	$sql = 'SELECT * FROM incidences WHERE sended = 0';

		        $resultados = DataBase::execute_query($sql, 'S');

		        if (count($resultados) > 0) {
            	foreach ($resultados as $res) {

	              $texto = '<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>Nueva Incidencia: '.$res['comments'].'</td>
	                              </tr>
	                              <tr>
	                                  <td height="10"></td>
	                              </tr>
	                              </tbody>
	                          </table>
	                      </td>
	                      <td width="25"></td>
	                  </tr>
	                  <tr></tr>
	                </tbody>
	              </table>';

                $mailin5 = new Mailin('juan.garcia.mir@gmail.com', 'DnMLSq8aGA1czXOm');
                    $mailin5->addTo('juanantonio@embat.es', 'Admin')->
                    setFrom('bookings@skippersailingclub.com', 'Skipper')->
                    setSubject('Nueva incidencia')->
                    setHtml($texto);
                    $resultEmail = $mailin5->send();

                $sql = 'UPDATE incidences SET sended = 1 WHERE id = '.$res['id'];
                DataBase::execute_query($sql, 'S');
              }
		        }

	}catch(Exception $e){
	  echo $e->getMessage();
	  echo $e->getTraceAsString();
  }


?>
