<?php
include_once(dirname(__FILE__) . '/UtilesController.php');
require_once(dirname(__FILE__) . '/../../vendor/autoload.php');
require_once(dirname(__FILE__) . '/../customConfig/Constants.php');

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;

class PagosController {
	private $utilesController;

	function __construct() {
		$this->utilesController = new UtilesController();
	}

	// Todos los pagos por país
	public function getPagosPendientesByCountry($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country'],
			'dateinit' => $client['dateinit'],
			'datefin' => $client['datefin']
		];

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

		return $resultPOST;
	}

	// Importar pagos desde excel
	public function setPagosRealizados($client) {
		// Preparar array de pagos
		$payments = [];
		foreach($client['payments'] as $payment) {
			if($payment['user'] == '-') {
				$payment['user'] = '';
			}
			if($payment['sid'] == '-') {
				$payment['sid'] = '0';
			}
			if($payment['valor'] == '-') {
				$payment['valor'] = 0;
			}
			if($payment['user'] != '' && $payment['sid'] != '' && $payment['cobrado'] == 1) {
				$participant = $payment['user'] . '#' . $payment['sid'] . '#' . $payment['valor'] . '#' . $payment['concepto'] . '#' . $payment['stamp'] . '#' . $payment['differentValue'];
				array_push($payments, $participant);
			}
		}

		$url = CONSTANTS::SERVERAPI . 'setPagosRealizados';
		$params = [
			'token' => $client['token'],
			'idUseridSurvey' => json_encode($payments)
		];

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

		if(isset($resultPOST)) {
			$this->saveExcelPayments($client);

			// Registro de pagos exportados con comentarios enviados
			$url = CONSTANTS::SERVERAPI . 'setPagosNoExported';

			if($client['noPaymentsComments'] === '') {
				$noPaymentsComments = '[]';
			} else {
				$noPaymentsComments = json_encode(explode(',', $client['noPaymentsComments']));
			}

			$params = [
				'token' => $client['token'],
				'idUseridSurvey' => $noPaymentsComments
			];

			$resultPOSTSPNE = $this->utilesController->sendCurlPOST($url, $params);

			if($resultPOSTSPNE->status == 'KO') {
				// Registro de errores
				if(isset($resultPOSTSPNE->result)) {
					$result = $resultPOSTSPNE->result;
				} else {
					$result = 'ERROR';
				}
				$this->utilesController->setCMBPLOG($client['token'], 'SERVICE', 'setPagosNoExported', $result, '', '1');

				return $resultPOSTSPNE;
			}

			return $resultPOST;
		} else {
			$response['status'] = 'KO';
			$response['result'] = 'Error';
			return $response;
		}
	}

	// Stamps de pagos esportados a excel
	public function setPagosPendientesExportados($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'stamp' => $client['stamp']
		];

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

		return $resultPOST;
	}

	// Enviar notificación de pagos no realizados
	public function sendNoPaymentNotifications($client) {
		foreach($client['data'] as $key => $value) {
			$dataMsg['from'] = $client['from'];

			// Obtener el jid del usuario
			$usersJid = '[';
			foreach($value as $email) {
				$emailArray = explode('#', $email);
				$url = CONSTANTS::SERVERAPI . 'getUserJidByEmail';
				$params = [
					'token' => $client['token'],
					'email' => $emailArray[0]
				];

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

				if($resultPOST->status != 'OK') {
					return $resultPOST;
				}

				if(!stripos($usersJid, $resultPOST->result)) {
					$usersJid .= '"' . $resultPOST->result . '",';
				}
			}

			$usersJid = substr($usersJid, 0, -1);
			$usersJid .= ']';

			$dataMsg['emailsToSend'] = $usersJid;
			$dataMsg['message'] = $client['message'] . "\n" . $key;
			$dataMsg['idlist'] = '';

			// Envío de notificación
			$noClient = true;
			$resultPOST = $this->utilesController->postMessageMultiple($noClient, $dataMsg, $client['token']);

			if($resultPOST->status != 'OK') {
				return $resultPOST;
			} else {
				// Registro de pagos exportados con comentarios enviados
				$url = CONSTANTS::SERVERAPI . 'setPagosNoExported';
				$params = [
					'token' => $client['token'],
					'idUseridSurvey' => json_encode($value)
				];

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

				if($resultPOST->status != 'OK') {
					return $resultPOST;
				}
			}
		}

		$response = [
			'status' => 'OK',
			'result' => 'OK'
		];

		return $response;
	}

	// Detalle de pagos
	public function getDetallePagos($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'allRows' => $client['allRows'],
			'country' => $client['country'],
			'filter' => $client['filter'],
			'dateinit' => $client['dateinit'],
			'datefin' => $client['datefin'],
			'mision' => $client['idmision']
		];

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

		// Exportacion excel
		if($client['allRows'] == '1') {
			$dataRows = $resultPOST;

			$size = count($dataRows->result);
			for($i = 0; $i < $size; $i++) {
				if($dataRows->result[$i]->fechaCobro != '') {
					$fechaCobroArray = explode(' ', $dataRows->result[$i]->fechaCobro);
					$fechaCobro = explode('-', $fechaCobroArray[0]);

					if($client['dateFormat'] == 'DDMMAAAA') {
						$cobroDate = $fechaCobro[2] . '/' . $fechaCobro[1] . '/' . $fechaCobro[0];
					} else {
						$cobroDate = $fechaCobro[0] . '/' . $fechaCobro[1] . '/' . $fechaCobro[2];
					}
	
					$dataRows->result[$i]->fechaCobro = $cobroDate . ' ' . $fechaCobroArray[1];
				}

				if($dataRows->result[$i]->fechaExported != '') {
					$fechaExportedArray = explode(' ', $dataRows->result[$i]->fechaExported);
					$fechaExported = explode('-', $fechaExportedArray[0]);

					if($client['dateFormat'] == 'DDMMAAAA') {
						$exportedDate = $fechaExported[2] . '/' . $fechaExported[1] . '/' . $fechaExported[0];
					} else {
						$exportedDate = $fechaExported[0] . '/' . $fechaExported[1] . '/' . $fechaExported[2];
					}
	
					$dataRows->result[$i]->fechaExported = $exportedDate . ' ' . $fechaExportedArray[1];
				}

				if($dataRows->result[$i]->fechaProcesado != '') {
					$fechaProcesadoArray = explode(' ', $dataRows->result[$i]->fechaProcesado);
					$fechaProcesado = explode('-', $fechaProcesadoArray[0]);

					if($client['dateFormat'] == 'DDMMAAAA') {
						$procesadoDate = $fechaProcesado[2] . '/' . $fechaProcesado[1] . '/' . $fechaProcesado[0];
					} else {
						$procesadoDate = $fechaProcesado[0] . '/' . $fechaProcesado[1] . '/' . $fechaProcesado[2];
					}
	
					$dataRows->result[$i]->fechaProcesado = $procesadoDate . ' ' . $fechaProcesadoArray[1];
				}
			}

			if($dataRows->numRows != '0') {
				$cabeceras = 'userNombre';
				$cabeceras .= ',userApellidos';
				$cabeceras .= ',userApellidos2';
				$cabeceras .= ',user';
				$cabeceras .= ',isopais';
				$cabeceras .= ',sid';
				$cabeceras .= ',concepto';
				$cabeceras .= ',valor';
				$cabeceras .= ',cobrado';
				$cabeceras .= ',fechaCobro';
				$cabeceras .= ',fechaExported';
				$cabeceras .= ',fechaProcesado';

				$date = date_create();
				$stamp = date_timestamp_get($date);
				$timeStamp = $stamp * 1000;

				$generateTableExcel = new GenerateTableExcel();

				$filename = $generateTableExcel->printExcelFromResultOrderedNew($dataRows->result, $cabeceras, $timeStamp);

				if($filename == 'The folder has not been created') {
					$resultPOST = [
						'status' => 'KO',
						'result' => 'The folder has not been created'
					];
				} else {
					$filename = str_replace(CONSTANTS::PATH_EXPORT_WORD . '/', '', $filename);
					$resultPOST = [
						'status' => 'OK',
						'result' => $filename
					];
				}
			} else {
				$resultPOST = [
					'result' => 'OK'
				];
				return $resultPOST;
			}
		}

		return $resultPOST;
	}

	// Crear pago automatizado
	public function setScheduledPayment($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'Activa' => $client['Activa'],
			'country' => $client['country'],
			'TiempoEntreEjecuciones' => $client['TiempoEntreEjecuciones'],
			'UnidadDeTiempo' => $client['UnidadDeTiempo'],
			'UsuarioANotificar' => $client['UsuarioANotificar'],
			'GrupoANotificar' => $client['GrupoANotificar'],
			'ListaANotificar' => $client['ListaANotificar'],
			'Archivo' => $client['Archivo'],
			'MailTo' => $client['MailTo'],
			'Asunto' => $client['Asunto'],
			'Cuerpo' => $client['Cuerpo']
		];

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

		return $resultPOST;
	}

	// Eliminar de pago automatizado
	public function deleteScheduledPayment($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['scheduledPayments'] != '[]') {
			foreach($client['scheduledPayments'] as $scheduledPayment) {
				$params = [
					'token' => $client['token'],
					'id' => $scheduledPayment['id']
				];

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

				if($resultPOST->status != 'OK') {
					return $resultPOST;
				}
			}
		} else {
			$resultPOST = [
				'status' => 'OK'
			];
		}

		return $resultPOST;
	}

	// Actualizar pago automatizado
	public function updateScheduledPayment($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'Activa' => $client['Activa'],
			'country' => $client['country'],
			'TiempoEntreEjecuciones' => $client['TiempoEntreEjecuciones'],
			'UnidadDeTiempo' => $client['UnidadDeTiempo'],
			'UsuarioANotificar' => $client['UsuarioANotificar'],
			'GrupoANotificar' => $client['GrupoANotificar'],
			'ListaANotificar' => $client['ListaANotificar'],
			'Archivo' => $client['Archivo'],
			'MailTo' => $client['MailTo'],
			'Asunto' => $client['Asunto'],
			'Cuerpo' => $client['Cuerpo']
		];

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

		return $resultPOST;
	}

	// Validar pagos
	public function validatePagosRealizados($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['idUseridSurvey'] == '[]') {
			$resultPOST = [
				'status' => 'OK',
				'result_diff_import' => [],
				'result_prev_processed' => []
			];
		} else {
			$size = count($client['idUseridSurvey']);
			$control = 499;
			$idUseridSurveyD = [];
			$pendingValidation = [];
			$processedPayments = [];
			for($i = 0; $i < $size; $i++) {
				array_push($idUseridSurveyD, $client['idUseridSurvey'][$i]);
				if($i == $control) {
					$params = [
						'token' => $client['token'],
						'idUseridSurvey' => json_encode($idUseridSurveyD)
					];

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

					if($resultPOST->status != 'OK') {
						return $resultPOST;
					} else {
						$control += 500;
						$idUseridSurveyD = [];
						if(count($resultPOST->result_diff_import) > 0) {
							$pendingValidation = array_merge($pendingValidation, $resultPOST->result_diff_import);
						}

						if(count($resultPOST->result_prev_processed) > 0) {
							$processedPayments = array_merge($processedPayments, $resultPOST->result_prev_processed);
						}
					}
				}
			}

			if(count($idUseridSurveyD) > 0) {
				$params = [
					'token' => $client['token'],
					'idUseridSurvey' => json_encode($idUseridSurveyD)
				];

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

				if(count($resultPOST->result_diff_import) > 0) {
					$pendingValidation = array_merge($pendingValidation, $resultPOST->result_diff_import);
				}

				if(count($resultPOST->result_prev_processed) > 0) {
					$processedPayments = array_merge($processedPayments, $resultPOST->result_prev_processed);
				}
			}
		}
		$resultPOST->result_diff_import = $pendingValidation;
		$resultPOST->result_prev_processed = $processedPayments;

		return $resultPOST;
	}

	// Registrar pagos no cobrables
	public function setPagosNoCobrables($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'motivo' => $client['motivo'],
			'idUseridSurvey' => json_encode($client['idUseridSurvey'])
		];

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

		if(isset($resultPOST)) {
			return $resultPOST;
		} else {
			$response['status'] = 'KO';
			$response['result'] = 'Error';
			return $response;
		}
	}

	// Subida de archivo de pagos pendientes descargados
	public function sendExcelDataToServer($client) {
		$response = [
			'status' => 'OK',
			'result' => 'Success'
		];

		try {
			// Excel
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();

			$cabeceras = $client['dataExcelHead'];

			$col = 1;
			foreach($cabeceras as $field) {
				$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
				$col++;
			}

			// Datos
			$row = 2;
			$allData = $client['dataExcelBody'];
			foreach($allData as $data) {
				$col = 1;
				foreach($data as $value) {
					$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
					$col++;
				}
				$row++;
			}

			// Estilos encabezados
			$letra = $spreadsheet->getActiveSheet()->getHighestColumn();
			$spreadsheet->getActiveSheet()->getStyle('A1:' . $letra . '1')->applyFromArray(
				[
					'fill' => [
						'type' => Fill::FILL_SOLID,
						'color' => [
							'rgb' => 'E5E4E2'
						]
					],
					'font' => [
						'bold' => false
					]
				]
			);

			// Autoajustar celdas
			$column = 'A';
			while($column != $letra) {
				$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
				$column++;
			}

			$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);

			$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/pagos/exportar/' . $client['userMail'];

			if(!file_exists($carpeta)) {
				$createFile = $this->utilesController->createDirectory($carpeta);

				if($createFile['status'] == 'KO') {
					return $createFile;
				}
			}

			$filename = $client['stampName'] . '.xlsx';

			$writer = new Xlsx($spreadsheet);
			$writer->save($carpeta . '/' . $filename);

			$type = 'Exported Payments';
			$service = $client['userMail'];
			$event = 'Se generó y descargó un archivo de pagos pendientes. Id del archivo: ' . $client['stampName'];
			$rute = '/pagos/exportar/' . $client['userMail'] . '/' . $filename;

			$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, $rute, '1');
		} catch(Exception $e) {
			$response['status'] = 'KO';
			$response['result'] = 'Error';
		}

		return $response;
	}

	// Subida de archivo de pagos a validar importado
	public function uploadImportPaymentsNoProcessed($client) {
		$response = [
			'status' => 'OK',
			'result' => 'Success'
		];

		try {
			if(isset($_FILES['file'])) {
				// Creación de carpeta temporal de pagos
				$filepath = CONSTANTS::PATH_EXPORT_WORD . '/pagos/importar/temp/' . $client['userMail'];
				if(!file_exists($filepath)) {
					$createFile = $this->utilesController->createDirectory($filepath);

					if($createFile['status'] == 'KO') {
						return $createFile;
					}
				} else {
					$folderName = $filepath . '/*';
					$files = glob($folderName);
					foreach($files as $file) {
						if(is_file($file)) {
							unlink($file);
						}
					}
				}

				// Mover excel temporal de pagos
				if(move_uploaded_file($_FILES['file']['tmp_name'], $filepath . '/' . $client['stampName'] . '.xlsx')) {
					// Devolución de nombre del archivo temporal
					$response['result'] = $client['stampName'];
				} else {
					$response['status'] = 'KO';
					$response['result'] = 'Error';
				}
			}
		} catch(Exception $e) {
			$response['status'] = 'KO';
			$response['result'] = 'Error';
		}

		return $response;
	}

	// Guardado de archivo de pagos realizados
	public function saveExcelPayments($client) {
		$response = [
			'status' => 'OK',
			'result' => 'Success'
		];

		try {
			// Excel
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();

			$cabeceras = $client['payments'][0];

			$col = 1;
			foreach($cabeceras as $key => $value) {
				$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $key);
				$col++;
			}

			// Datos
			$row = 2;
			$allData = $client['payments'];
			foreach($allData as $data) {
				$col = 1;
				foreach($data as $value) {
					$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
					$col++;
				}
				$row++;
			}

			// Estilos encabezados
			$letra = $spreadsheet->getActiveSheet()->getHighestColumn();
			$spreadsheet->getActiveSheet()->getStyle('A1:' . $letra . '1')->applyFromArray(
				[
					'fill' => [
						'type' => Fill::FILL_SOLID,
						'color' => [
							'rgb' => 'E5E4E2'
						]
					],
					'font' => [
						'bold' => false
					]
				]
			);

			// Autoajustar celdas
			$column = 'A';
			while($column != $letra) {
				$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
				$column++;
			}

			$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);

			$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/pagos/importar/' . $client['userMail'];

			if(!file_exists($carpeta)) {
				$createFile = $this->utilesController->createDirectory($carpeta);

				if($createFile['status'] == 'KO') {
					return $createFile;
				}
			}

			$filename = $client['tempFileName'] . '_payments.xlsx';

			$writer = new Xlsx($spreadsheet);
			$writer->save($carpeta . '/' . $filename);

			$filepathS = CONSTANTS::PATH_EXPORT_WORD . '/pagos/importar/temp/' . $client['userMail'] . '/' . $client['tempFileName'] . '.xlsx';
			$filepathE = CONSTANTS::PATH_EXPORT_WORD . '/pagos/importar/' . $client['userMail'] . '/' . $client['tempFileName'] . '.xlsx';
			rename($filepathS, $filepathE);

			$type = 'Imported Payments';
			$service = $client['userMail'];
			$event = 'Se procesó un archivo de pagos pendientes. Id del archivo: ' . $client['tempFileName'] . '_payments';
			$rute = '/pagos/importar/' . $client['userMail'] . '/' . $filename . ',/pagos/importar/' . $client['userMail'] . '/' . $client['tempFileName'] . '.xlsx';

			$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, $rute, '1');
		} catch(Exception $e) {
			$response['status'] = 'KO';
			$response['result'] = 'Error';
		}

		return $response;
	}
}