<?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.'companypricelists.php');

class JBusinessDirectoryModelManageCompanyPriceLists extends JBusinessDirectoryModelCompanyPriceLists {
	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 = 'CompanyServicesList', $prefix = 'JTable', $config = array()) {
		return JTable::getInstance($type, $prefix, $config);
	}
	/**
	*
	* @return object with data
	*/
	public function getItems() {
		// Load the data
		$user = JBusinessUtil::getUser();
		$this->companyIds = JBusinessUtil::getCompaniesByUserId($user->id,true);
		$table = $this->getTable();

		if (!empty($this->companyIds)) {
			$items = $table->getUserPriceLists($user->id, $this->companyIds, $this->getState('limitstart'), $this->getState('limit'));
			foreach ($items as &$item) {
				$item->services = explode('##', $item->services);
			}
			return $items;
		}
		return null;
	}

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

}
