<?php

require_once DOL_DOCUMENT_ROOT . '/custom/rollerstorage/class/rollerrenthistory.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/roller_handling_helper.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/rollerstorage/class/rollerhistory.class.php';


use Luracast\Restler\RestException;

trait RollerHandling
{
	use RollerHandligHelper;

	/**
	 * Get status of a roller by barcode
	 *
	 * Return an array with product information.
	 *
	 * @param  string $code	Roller QR code
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url POST RENT_checkScooterStatus
	 */

	// Kellenek még a foglalási adatok ha vanank egy tömbben. HA nincs ,akkor üres tömb.
	public function RENT_checkScooterStatus(string $code)
	{
		ApiBbusLog::ScooterRentLog("RENT_checkScooterStatus: ___START___");
		$scooterData = $this->getAllScooterDataByCode($code);
		$scooterData->isExpired = $this->RENT_isExpired($code);
		ApiBbusLog::ScooterRentLog("RENT_checkScooterStatus: ___END___");
		return $scooterData;
	}


	/**
	 * Get status of a roller by barcode and Invoice number
	 *
	 * Return an array with product information.
	 *
	 * @param  string $code	Roller QR code
	 * @param  string $invoice_number	Invoice number
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url POST RENT_checkScooterStatusAfterTicketValidation
	 */

	// Kellenek még a foglalási adatok ha vanank egy tömbben. HA nincs ,akkor üres tömb.
	public function RENT_checkScooterStatusAfterTicketValidation(string $code, $invoice_number)
	{
		ApiBbusLog::ScooterRentLog("RENT_checkScooterStatusAfterTicketValidation: ___START___");
		$scooterDataArray = [];
		$scooterData = $this->getAllScooterDataByCode($code);
		$scooterDataArray['scooter'] = $scooterData;
		$scooterDataArray['isRented'] = $this->db->num_rows($this->checkRentHistory($scooterData->rowid, $invoice_number)) > 0;
		ApiBbusLog::ScooterRentLog("RENT_checkScooterStatusAfterTicketValidation: ___END___");
		return $scooterDataArray;
	}


	/**
	 * Get available statuses of a roller
	 *
	 * Return an array with product information.
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url GET RENT_GetAvailableStatuses
	 */
	public function RENT_GetAvailableStatuses()
	{
		ApiBbusLog::ScooterRentLog("RENT_GetAvailableStatuses: ___START___");
		$statuses = [];
		$sql = "SELECT status_id FROM llx_rollerstorage_statuses WHERE status_id != 112";
		$result = $this->db->query($sql);
		if ($this->db->num_rows($result) > 0) {
			while ($row = $this->db->fetch_object($result)) {
				$statuses[] = $row->status_id;
			}
			ApiBbusLog::ScooterRentLog("RENT_GetAvailableStatuses: ___END___");
			return $statuses;
		}
		ApiBbusLog::ScooterRentLog("RENT_GetAvailableStatuses: ___END___");
		return $statuses;
	}

	/**
	 * Get all statuses of a rollers
	 *
	 * Return an array with product information.
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url GET RENT_GetAllStatuses
	 */
	public function RENT_GetAllStatuses()
	{
		ApiBbusLog::ScooterRentLog("RENT_GetAllStatuses: ___START___");
		$statuses = [];
		$sql = "SELECT status_id FROM llx_rollerstorage_statuses";
		$result = $this->db->query($sql);
		if ($this->db->num_rows($result) > 0) {
			while ($row = $this->db->fetch_object($result)) {
				$statuses[] = $row->status_id;
			}
			ApiBbusLog::ScooterRentLog("RENT_GetAllStatuses: ___END___");
			return $statuses;
		}
		ApiBbusLog::ScooterRentLog("RENT_GetAllStatuses: ___END___");
		return $statuses;
	}

	/**
	 * Set status of a scooter
	 *
	 * @param  string $statuscode
	 * @param  string $rowid
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url POST RENT_setScooterStatus
	 */
	public function RENT_setScooterStatus($statuscode, $rowid)
	{
		$statuses = $this->RENT_GetAllStatuses();
		if (!in_array($statuscode, $statuses)) {
			throw new RestException(404, 'Status Not found.');
		}
		$inventoryObjFROM = new Inventory($this->db);
		$resultFROM = $inventoryObjFROM->fetch($rowid);
		$fromStatus = $inventoryObjFROM->status;
		ApiBbusLog::ScooterRentLog("RENT_setScooterStatus: ___START___");
		$sql = "UPDATE llx_inventory SET status = {$statuscode} WHERE rowid = {$rowid}";
		$result = $this->db->query($sql);
		$inventoryObj = new Inventory($this->db);
		$resultupdated = $inventoryObj->fetch($rowid);
		$this->createHistoryRecord($inventoryObj, $fromStatus);
		ApiBbusLog::ScooterRentLog("Scooter status changed to {$inventoryObj->status}!");
		ApiBbusLog::ScooterRentLog("RENT_setScooterStatus: ___END___");
		return $inventoryObj->status;
	}

