<?php
namespace Modules\RemoteData\EntityManagementWs\Model\Entity\Document;

class SendEmail extends \Modules\RemoteData\EntityManagementWs\Model\Entity\GeneralAbstract
{
	/**
	 * Document id received from get request
	 * @var int
	 */
	protected $id;

	public function __construct(array $requestGet, \stdClass $request, \Modules\RemoteData\EntityManagementWs\Model\Response $response)
	{
		parent::__construct($requestGet, $request, $response);
		$this->id = $requestGet['id'];
	}

	/**
	 * {@inheritDoc}
	 * @see \Modules\RemoteData\EntityManagementWs\Model\Entity\GeneralAbstract::checkRequestData()
	 */
	protected function checkRequestData() :void
	{ }


	/**
	 * {@inheritDoc}
	 * @see \Modules\RemoteData\EntityManagementWs\Model\Entity\GeneralAbstract::processRequest()
	 */
	protected function processRequest() :void
	{
		try {
			\DB::startTransaction();
			$this->sendEmail();
			\DB::commitTransaction();
		}
		catch (\App\Entity\Exception $ex) {
			\DB::rollbackTransaction();
			throw new \Modules\RemoteData\EntityManagementWs\Model\RuntimeException($ex->getMessagesCollector()->getMessageBulk(), 'TinaEntityError');
		}
		catch (\Exception $e) {
			\DB::rollbackTransaction();
			throw new \Modules\RemoteData\EntityManagementWs\Model\RuntimeException($e->getMessage(), 'TinaError');
		}
	}

	/**
	 * Does the actual sending of the email
	 */
	private function sendEmail()
	{
		$docEnt = \Entity\Document::sendMail($this->id);

		$docEnt->selfBcc 			= $this->request->selfBcc;
		$docEnt->sendReadReceipt 	= $this->request->sendReadReceipt;
		$docEnt->idSenderUser 		= $this->request->idSenderUser;
		$docEnt->subject 			= $this->request->subject;
		$docEnt->body 				= $this->request->body;
		$docEnt->forceSenderEmail 	= $this->request->forceSenderEmail;
		$docEnt->forceSenderName 	= $this->request->forceSenderName;

		$receiversToResult = []; // this array will be the resulted one where custom email formats will be replaced

		if ($this->request->receiversTo) {
			foreach ($this->request->receiversTo as $receiverEmail) {
				if (in_array($receiverEmail, ['corporateEmail', 'customerEmail', 'corporateOfficeEmail', 'auto'])) {
					$customEmail = $this->determineCustomEmail($receiverEmail);
					if ($customEmail) {
						$receiversToResult[] = $customEmail;
					}
				}
				else {
					$receiversToResult[] = $receiverEmail;
				}
			}
		}

		$docEnt->receiversTo = $receiversToResult;

		$receiversCcResult = [];

		if ($this->request->receiversCc) {
			foreach ($this->request->receiversCc as $receiverEmail) {
				if (in_array($receiverEmail, ['corporateEmail', 'customerEmail', 'corporateOfficeEmail', 'auto'])) {
					$customEmail = $this->determineCustomEmail($receiverEmail);
					if ($customEmail) {
						$receiversCcResult[] = $customEmail;
					}
				}
				else {
					$receiversCcResult[] = $receiverEmail;
				}
			}
		}

		$docEnt->receiversCc = $receiversCcResult;

		if ($this->request->generatedFiles) {
			$docEnt->generatedFiles = $this->request->generatedFiles;
		}

		$docEnt->save();
	}

