<?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\Table\Table;
use Joomla\String\StringHelper;
use Joomla\CMS\MVC\Model\AdminModel;

class SpbookingModelBooking extends AdminModel
{
	protected $text_prefix = 'COM_SPBOOKING';

	public function getTable($name = 'Booking', $prefix = 'SpbookingTable', $config = array())
	{
		return Table::getInstance($name, $prefix, $config);
	}

	public function getForm($data = array(), $loadData = true)
	{
		$app = Factory::getApplication();
		$form = $this->loadForm('com_spbooking.booking', 'booking', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	public function loadFormData()
	{
		$data = Factory::getApplication()
			->getUserState('com_spbooking.edit.booking.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		return $data;
	}

	protected function canDelete($record)
	{
		if (!empty($record->id))
		{
			if ($record->published != -2)
			{
				return;
			}

			$user = Factory::getUser();

			return parent::canDelete($record);
		}
	}

	protected function canEditState($record)
	{
		return parent::canEditState($record);
	}

	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			$item->total_price = 0;

			if ($item->booking_for == 'room')
			{
				$cartData  = !empty($item->cartData) && is_string($item->cartData) ? json_decode($item->cartData) : false;
				$room_info = !empty($item->number_of_rooms) && is_string($item->number_of_rooms) ? json_decode($item->number_of_rooms) : false;

				if ($cartData)
				{
					$key = 0;

					foreach ($cartData as $k => $cdata)
					{
						if ($k != 'additionalServices')
						{
							foreach ($cdata->room_price as $cd)
							{
								$cd->special_price = (int) $cd->special_price;
								$cd->original_price = (int) $cd->original_price;
								$cd->child_special_price = (int) $cd->child_special_price;
								$cd->child_price = (int) $cd->child_price;

								if (!empty($cd->special_price))
								{
									$item->total_price += $cd->special_price * $cdata->n_rooms;
								}
								else
								{
									$item->total_price += $cd->original_price * $cdata->n_rooms;
								}

								if (isset($cdata->child))
								{
									if (!empty($cd->child_special_price))
									{
										$item->total_price += $cd->child_special_price * $cdata->n_rooms;
									}
									else
									{
										$item->total_price += $cd->child_price * $cdata->n_rooms;
									}
								}
							}

							// Adding Adult and Child info in "number_of_rooms" data so that it can be visible in the booking list.
							if ($room_info)
							{
								$number_of_rooms = 'number_of_rooms' . $key;

								if ($room_info->$number_of_rooms && $cdata->room_id === $room_info->$number_of_rooms->room)
								{
									$room_info->$number_of_rooms->room_adult = $cdata->adult;
									$room_info->$number_of_rooms->room_child = (isset($cdata->child)) ? $cdata->child : '';
									$key++;
								}
							}
						}
						else
						{
							foreach ($cdata as  $service)
							{
								$item->extra_features[] = $service->id;
								$item->total_price 	   += $service->price;
							}
						}
					}
				}

				$item->number_of_rooms = (!empty($room_info) ? json_encode($room_info) : $item->number_of_rooms);
			}
			elseif ($item->booking_for == 'package' || $item->booking_for == 'transport')
			{
				$cartData = !empty($item->cartData) && is_string($item->cartData) ? json_decode($item->cartData) : false;

				$sale_price 	  = (int) $cartData->sale_price;
				$price     		  = (int) $cartData->price;
				$child_sale_price = (isset($cartData->child_sale_price)) ? (int) $cartData->child_sale_price : 0;
				$child_price 	  = (isset($cartData->child_price)) ? (int) $cartData->child_price : 0;

				// For Transport
				if ($item->booking_for == 'transport')
				{
					$pickup_date                = new DateTime($cartData->pickup_date);
					$dropoff_date               = new DateTime($cartData->dropoff_date);

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

				if (!empty($sale_price))
				{
					$item->total_price = ($item->booking_for == 'package') ? $sale_price * $cartData->adult : $sale_price * $total_interval_days;
				}
				else
				{
					$item->total_price = ($item->booking_for == 'package') ? $price * $cartData->adult : $price	* $total_interval_days;
				}

				// Child Price
				if ($cartData->child)
				{
					if (!empty($child_sale_price))
					{
						$item->total_price += ($item->booking_for == 'package') ? $child_sale_price * $cartData->child : $child_sale_price * $total_interval_days;
					}
					else
					{
						$item->total_price += ($item->booking_for == 'package') ? $child_price * $cartData->child : $child_price * $total_interval_days;
					}
				}

				// Additional Price
				if (!empty($cartData->additionalServices) && ($item->booking_for == 'package'))
				{
					foreach ($cartData->additionalServices as $service)
					{
						$item->total_price += $service->price;
						$item->extra_features[] = $service->id;
					}
				}

				$item->adult = $cartData->adult;
				$item->child = $cartData->child;

				// Tax Calculation
				$item->total_price = (float) $item->total_price + ($item->total_price * ($item->tax / 100));
			}

			return $item;
		}

		return parent::getItem($pk);
	}

	private function generateNewTitleLocally($alias, $title)
	{
		// Alter the title & alias
		$table = $this->getTable();

		while ($table->load(array('alias' => $alias)))
		{
			$title = StringHelper::increment($title);
			$alias = StringHelper::increment($alias, 'dash');
		}

		return array($title, $alias);
	}

	public function save($data)
	{
		$input 	= Factory::getApplication()->input;
		$task 	= $input->get('task');

		if ($task == 'save2copy')
		{
			$originalTable = clone $this->getTable();
			$originalTable->load($input->getInt('id'));

			if ($data['title'] == $originalTable->title)
			{
				list($title, $alias) = $this->generateNewTitleLocally($data['alias'], $data['title']);
				$data['title'] = $title;
				$data['alias'] = $alias;
			}
			else
			{
				if ($data['alias'] == $originalTable->alias)
				{
					$data['alias'] = '';
				}
			}

			$data['published'] = 0;
		}

		if (parent::save($data))
		{
			return true;
		}

		return false;
	}
}

