<?php

use Luracast\Restler\RestException;

require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_log.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiinvoicehelper.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/booking/class/preorder.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/booking/class/api_booking.class.php';
require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/booking/class/bookinghistory.class.php';

class LunaTours
{

	public $db;

	public $user;

	public $apiInvoiceHelper;

	public $BookingApi;

	public $PreOrder;

	const EMAIL_TEMPLATE = 'invoiceemail';
	const GLOBAL_CONF_SEND_TO_EMAIL = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL';
	
	const GLOBAL_CONF_EMAIL_FROM = 'GLOBAL_CONF_EMAIL_FROM';
	const INVOICE_SUBJECT = 'INVOICE_SUBJECT';
	const INVOICE_DESCRIPTION = 'INVOICE_DESCRIPTION';

	public function __construct($db)
	{
		global $db, $user;
		$this->db = $db;
		$this->user = $user;
		$this->apiInvoiceHelper = new ApiInvoiceHelper;
		$this->BookingApi = new BookingApi();
		$this->PreOrder = new PreOrder($db);
	}

	public function localCheckAvailablePlacesForCheckPermission($product_id)
	{
		ApiBbusLog::LunaToursLog("localCheckAvailablePlacesForCheckPermission: {$product_id}");

		$date_from = $this->getCutOffTimeDate($product_id);
		$sql = "SELECT 
			ac.id
			FROM llx_actioncomm as ac 
			LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
			INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
			INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
			WHERE ac.code = 'AC_EVENT'
			AND ep.fk_product = {$product_id}
			AND ac.datep > '{$date_from}' 
			ORDER BY ac.datep ASC";
		$result = $this->db->query($sql);
		return $this->db->num_rows($result) > 0 ? 1 : 0;
	}

	private function getCutOffTimeDate($product_id)
	{
		$date = date("Y-m-d H:i:s");
		$sql = "SELECT cut_off_time_app FROM llx_product_extrafields WHERE fk_object = {$product_id}";
		if ($result = $this->db->query($sql)) {
			if ($this->db->num_rows($result) > 0) {
				while ($row = $this->db->fetch_object($result)) {
					$cutOffTime = $row->cut_off_time_app;
				}
				$dateTimestamp = strtotime($date);
				$date = date("Y-m-d H:i:s", $dateTimestamp + $cutOffTime * 60);
			}
		}
		return $date;
	}

	public function localavailableplaces($date_from, $date_to, $product_id)
	{
		ApiBbusLog::LunaToursLog("localAvailablePlaces");
		$array = [];
		$date = new DateTime($date_to);
		$date->modify('+1 day');
		$date_to = $date->format('Y-m-d');
		$date_from = $this->getCutOffTimeDate($product_id);
		$sql = "SELECT 
		ac.id, 
		ac.datep, 
		ace.max_num, 
		ace.participants,
		ace.buffer
		FROM llx_actioncomm as ac 
		LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
		INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
		INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
		WHERE ac.code = 'AC_EVENT'
		AND ep.fk_product = {$product_id}
		AND ac.datep > '{$date_from}' 
		AND ac.datep2 < '{$date_to} 00:00:00'
		ORDER BY ac.datep ASC";
		$result = $this->db->query($sql);
		while ($row = $this->db->fetch_object($result)) {
			$max_num = $row->max_num;
			$buffer = $row->buffer;
			$participants = $row->participants;
			$date = strtotime($row->datep);
			$element['event_id'] = $row->id;
			$element['participants'] = is_null($participants) ? 0 : (int) $participants;
			$element['max_num'] = $max_num;
			$element['buffer'] = $buffer;
			//if ($max_num > $participants) {
			//	if ($max_num + $buffer > $participants + $participant_number) {
			$array[date("Y-m-d", $date)][date("H:i", $date)] = $element;
			//	}
			//}
		}
		return $array;
	}

