<?php

defined('BASEPATH') OR exit('No direct script access allowed');



class Appointment extends CI_Controller {



	public function __construct()

    {

        parent::__construct();

        $this->load->model('Appointment_model');

        $this->load->model('Available_model');

    }



	/**

	 * form

	 */

	public function index()
	{

		$available = Available_model::first();

		

		// $start = $available->start_date < $available->start_date_m ? 

		// 	$available->start_date : $available->start_date_m;

		

		if ($available->start_date < $available->start_date_m) {

			$start = $available->start_date;



		} elseif($available->end_date_m > date('Y-m-d', time())) {

			$start = $available->start_date_m;



		} else {

			$start = $available->start_date;

		}



		// Si la fecha del horario completo es mayor a la del matutino, se usa como referencia para 

		// el final de la fecha disponible, si no, se usa la del matutino como fecha final

		if ($available->end_date > $available->end_date_m) {

			$end = $available->end_date;



		} else {

			//$end = $available->end_date_m;
			$end = $available->end_date;

		}



		$data['start_date'] = date('Y-m-d', strtotime($start));

		$data['end_date'] 	= date('Y-m-d', strtotime($end));

		$data['today'] 	= date('Y-m-d');

		$this->load->view('appointment', $data);

	}



	/**

	 * Hours

	 */

	public function hours_get()

	{

		$get = $this->input->get(null, true);

		$request_date = $get['request_date'];

		$available = Available_model::first();

		$hours = array();

		

		// var_dump($request_date);

		if ($request_date >= $available->start_date && $request_date <= $available->end_date) {

			$hours = $this->_hours(18, $request_date);

		}

		if ($request_date >= $available->start_date_m && $request_date <= $available->end_date_m) {

			$hours = $this->_hours(13, $request_date);

		}

		// if ($request_date !== "2020-09-16") {

		// 	$hours = $this->_hours();

		// }

		

		echo json_encode($hours);

	}



	/**

	 * Get hours

	 * 

	 * @return array

	 */

	private function _hours($schedule = 18, $request_date)

	{

		$day = date('D', strtotime($request_date));
		$hours = array();

		// sabados

		if ($day == 'Sat') {



			// for de horas

			// for ($x = 9; $x <= 13; $x++) {



			// 	// for de minutos, se aumentan cada 15

			// 	for ($y = 0; $y <= 45; $y += 15) {

			// 		$minutes = $y == 0 ? '00' : $y;

			// 		$hours[] = $x . ':' . $minutes;



			// 		if (($x . ':' . $minutes) == '13:15') {

			// 			// se asignan las horas al arreglo

			// 			break;

			// 		}

			// 	}

			// }



		} elseif ($day =='Sun') {

			// si es domingo no pasa nada



		} else {
			// entre semana
			// for de horas
			for ($x = 9; $x <= $schedule; $x++) {

				// valida que empiece de 30
				$start = ($x == 8 || $x == 11) ? 30 : 0;

	

				// for de minutos, se aumentan cada 15

				for ($y = $start; $y <= 45; $y += 15) {

					// si el valor es de 0 se pone 00

					$minutes = $y == 0 ? '00' : $y;

	

					// se crea el arreglo siempre que no sean las 18:45
					// se cambia el valor de 18:45 a 19:00 para que se muestren las 18:45
					if (($x . ':' . $minutes) != '19:00') {

						// se asignan las horas al arreglo
						$hour = $x . ':' . $minutes;

						$appointment_count = Appointment_model::where('request_date', $request_date)
							->where('request_time', $hour)->count();

						// si hay menos de 4 registrados en la hora y el dia, la hora sera mostrada
						if ($request_date == "2024-08-07") {
							if ($appointment_count < 2) {	
								$hours[] = $hour;	
							}

						} else {
							if ($appointment_count < 4) {	
								$hours[] = $hour;	
							}
						}

					}

				}

				

				// si dan las 10:45 se asignan las 10 hrs

				if (($x . ':' . $minutes) == '10:45') {

					$x = 10;

				} 

				// si dan las 13:45 se asignan las 15 hrs

				elseif (($x . ':' . $minutes) == '13:45') {

					$x = 15;

				}

			}

		}

		return $hours;

	}



	/**

	 * post

	 */

	public function appointment_post()

	{

		$post = $this->input->post(null, true);

		

		$request_date = $post['request_date'];

		$request_time = $post['request_time'];

		$totalAppointment = Appointment_model::where('request_date', $request_date)->where('request_time', $request_time)->count();



		if ($totalAppointment < 4) {

			$appointment = new Appointment_model();

			$appointment->parent = $post['name'];

			$appointment->phone = $post['phone'];

			$appointment->email = $post['email'];

			$appointment->request_date = $post['request_date'];

			$appointment->request_time = $post['request_time'];

		

		if ($appointment->save()) {

			$this->session->set_flashdata('success', 'Su cita se ha registrado con exito');



			$config['mailtype'] = 'html';

			

			$this->load->library('email', $config);

			$this->email->set_newline("\r\n");

			$this->email->set_mailtype("html");



			$this->email->from('noreply@libromex.com.mx', 'Libromex');

			$this->email->to($post['email']);

			$this->email->subject('Cita de libromex');

			$this->email->message(

				'Su cita ha quedado registrada para el día ' . $post['request_date'] . 

				' a las ' .$post['request_time']

			);

			$this->email->send();



		} else {

			$this->session->set_flashdata('error', 'No se ha podido registrar la cita, favor de intentarlo de nuevo');

		 }



		} else {

			$this->session->set_flashdata('error', 'El horario seleccionado no esta disponible, por favor elija otro');

		}

		

		redirect('appointment/appointment_msg');

	}



	public function appointment_msg() 

	{

		$this->load->view('appointment_msg');

	}

}