	/**
	 * Determine the actual email that will replace the specified format
	 * @param string $customEmailType
	 * @throws \Modules\RemoteData\EntityManagementWs\Model\RuntimeException
	 * @return string|NULL
	 */
	private function determineCustomEmail(string $customEmailType) : ?string
	{
		$docEnt = \Entity\Document::selectForUpdate($this->id);
		$emailResult = null;

		switch ($docEnt->pivotCode) {
			case 'invoice':
				if ($customEmailType == 'corporateEmail') {
					$emailResult = $docEnt->pivot->corporate->email;
				}
				elseif ($customEmailType == 'customerEmail') {
					$emailResult = $docEnt->pivot->customer->email;
				}
				elseif ($customEmailType == 'corporateOfficeEmail') {
					$emailResult = $docEnt->pivot->corporateOffice->email;
				}
				elseif ($customEmailType == 'auto') {
					if ($docEnt->pivot->corporateOffice->email) {
						$emailResult = $docEnt->pivot->corporateOffice->email;
					}
					elseif ($docEnt->pivot->corporate->email) {
						$emailResult = $docEnt->pivot->corporate->email;
					}
					elseif ($docEnt->pivot->customer->email) {
						$emailResult = $docEnt->pivot->customer->email;
					}
				}
			break;

			case 'cashing':
				if ($customEmailType == 'corporateEmail') {
					$emailResult = $docEnt->pivot->invoice->corporate->email;
				}
				elseif ($customEmailType == 'customerEmail') {
					$emailResult = $docEnt->pivot->invoice->customer->email;
				}
				elseif ($customEmailType == 'corporateOfficeEmail') {
					$emailResult = $docEnt->pivot->invoice->corporateOffice->email;
				}
				elseif ($customEmailType == 'auto') {
					if ($docEnt->pivot->invoice->corporateOffice->email) {
						$emailResult = $docEnt->pivot->invoice->corporateOffice->email;
					}
					elseif ($docEnt->pivot->invoice->corporate->email) {
						$emailResult = $docEnt->pivot->invoice->corporate->email;
					}
					elseif ($docEnt->pivot->invoice->customer->email) {
						$emailResult = $docEnt->pivot->invoice->customer->email;
					}
				}

			break;

			case 'order':
				if ($customEmailType == 'corporateEmail') {
					$emailResult = $docEnt->pivot->corporateOwner->email;
				}
				elseif ($customEmailType == 'customerEmail') {
					$emailResult = $docEnt->pivot->customerOwner->email;
				}
				elseif ($customEmailType == 'corporateOfficeEmail') {
					$emailResult = $docEnt->pivot->corporateOwnerOffice->email;
				}
				elseif ($customEmailType == 'auto') {
					if ($docEnt->pivot->corporateOwnerOffice->email) {
						$emailResult = $docEnt->pivot->corporateOwnerOffice->email;
					}
					elseif ($docEnt->pivot->corporateOwner->email) {
						$emailResult = $docEnt->pivot->corporateOwner->email;
					}
					elseif ($docEnt->pivot->customerOwner->email) {
						$emailResult = $docEnt->pivot->customerOwner->email;
					}
				}
			break;

			case 'service':
				if ($customEmailType == 'corporateEmail') {
					$emailResult = $docEnt->pivot->order->corporateOwner->email;
				}
				elseif ($customEmailType == 'customerEmail') {
					$emailResult = $docEnt->pivot->order->customerOwner->email;
				}
				elseif ($customEmailType == 'corporateOfficeEmail') {
					$emailResult = $docEnt->pivot->order->corporateOwnerOffice->email;
				}
				elseif ($customEmailType == 'auto') {
					if ($docEnt->pivot->order->corporateOwnerOffice->email) {
						$emailResult = $docEnt->pivot->order->corporateOwnerOffice->email;
					}
					elseif ($docEnt->pivot->order->corporateOwner->email) {
						$emailResult = $docEnt->pivot->order->corporateOwner->email;
					}
					elseif ($docEnt->pivot->order->customerOwner->email) {
						$emailResult = $docEnt->pivot->order->customerOwner->email;
					}
				}
			break;

			case 'importedDocument':
				if ($customEmailType == 'corporateEmail') {
					$emailResult = $docEnt->pivot->corporate->email;
				}
				elseif ($customEmailType == 'customerEmail') {
					$emailResult = $docEnt->pivot->customer->email;
				}
				elseif ($customEmailType == 'corporateOfficeEmail') {
					$emailResult = $docEnt->pivot->corporate->mainOffice->email;
				}
				elseif ($customEmailType == 'auto') {
					if ($docEnt->pivot->corporate->mainOffice->email) {
						$emailResult = $docEnt->pivot->corporate->mainOffice->email;
					}
					elseif ($docEnt->pivot->corporate->email) {
						$emailResult =  $docEnt->pivot->corporate->email;
					}
					elseif ($docEnt->pivot->customer->email) {
						$emailResult = $docEnt->pivot->customer->email;
					}
				}
			break;

			case 'importedService':
				if ($customEmailType == 'corporateEmail') {
					$emailResult = $docEnt->pivot->importedOrder->corporate->email;
				}
				elseif ($customEmailType == 'customerEmail') {
					$emailResult = \Entity\Customer::select($docEnt->pivot->importedOrder->idCustomerOwner)->email;
				}
				elseif ($customEmailType == 'corporateOfficeEmail') {
					$emailResult = $docEnt->pivot->importedOrder->corporate->mainOffice->email;
				}
				elseif ($customEmailType == 'auto') {
					if ($docEnt->pivot->importedOrder->corporate->mainOffice->email) {
						$emailResult = $docEnt->pivot->importedOrder->corporate->mainOffice->email;
					}
					elseif ($docEnt->pivot->importedOrder->corporate->email) {
						$emailResult = $docEnt->pivot->importedOrder->corporate->email;
					}
					elseif (\Entity\Customer::select($docEnt->pivot->importedOrder->idCustomerOwner)->email) {
						$emailResult = \Entity\Customer::select($docEnt->pivot->importedOrder->idCustomerOwner)->email;
					}
				}
			break;

			default: {
				throw new \Modules\RemoteData\EntityManagementWs\Model\RuntimeException(sprintf("For pivot %s the custom email is not supported", $docEnt->pivotCode));
			}
		}

		return $emailResult;
	}

}