	function createLog($fk_event, $reservations, $product_id)
	{
		/**
		 * LOG SECTION
		 */
		ApiBbusLog::LunaToursLog("=== NEW INVOICE ===");
		ApiBbusLog::LunaToursLog("User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
		ApiBbusLog::LunaToursLog(json_encode([
			'fk_event' => $fk_event,
			'reservations' => $reservations,
			'product_id' => $product_id
		]));
	}

	function localcreatedpreorderobj($fk_event, $reservations, $product_id)
	{
		global $user;
		ApiBbusLog::LunaToursLog("localcreatedpreorderobj");

		$createdPreOrderOBJ = [];
		for ($i = 1; $i <= $reservations; $i++) {
			dol_include_once('/comm/action/class/actioncomm.class.php');
			dol_include_once('/custom/booking/class/preorder.class.php');
			$this->apiInvoiceHelper->increaseParticipant($fk_event);

			$lines = $this->apiInvoiceHelper->getProductLines($product_id);
			foreach ($lines as $line) {
				$preOrderObj = $this->PreOrder;
				$preOrderObj->ref = $this->BookingApi->generateRandomString();
				$preOrderObj->fk_event = $fk_event;
				$preOrderObj->fk_product = $product_id;
				$result = $preOrderObj->create($user);
				if ($result > 0) {
					$createdPreOrderOBJ[] = [
						'id' => $preOrderObj->id,
						'ref' => $preOrderObj->ref,
					];
				} else {
					foreach ($preOrderObj->errors as $error) {
						ApiBbusLog::LunaToursLog("Error: " . $error);
					}
					ApiBbusLog::LunaToursLog("Unsaved event: " . $fk_event);
					throw new RestException(401, 'Unsaved event: ' . $fk_event);
				}
			}
		}
		ApiBbusLog::LunaToursLog(json_encode($createdPreOrderOBJ));
		return $createdPreOrderOBJ;
	}

	public function localValidateAndSaveInvoice($invoice, $preorder, $payment, $cardPaymentLog, $company_invoice = [])
	{
		ApiBbusLog::LunaToursLog("localValidateAndSaveInvoice");

		global $user, $db, $conf;
		$server_host_curl = false;
		$createdInvoiceData = [];
		$apiInvoiceHelper = new ApiInvoiceHelper;
		$bbusApi = new BBus();
		foreach ($preorder as $rowid) {
			$params = compact('rowid');
			ApiBbusLog::LunaToursLog("localValidateAndSaveInvoice: local");
			$preorderArray = $this->BookingApi->localpreorderarray($rowid);
			$lines = $apiInvoiceHelper->getProductLinesWithoutDiscount($preorderArray->fk_product);
			$createdInvoiceArray = $bbusApi->invoice($invoice, $lines, $payment, $cardPaymentLog = '', $sendId = '', $server_host_curl, $company_invoice);
			$createdInvoiceData[] = $createdInvoiceArray;
		}
		ApiBbusLog::LunaToursLog("Visszaküld");
		$asd = json_encode($createdInvoiceData);
		ApiBbusLog::LunaToursLog("{$asd}");

		return $createdInvoiceData;
	}

	public function saveEventData($fk_event, $fk_facture = null, $fk_eventproduct = null, $ref = null, $note = '')
	{

		ApiBbusLog::appLog("saveEventData");

		dol_include_once('/custom/booking/class/bookinghistory.class.php');
		dol_include_once('/comm/action/class/actioncomm.class.php');
		$actionCommObj = new ActionComm($this->db);
		$sql = "SELECT fk_element, datep, datep2 FROM " . MAIN_DB_PREFIX . $actionCommObj->table_element . " WHERE id = {$fk_event}";
		ApiBbusLog::appLog("{$sql}");

		$result = $this->db->query($sql);
		if ($this->db->num_rows($result) > 0) {
			$row = $this->db->fetch_object($result);
			$BookingHistory = new BookingHistory($this->db);
			$BookingHistory->fk_event = $fk_event;
			$BookingHistory->fk_facture = $fk_facture;
			$BookingHistory->fk_event_detail = $row->fk_element;
			$BookingHistory->fk_eventproduct = $fk_eventproduct;
			$BookingHistory->date_start = strtotime($row->datep);
			$BookingHistory->date_end = strtotime($row->datep2);
			$BookingHistory->invoice_number = $ref;
			$BookingHistory->note = $note;
			$result = $BookingHistory->create($this->user);
			if ($result > 0) {
				ApiBbusLog::appLog("saveEventData: OK {$BookingHistory->id}");
				return $BookingHistory->id;
			} else {
				foreach ($BookingHistory->errors as $error) {
					ApiBbusLog::appLog("saveEventData: {$error}");
				}
				ApiBbusLog::appLog("saveEventData: ERROR");
				throw new RestException(401, 'Unsaved');
			}
		} else {
			throw new RestException(401, 'No Event record');
		}
	}

	public function updateBbticket($invoice, $bookingHistory)
	{
		$this->BookingApi->updateBbticket($invoice, $bookingHistory);
	}

	public function deletePreorder($preorder)
	{
		$this->BookingApi->deletePreorder($preorder);
	}

	public function emailSender($note, $createdInvoiceArray)
	{
		foreach ($createdInvoiceArray as $invoice) {
			$note_array = [];
			ApiBbusLog::LunaToursLog("Start E-mail sending");
			$note_array = json_decode($note, true);
			$emailAddress = $note_array['email'];

			$const = new GlobalConst;
			$emailFrom = $const->load(self::GLOBAL_CONF_EMAIL_FROM);
			$recipients = $emailAddress;
			//$recipients = 'szollosi.laszlo@urbanms.hu';
			if (!empty($recipients) && !empty($emailFrom)) {
				$emailTemplateHandler = new EmailTemplateHandler;
				$template = $emailTemplateHandler->load(self::EMAIL_TEMPLATE);
				$templateObject = new stdClass();
				foreach ($template as $key => $value) {
					$templateObject->$key = $value;
				}
				if ($templateObject) {
					$varsInvoice = [
						'__SUBJECT__' => $const->load(self::INVOICE_SUBJECT),
						'__DESCRIPTION__' => $const->load(self::INVOICE_DESCRIPTION),
					];
					$template = $emailTemplateHandler->prepareTemplate($templateObject, $varsInvoice);
					$attachment = [DOL_DOCUMENT_ROOT . '/documents/facture/' . $invoice['invoice']['ref'] . '/' . $invoice['invoice']['ref'] . '.pdf'];
					$mimetype = ['application/pdf'];
					$mimefilename = [$invoice['invoice']['ref'] . '.pdf'];
					$mail = new CMailFile(
						$template->topic,
						$recipients,
						$emailFrom,
						$template->content,
						$attachment,
						$mimetype,
						$mimefilename,
						//null,
						//null,
						//null,
						'',
						'',
						0,
						1
					);
					// Send Email
					$mail->sendfile();
					ApiBbusLog::LunaToursLog('E-mail address: ' . $emailAddress);

					if ($mail->error) {
						ApiBbusLog::LunaToursLog($mail->error);
						// do something...
						dol_syslog('CRON ALERT EMAIL ERROR: ' . $mail->error, LOG_ERR);
					} else {
						ApiBbusLog::LunaToursLog("E-mail sent");
					}
				}
			}
		}
	}

	public function createPermissionArray($array){
		foreach ($array as $key => $item) {
			if ($this->localCheckAvailablePlacesForCheckPermission($item->rowid)) {
				$permissionArray[$item->rowid] = $item;
			}
		}
		return $permissionArray;
	}
}
