<?php

namespace App\ReportsData\Populate\Entity;

class SupplierInvoice extends \App\ReportsData\Populate\GeneralAbstract
{

	/**
	 * The supplier invoice rows table.
	 * @var string
	 */
	private $dbTableName_supplierInvoiceRows;

	/**
	 * Returns the table name that will store the current entity queue.
	 * @return string
	 */
	protected function getDbTableName()
	{
		global $DBTRd_supplierInvoices, $DBTRd_supplierInvoiceRows;
		$this->dbTableName_supplierInvoiceRows = $DBTRd_supplierInvoiceRows;
		return $DBTRd_supplierInvoices;
	}


	/**
	 * {@inheritDoc}
	 * @see \App\ReportsData\Populate\GeneralAbstract::getEntityFields()
	 */
	protected function getEntityFields()
	{

		// get current entity details
		$entity = \Entity\SupplierInvoice::select($this->id);

		// for non existing rows - it may be an invoice which changed its month and we need to delete it from RD table
		if (!$entity->recordExists()) {
			$this->dbExecuteDelete($this->dbTableName, 'id', $this->id);
			$this->dbExecuteDelete($this->dbTableName_supplierInvoiceRows, 'idInvoice', $this->id);
			return null;
		}

		// get default currency rate
		$defaultCurrency = \App\Config\Currencies::getInstance()->getDefaultCurrency();
		$workCurrency = \App\Config\Currencies::getInstance()->getWorkCurrency();
		$currencyRate = \App\CurrencyExchange\Rates::getInstance($entity->invoiceDate)->convert(1, $entity->currency, $defaultCurrency, null);
		$workCurrencyRate = \App\CurrencyExchange\Rates::getInstance($entity->invoiceDate)->convert(1, $workCurrency, $defaultCurrency, null);

		// populate the entity details
		$return = [
			'id'				=> $this->id,
			'deleted'			=> $entity->deleted,
			'idSupplier'		=> $entity->idSupplier,
			'idSupplierBankAccount' => $entity->idSupplierBankAccount,
			'statusOp'			=> $entity->statusOp,
			'statusFin'			=> $entity->statusFin,
			'invoiceDate'		=> $entity->invoiceDate,
			'invoiceSeries'		=> $entity->invoiceSeries,
			'invoiceNumber'		=> $entity->invoiceNumber,
			'invoiceComments'	=> $entity->invoiceComments,
			'formOfPayment'		=> $entity->formOfPayment,
			'dueDate'			=> $entity->dueDate,
			'fulfillmentDate'	=> $entity->fulfillmentDate,
			'estPayDate'		=> $entity->estPayDate,
			'invoiceValue'		=> $entity->priceValue,
			'invoiceVat'		=> $entity->vatValue,
			'invoiceTotal'		=> $entity->totalValue,
			'payedValue'		=> $entity->payedValue,
			'lastPaymentDate'	=> $entity->lastPaymentDocumentDate?:null,
			'currency'			=> $entity->currency,
			'currencyRate'		=> $currencyRate,
			'workCurrencyRate'	=> $workCurrencyRate,
			'remarks'			=> $entity->remarks,
			'processedRemarks'	=> ($entity->processedRemarks ? json_encode($entity->processedRemarks) : ''),
			'extraInfo'			=> ($entity->extraInfo ? json_encode($entity->extraInfo) : ''),
			'idUser'			=> $entity->idUser,
			'idOffice'			=> $entity->idOffice,
			'idAddUser'			=> $entity->idAddUser,
			'addTime'			=> \Engine\DateTime::createFromTimestamp($entity->addTime)->formatDatetimeIso(),
			'idUpdateUser'		=> $entity->idUpdateUser,
			'lastUpdateTime'	=> ( $entity->lastUpdateTime ? \Engine\DateTime::createFromTimestamp($entity->lastUpdateTime)->formatDatetimeIso() : null ),
			'updatesCount'		=> $entity->updatesCount,
			'blockable'			=> $entity->blockable,
			'idBlockUser'		=> $entity->idBlockUser,
			'blockTime'			=> ( $entity->blockTime ? \Engine\DateTime::createFromTimestamp($entity->blockTime)->formatDatetimeIso() : null ),
		];

		return $return;
	}


	/**
	 * Add supplier invoice rows as well.
	 * {@inheritDoc}
	 * @see \App\ReportsData\Populate\GeneralAbstract::populate()
	 */
	public function populate() :void
	{

		// insert the invoice
		parent::populate();

		// GET SUPPLIER INVOICE ROWS DETAILS //////////////////////////////////////////////////////
		$invoiceRows = \Entity\SupplierInvoice::select($this->id)->rowsList;


		// DELETE PREVIOUS INVOICE ROWS ///////////////////////////////////////////////////////////
		$this->dbExecuteDelete($this->dbTableName_supplierInvoiceRows, 'idInvoice', $this->id);


		// ADD NEW INVOICE ROWS ///////////////////////////////////////////////////////////////////
		if ($invoiceRows) {
			foreach($invoiceRows as $idRow=>$invoiceRow) {

				$invoiceRowEnt = \Entity\SupplierInvoiceRow::select($idRow);

				$fields = [
					'id'						=> $idRow,
					'idInvoice'					=> $invoiceRowEnt->idInvoice,
					'serviceCode'				=> $invoiceRowEnt->serviceCode,
					'description'				=> $invoiceRowEnt->description,
					'rowType'					=> $invoiceRowEnt->rowType,
					'externalReservationId'		=> $invoiceRowEnt->externalReservationId,
					'externalReservationDate'	=> $invoiceRowEnt->externalReservationDate,
					'confirmationNumber'		=> $invoiceRowEnt->confirmationNumber,
					'idPassenger'				=> $invoiceRowEnt->idPassenger,
					'checkIn'					=> $invoiceRowEnt->checkIn,
				    'checkOut'					=> $invoiceRowEnt->checkOut,
					'contractNumber'			=> $invoiceRowEnt->contractNumber,
					'ticketNo'					=> $invoiceRowEnt->ticketNo,
					'idSupplierProduct'			=> $invoiceRowEnt->idSupplierProduct,
					'countryCode'				=> $invoiceRowEnt->countryCode,
					'cityId'					=> $invoiceRowEnt->cityId,
					'orderCode'					=> $invoiceRowEnt->reservationCode,
					'orderNumber'				=> $invoiceRowEnt->reservationNumber,
					'idOrder'					=> $invoiceRowEnt->reservationId,
					'idService'					=> $invoiceRowEnt->idService,
					'measureUnit'				=> $invoiceRowEnt->measureUnit,
					'quantity'					=> $invoiceRowEnt->quantity,
					'rowUnitValue'				=> $invoiceRowEnt->unitPriceValue,
					'rowValue'					=> $invoiceRowEnt->priceValue,
					'rowVat'					=> $invoiceRowEnt->vatValue,
					'vatPercent'				=> $invoiceRowEnt->vatPercent,
					'vatText'					=> $invoiceRowEnt->vatText,
					'idBalance'					=> $invoiceRowEnt->idBalance,
				];

				$this->dbExecuteInsert($this->dbTableName_supplierInvoiceRows, $fields);

			}
		}

	}

}
