<?php

/**
 * @package com_spbooking
 * @author JoomShaper http://www.joomshaper.com
 * @copyright Copyright (c) 2010 - 2023 JoomShaper
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
 */

// No Direct Access
defined('_JEXEC') or die('Resticted Aceess');

use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\MVC\View\HtmlView;
use Joomla\CMS\Component\ComponentHelper;

class SpbookingViewPayment extends HtmlView
{
	protected $item;
	public function display($tpl = null)
	{
		$model                      = $this->getModel();
		$input                      = Factory::getApplication()->input;
		$doc                        = Factory::getDocument();
		$this->user                 = Factory::getUser();
		$this->item                 = $this->get('Item');
		$this->payment_for          = $input->get('payment_for', 'accomodation', 'STRING');
		$this->booked_id            = $input->get('booking_id', '', 'STRING');
		$this->validity = true;

		$this->params = ComponentHelper::getParams('com_spbooking');
		$this->currency = explode(':', $this->params->get('currency', "USD:$"));
		$this->payment_method = $this->params->get('payment_method', array('paypal', 'paylater','stripe'));
		$this->item->tax = $this->params->get('tax', '');

		$this->notify_url 	    = Uri::base() . 'index.php?option=com_spbooking&task=payment.notify';
		$this->return_success   = Uri::base() . 'index.php?option=com_spbooking&task=payment.success';
		$this->return_cencel    = Uri::base() . 'index.php?option=com_spbooking&task=payment.paymencancel';

		$this->paylater_url     = Uri::base() . 'index.php?option=com_spbooking&task=payment.paylater';

		if ($this->payment_for == 'accomodation')
		{
			$this->accomodation_id    = $input->get('accomodation_id', '', 'INT');
			$this->validity = $this->isValidRequest($this->accomodation_id, $this->booked_id, 'room');
		}
		elseif ($this->payment_for == 'package')
		{
			$this->package_id = $input->get('package_id', '', 'INT');
			$this->validity = $this->isValidRequest($this->package_id, $this->booked_id, 'package');
		}
		elseif ($this->payment_for == 'transport')
		{
			$this->transport_id = $input->get('transport_id', '', 'INT');
			$this->validity = $this->isValidRequest($this->transport_id, $this->booked_id, 'transport');
		}

		if (!empty($this->item))
		{
			if ($this->payment_for == 'accomodation')
			{
				$this->item->accomodation   = array();
				$this->item->accomodation = $model->getAccomodationInfo($this->accomodation_id);

				if (!empty($this->item->cartData) && is_string($this->item->cartData))
				{
					$this->item->cartData = json_decode($this->item->cartData);
				}

				$this->subtotal = 0;
				$this->total = 0;
				$this->tax = 0;

				if (!empty($this->item->cartData))
				{
					foreach ($this->item->cartData as $key => $cdata)
					{
						if ($key == 'additionalServices')
						{
							foreach ($cdata as $additionalServices)
							{
								$this->subtotal += $additionalServices->price;
							}
						}
						else
						{
							$room_price = $this->calculateUnitPrice($cdata->room_price) * (int) $cdata->n_rooms;
							$this->subtotal += (float) $room_price;
						}
					}
				}

				$this->tax = ($this->subtotal * (float) $this->item->tax) / 100;
				$this->total = $this->subtotal + $this->tax;
			}
			elseif ($this->payment_for == 'package')
			{
				$this->item->package = $model->getPackageInfo($this->package_id);

				if (!empty($this->item->cartData) && is_string($this->item->cartData))
				{
					$this->item->cartData = json_decode($this->item->cartData);
				}

				if (!empty($this->item->cartData))
				{
					$this->item->cartData->price      = (int) $this->item->cartData->price;
					$this->item->cartData->sale_price = (int) $this->item->cartData->sale_price;
					$this->price                      = $this->item->cartData->price;
					$this->sale_price                 = $this->item->cartData->sale_price;
					$this->child_price                = (int) $this->item->cartData->child_price;
					$this->child_sale_price           = (int) $this->item->cartData->child_sale_price;
					$this->total_child_price          = 0;
					$this->additional_service         = 0;

					if (!empty($this->sale_price))
					{
						$this->price = $this->sale_price;
					}

					if (!empty($this->child_sale_price))
					{
						$this->child_price = $this->child_sale_price;
					}

					$this->tax = ($this->price * (float) $this->item->tax) / 100;
					$this->item->cartData->adult = (!empty($this->item->cartData->adult) ? $this->item->cartData->adult : 1);
					$this->total_adult_price = $this->price * $this->item->cartData->adult;

					if (!empty($this->child_price))
					{
						$this->total_child_price = $this->child_price * $this->item->cartData->child;
					}

					if (!empty($this->item->cartData->additionalServices))
					{
						foreach ($this->item->cartData->additionalServices as $service)
						{
							$this->additional_service += $service->price;
						}
					}

					$this->unit_total = $this->total_adult_price + $this->total_child_price + $this->additional_service;
					$this->subtotal = $this->unit_total;
					$this->tax = ($this->subtotal * (float) $this->item->tax) / 100;
					$this->total = $this->subtotal + $this->tax;
					$this->save_price = $this->item->cartData->price - $this->item->cartData->sale_price;
				}
			}
			elseif ($this->payment_for == 'transport')
			{
				$this->item->transport = $model->getTransportInfo($this->transport_id);

				if (!empty($this->item->cartData) && is_string($this->item->cartData))
				{
					$this->item->cartData = json_decode($this->item->cartData);
				}

				if (!empty($this->item->cartData))
				{
					$this->item->cartData->price      = (int) $this->item->cartData->price;
					$this->item->cartData->sale_price = (int) $this->item->cartData->sale_price;
					$this->price                      = $this->item->cartData->price;
					$this->sale_price                 = $this->item->cartData->sale_price;
					$this->child_price                = (int) $this->item->cartData->child_price;
					$this->child_sale_price           = (int) $this->item->cartData->child_sale_price;
					$this->pickup_date                = new DateTime($this->item->cartData->pickup_date);
					$this->dropoff_date               = new DateTime($this->item->cartData->dropoff_date);

					$interval = $this->dropoff_date->diff($this->pickup_date);
					$this->total_interval_days = $interval->d;

					if (!empty($this->sale_price))
					{
						$this->price = $this->sale_price;
					}

					if (!empty($this->child_sale_price))
					{
						$this->child_price = $this->child_sale_price;
					}

					if ($this->item->cartData->child)
					{
						$price = $this->price + $this->child_price;
					}
					else
					{
						$price = $this->price;
					}

					$this->subtotal = ($price) * $this->total_interval_days;
					$this->tax = ($this->subtotal * (float) $this->item->tax) / 100;
					$this->total = $this->subtotal + $this->tax;
					$this->save_price = $this->item->cartData->price - $this->item->cartData->sale_price;
				}
			}
		}

		if (!$this->validity)
		{
			return Factory::getApplication()->enqueueMessage('Invalid Url! You must not modify the url query parameters.', 'error');
		}

		$doc->addScript(Uri::root() . 'components/com_spbooking/assets/js/sppayment.js');
		$doc->addScriptDeclaration("
            jQuery(function($){
                $('.spbooking-payment').spPayment();
            });
        "
		);

		return parent::display($tpl = null);
	}