	/**
	 * Connect scooter and facture
	 *
	 * @param  string $inventory_id
	 * @param  string $ticketQRCode
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url POST RENT_ConnectFactureAndScooter
	 */
	public function RENT_ConnectFactureAndScooter($inventory_id, $ticketQRCode, $isReplaced = false)
	{
		ApiBbusLog::ScooterRentLog("RENT_ConnectFactureAndScooter: ___START___");
		$QRCodeData = explode('_', $ticketQRCode);
		if ($this->isRented($QRCodeData, $inventory_id)) {
			ApiBbusLog::ScooterRentLog("RENT_ConnectFactureAndScooter:  Already rented -> return: FALSE");
			return false;
		}
		$error = 0;
		$this->db->begin();
		$ScooterRentHistoryId = $this->CreateScooterRentHistoryRecord($inventory_id, $QRCodeData[0], $QRCodeData[1], null);
		(int)$ScooterRentHistoryId > 0 ?: $error++;
		ApiBbusLog::ScooterRentLog("RentHistoryRecord: {$ScooterRentHistoryId}");
		$this->RENT_setScooterStatus("112", $inventory_id) == '112' ?: $error++;
		$ticket_id = $this->getTicketId($QRCodeData[0], $QRCodeData[1]);
		if (!$isReplaced) {
			$sql = "SELECT * FROM llx_bbus_bbticket WHERE rowid = {$ticket_id}";
			$result = $this->db->query($sql);
			while ($row = $this->db->fetch_object($result)) {
				$this->updateScooterBbticket($row) > 0 ?: $error++;
			}
		}
		$this->checkError($error);
		$this->db->commit();
		ApiBbusLog::ScooterRentLog("RENT_ConnectFactureAndScooter: ___END___");
		return "OK";
	}

	/**
	 * Scooter isExpired check
	 *
	 * @param  string $code Scooter title code
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url POST RENT_isExpired
	 */
	public function RENT_isExpired($code)
	{
		ApiBbusLog::ScooterRentLog("RENT_isExpired: ___START___");
		$scooterData = $this->getScooterRowidByCode($code);
		$rollerrenthistoryData = $this->getRollerrenthistoryDataByInvetoryId($scooterData);
		return $this->checkExpireDate($rollerrenthistoryData->ticket_id);
	}

	/**
	 * Scooter Take back
	 *
	 * @param  string $code
	 * @param  int $roller_status
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url POST RENT_scooterTakeBack
	 */
	public function RENT_scooterTakeBack($code, $roller_status)
	{
		ApiBbusLog::ScooterRentLog("RENT_scooterTakeBack: ___START___");
		# Ezt hívjuk meg akkor is, ha csere van (státusz: 110 (In stock) / 114 (Faulty)) és akkor is ha rendes visszavételezés történik, de ebben az esetben 111-es státusszal.
		$error = 0;
		$scooterData = $this->getScooterRowidByCode($code);
		$rollerrenthistoryData = $this->getRollerrenthistoryDataByInvetoryId($scooterData);
		$this->db->begin();
		# Create RollerRentHistory Record
		$ScooterRentHistoryId = $this->CreateScooterRentHistoryRecord($scooterData, $rollerrenthistoryData->invoice_number, null, $rollerrenthistoryData->ticket_id, 0);
		(int)$ScooterRentHistoryId > 0 ?: $error++;
		# Update Rollerstatus in llx_inventory
		$this->RENT_setScooterStatus($roller_status, $scooterData)  == $roller_status ?: $error++;
		$this->checkError($error);
		$this->db->commit();
		ApiBbusLog::ScooterRentLog("RENT_scooterTakeBack: {$code} -> Rent record created: {$ScooterRentHistoryId}");
		ApiBbusLog::ScooterRentLog("RENT_scooterTakeBack: ___END___");
		return 'OK';
	}

	/**
	 * Scooter replacement
	 *
	 * @param  string $code_1				//Scooter QRcode
	 * @param  string $scooter_1_status		//1st Scooter status
	 * @param  string $code_2				//Scooter QRcode
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url POST RENT_scooterReplacement
	 */
	public function RENT_scooterReplacement($code_1, $scooter_1_status, $code_2)
	{
		$error = 0;
		ApiBbusLog::ScooterRentLog("RENT_scooterReplacement: ___START___");
		# Take the scooter back
		$scooter_1_data = $this->RENT_checkScooterStatus($code_1);
		$scooter_2_data = $this->RENT_checkScooterStatus($code_2);
		if ($scooter_1_data->status == $scooter_1_status) {
			$scooter_1_status = '110';
		}
		$this->RENT_scooterTakeBack($code_1, $scooter_1_status);
		if ($scooter_2_data->status == '110') {
			$isReplaced = true;
			$scooter_1_data = $this->RENT_checkScooterStatus($code_1);
			$invoice_number = $this->getInvoiceNumberByInvetoryId($scooter_1_data->rowid);
			$ticket_id = $this->getTicketIdByInvoiceNumberFromRollerRentHistory($invoice_number, $code_1);
			$this->db->begin();
			$ScooterRentHistoryId = $this->CreateScooterRentHistoryRecord($scooter_2_data->rowid, $invoice_number, null, $ticket_id, 1);
			(int)$ScooterRentHistoryId > 0 ?: $error++;
			ApiBbusLog::ScooterRentLog("RENT_scooterReplacement: {$code_2} -> Rent record created: {$ScooterRentHistoryId}");
			$this->RENT_setScooterStatus("112", $scooter_2_data->rowid) == '112' ?: $error++;
			if (!$isReplaced) {
				$sql = "SELECT * FROM llx_bbus_bbticket WHERE rowid = {$ticket_id}";
				$result = $this->db->query($sql);
				while ($row = $this->db->fetch_object($result)) {
					$this->updateScooterBbticket($row) > 0 ?: $error++;
				}
			}
			$this->checkError($error);
			$this->db->commit();
			ApiBbusLog::ScooterRentLog("RENT_scooterReplacement: ___END___");
			return "OK";
			//$this->RENT_ConnectFactureAndScooter($scooter_2_data->rowid, $invoice_number, $ticket_id, true);

		} else {
			return $scooter_2_data->status;
		}
		ApiBbusLog::ScooterRentLog("RENT_scooterReplacement: ___END___");
		return 'OK';
	}
}
