<?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\MVC\Model\ItemModel;
use Joomla\CMS\Language\Multilanguage;

class SpbookingModelInvoice extends ItemModel
{
	protected $_context = 'com_spbooking.invoice';

	protected function populateState()
	{
		$app = Factory::getApplication('site');
		$itemId = $app->input->getInt('id');
		$this->setState('invoice.id', $itemId);
		$this->setState('filter.language', Multilanguage::isEnabled());
	}

	public function getItem( $itemId = null )
	{
		$user = Factory::getUser();
		$itemId = (!empty($itemId)) ? $itemId : (int) $this->getState('invoice.id');

		if ($this->_item == null)
		{
			$this->_item = array();
		}

		if (!isset($this->_item[$itemId]))
		{
			try
			{
				$db = $this->getDbo();
				$query = $db->getQuery(true);
				$query->select('a.*');
				$query->from($db->quoteName('#__spbooking_bookings', 'a'));
				$query->where('a.id = ' . (int) $itemId);

				// Filter by published state.
				$query->where('a.published = 1');

				if ($this->getState('filter.language'))
				{
					$query->where('a.language in (' . $db->quote(Factory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
				}

				// Authorised
				$groups = implode(',', $user->getAuthorisedViewLevels());
				$query->where('a.access IN (' . $groups . ')');

				$db->setQuery($query);
				$data = $db->loadObject();

				$this->_item[$itemId] = $data;
			}
			catch (Exception $e)
			{
				throw new Exception($e->getMessage(), $e->getCode());

				if ($e->getCode() != 404)
				{
					$this->_item[$itemId] = false;
				}
			}
		}

		return $this->_item[$itemId];
	}

}