	private function isValidRequest($id, $booking_id, $type ='room')
	{
		$db = Factory::getDbo();
		$query = $db->getQuery(true);
		$query->select('id')
			->from($db->quoteName('#__spbooking_bookings'))
			->where($db->quoteName('published') . ' = 1')
			->where($db->quoteName('booked_id') . ' = ' . $db->quote($booking_id));

		$query->where($db->quoteName('booking_for') . ' = ' . $db->quote($type));

		if ($type == 'room')
		{
			$query->where($db->quoteName('accomodation_id') . ' = ' . $db->quote($id));
		}
		elseif ($type == 'package')
		{
			$query->where($db->quoteName('package_id') . ' = ' . $db->quote($id));
		}
		elseif ($type == 'transport')
		{
			$query->where($db->quoteName('transport_id') . ' = ' . $db->quote($id));
		}

		$query->where($db->quoteName('booking_status') . ' = ' . $db->quote('in_approve'));
		$db->setQuery($query);
		$result = $db->loadObject();

		return !empty($result) ? true : false;
	}

	public function calculateUnitPrice($priceData)
	{
		$price = 0;

		if (!empty($priceData))
		{
			foreach ($priceData as $v)
			{
				$v->special_price = (int) $v->special_price;
				$v->original_price = (int) $v->original_price;
				$v->child_special_price = (int) $v->child_special_price;
				$v->child_price = (int) $v->child_price;
				$total_price = (isset($v->child_val) && $v->child_val) ? ($v->original_price + $v->child_price) : $v->original_price;

				if ($v->special_price || $v->child_special_price)
				{
					$price += ($v->special_price > 0 && $v->special_price < $v->original_price) ? $v->special_price : $v->original_price;
					$price += ($v->child_special_price > 0 && $v->child_special_price < $v->child_price && $v->child_val) ? $v->child_special_price : (($v->child_val) ? $v->child_price : 0);
				}
				else
				{
					$price += $total_price;
				}
			}
		}

		return $price;
	}
}
