<?php
require_once(dirname(__FILE__) . '/../customConfig/Constants.php');

class ServiceSegmentations {
	private $token;
	private $controller;

	function __construct() {
		$this->token = 'HtDFjQYeyfFb9e27n9URgFw27b9en9URg11Fw664ey11664ey11WJ9P27aGLOKmFh';
		$this->controller = new Controller;
	}

	public function startTestSegmentations() {
		try {
			// Ejecutar el servicio de segmentaciones programadas
			$response = $this->startService();

			return $response;
		} catch(Exception $e) {
			//Gestión de excepciones
			$errorFile = dirname(__FILE__) . '/runningSegmentationsError.txt';
			$date = date('Y-m-d H:i:s');
			$exceptionString =	' EXCEPTION OCURRED: ' . $e->getMessage() . "\r\n" .
								'	-Exception Code: ' . $e->getCode() . "\r\n" .
								'	-Exception Line: ' . $e->getLine() . "\r\n" .
								'	-Exception Trace: ' . "\r\n" . $e->getTraceAsString() . "\r\n";
			//escribir la excepción en el errorfile
			file_put_contents($errorFile, $date . $exceptionString . '---------------------------------' . "\r\n", FILE_APPEND);
			//lanzar un log en el server para registrarlo
			$this->controller->setCMBPLOG($this->token, 'SERVICE_SEGMENTATIONS_EXCEPTION', 'service segmentations exception', $exceptionString, '');
		}
	}

	public function startService() {
		try {
			// Llamar a las ejecuciones de schedule_segmentation
			$schedule_segmentation = $this->schedule_segmentation();

			return $schedule_segmentation;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			//$this->ErrorToFile('serviceSegmentation.txt', $error);
			return $error;
		}
	}

	// Servicio de segmentaciones programadas
	public function schedule_segmentation() {
		try {
			$returnScheduleSegmentation = 'OK';
			$schedule_segmentation = $this->getCMBPNotificationsServiceScheduleSegmentations($this->token);

			if($schedule_segmentation->status == 'OK' && count($schedule_segmentation->result) > 0) {
				foreach($schedule_segmentation->result as $result) {
					$unitTime = $result->UnidadDeTiempo;
					$timeEjecution = $result->TiempoEntreEjecuciones;

					// Valores de las segmentaciones a comprobar
					$segmentations = $this->getCMBPNotificationsServiceScheduleSegmentationsTimer($unitTime, $timeEjecution);

					if($segmentations->status == 'OK' && count($segmentations->result) > 0) {
						foreach($segmentations->result as $segmentation) {
							// Comprobación de ciclo
							if(isset($segmentation->UltimaEjecucion) && $segmentation->UltimaEjecucion != '') {
								date_default_timezone_set(date_default_timezone_get());
								$dateNow = strtotime(date('d-m-Y H:i:00', time()));
								$dateLast = $segmentation->UltimaEjecucion;

								// Dividir en fecha y hora
								$dateLastArray = explode(' ', $dateLast);

								// Fecha
								$dateArray = explode('-', $dateLastArray[0]);
								$dateLast = $dateArray[2] . '-' . $dateArray[1] . '-' . $dateArray[0];

								// Dividir en hora, minutos y segundos
								$dateLastTimeArray = explode(':', $dateLastArray[1]);

								// Crear la fecha/hora de la última ejecución pasando los segundos a 00
								$dateLastSeg = $dateLast . ' ' . $dateLastTimeArray[0] . ':' . $dateLastTimeArray[1] . ':00';

								$period = $segmentation->TiempoEntreEjecuciones;
								$interval = $segmentation->UnidadDeTiempo;
								$tInter = '';

								switch($interval) {
									case 'minutos':
										$tInter = ' minute';
										break;
									case 'horas':
										$tInter = ' hour';
										break;
									case 'días':
										$tInter = ' days';
										break;
								}

								$dateInterval = strtotime('+' . $period . $tInter, strtotime($dateLastSeg));

								if($dateNow < $dateInterval || $segmentation->enEjecucion == '1') {
									continue;
								}
							}
							// Ejecuto las segmentaciones mediante su país
							$executeSeg = $this->executeAllSegmentationsByCountry($segmentation->country, $this->token);

							if($executeSeg->status != 'OK') {
								$returnScheduleSegmentation = 'executeAllSegmentationsByCountry KO';
							}
						}
					} else if($segmentations->status != 'OK') {
						$returnScheduleSegmentation = 'getCMBPNotificationsServiceScheduleSegmentationsTimer KO';
					}
				}
			} else if($schedule_segmentation->status != 'OK') {
				$returnScheduleSegmentation = 'getCMBPNotificationsServiceScheduleSegmentations KO';
			}
			return $returnScheduleSegmentation;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();

			return $error;
		}
	}

	// Petición de segmentaciones programadas
	public function getCMBPNotificationsServiceScheduleSegmentations($token) {
		try {
			$url = CONSTANTS::SERVERAPI . 'getCMBPNotificationsServiceScheduleSegmentations';
			$params = [
				'token' => $token
			];

			$resultPOST = $this->controller->sendCurlPOST($url, $params);

			return $resultPOST;
		} catch(\Throwable $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();

			return $error;
		}
	}

	// Ejecución de segmentaciones por tiempo / unidad
	public function getCMBPNotificationsServiceScheduleSegmentationsTimer($unitTime, $timeEjecution) {
		try {
			$url = CONSTANTS::SERVERAPI . 'getCMBPNotificationsServiceScheduleSegmentationsTimer';
			$params = [
				'token' => $this->token,
				'TiempoEntreEjecuciones' => $timeEjecution,
				'UnidadDeTiempo' => $unitTime
			];

			$resultPOST = $this->controller->sendCurlPOST($url, $params);

			return $resultPOST;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();

			return $error;
		}
	}

	// Ejecución de todas las segmentaciones por país
	public function executeAllSegmentationsByCountry($country, $token) {
		try {
			$url = CONSTANTS::SERVERAPI . 'executeAllSegmentationsByCountry';
			$params = [
				'token' => $token,
				'country' => $country
			];

			$resultPOST = $this->controller->sendCurlPOST($url, $params);

			return $resultPOST;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();

			return $error;
		}
	}

	public function ErrorToFile($file, $message) {
		try {
			$nombre_archivo = $file;

			if($archivo = fopen($nombre_archivo, 'a')) {
				fwrite($archivo, date('Y-m-d H:i:s') . "\t|| " . $message . " \n");
				fclose($archivo);
			}
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}
}