<?php
/**
 * @package    JBusinessDirectory
 *
 * @author CMSJunkie http://www.cmsjunkie.com
 * @copyright  Copyright (C) 2007 - 2021 CMSJunkie. All rights reserved.
 * @license   https://www.gnu.org/licenses/agpl-3.0.en.html
 */
defined('_JEXEC') or die('Restricted access');


JTable::addIncludePath(DS.'components'.DS.'com_jbusinessdirectory'.DS.'tables');
require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'models'.DS.'events.php');

class JBusinessDirectoryModelManageCompanyEvents extends JBusinessDirectoryModelEvents {
	public function __construct() {
		parent::__construct();
		$this->appSettings = JBusinessUtil::getApplicationSettings();
		$this->_total = 0;

		$mainframe = JFactory::getApplication();
		$jinput = JFactory::getApplication()->input;
		// Get pagination request variables
		$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $jinput->get('limitstart', 0);

		// In case limit has been changed, adjust it
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);

		$offset = $jinput->getInt('limitstart');
		$this->setState('list.offset', $offset);
	}
	
	/**
	 * Returns a Table object, always creating it
	 *
	 * @param   type	The table type to instantiate
	 * @param   string	A prefix for the table class name. Optional.
	 * @param   array  Configuration array for model. Optional.
	 * @return  JTable	A database object
	 */
	public function getTable($type = 'Companies', $prefix = 'JTable', $config = array()) {
		return JTable::getInstance($type, $prefix, $config);
	}
	/**
	*
	* @return object with data
	*/
	public function getEvents() {
		// Load the data
		$user = JBusinessUtil::getUser();
		$packagesTable = $this->getTable("Package");
		$eventsTable = JTable::getInstance('Event', 'JTable', array());

		if (empty($this->_data)) {
			$this->_data = $eventsTable->getUserEvents($user->id, $this->getState('limitstart'), $this->getState('limit'));

			if (!empty($this->_data)) {
				foreach ($this->_data as $event) {
					$event->allow_events = false;
					$event->expired = false;
	
					if (!$this->appSettings->enable_packages || $this->appSettings->item_decouple) {
						$event->allow_events = true;
					} elseif (!empty($event->company_id)) {
						$package = $packagesTable->getCurrentActivePackage($event->company_id);

						if (!empty($package->features)) {
							$event->features = $package->features;
						} else {
							$event->features = array();
						}

						if (in_array(COMPANY_EVENTS, $event->features)) {
							$event->allow_events = true;
						}
					}
					if (!empty($event->end_date) && $event->end_date != '0000-00-00' && (strtotime(date("Y-m-d")) > strtotime($event->end_date))) {
						$event->expired = true;
					}

					$event->checklist = JBusinessUtil::getCompletionProgress($event, 3);
					$event->progress = 0;

					if (count($event->checklist) > 0) {
						// calculate percentage of completion
						$count = 0;
						$completed = 0;
						foreach ($event->checklist as $key => $val) {
							if ($val->status) {
								$completed++;
							}
							$count++;
						}
						$event->progress = (float)($completed / $count);
					}
					$event->progress = round($event->progress, 4);
				}
			}
		}
		
		if (empty($this->_data)) {
			$this->_data = array();
		}
		
		if ($this->appSettings->enable_multilingual) {
			JBusinessDirectoryTranslations::updateEventsTranslation($this->_data);
		}
		
		return $this->_data;
	}
	
	/**
	 * Check if event creating is allowed
	 *
	 * @return boolean
	 */
	public function getCreateEventPermission() {
		$packagesTable = $this->getTable("Package");

		$user = JBusinessUtil::getUser();
		$companiesTable = $this->getTable("Company");
		$companies = $companiesTable->getCompaniesByUserId($user->id);


		if (!$this->appSettings->enable_packages || $this->appSettings->item_decouple) {
			return true;
		} else {
			if (!empty($companies)) {
				foreach ($companies as $company) {
					$package = $packagesTable->getCurrentActivePackage($company->id);

					if (empty($package)) {
						continue;
					}

					if (!empty($package->features)) {
						$package->features = $package->features;
					} else {
						$package->features = array();
					}

					if (!empty($package->features) && in_array(COMPANY_EVENTS, $package->features)) {
						return true;
					}
				}
			}
		}

		return false;
	}

	public function getTotal() {
		$user = JBusinessUtil::getUser();
		// Load the content if it doesn't already exist
		if (empty($this->_total)) {
			$offersTable = $this->getTable("Event");
			$this->_total = $offersTable->getTotalUserEvents(JBusinessUtil::getCompaniesByUserId($user->id,true), $user->id);
		}
		
		return $this->_total;
	}
}
