<?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');
use Joomla\Utilities\ArrayHelper;

jimport('joomla.application.component.modeladmin');
/**
 * Company Price List Model.
 *
 */
class JBusinessDirectoryModelCompanyPriceList extends JModelAdmin {
	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since   1.6
	 */
	protected $text_prefix = 'COM_JBUSINESSDIRECTORY_COMPANY_PRICE_LIST';

	/**
	 * Model context string.
	 *
	 * @var		string
	 */
	protected $_context		= 'com_jbusinessdirectory.companypricelist';

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object	A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
	 */
	protected function canDelete($record) {
		return true;
	}

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object	A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission set in the component.
	 */
	protected function canEditState($record) {
		return true;
	}

	/**
	 * 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);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since   1.6
	 */
	protected function populateState() {
		$app = JFactory::getApplication('administrator');

		// Load the User state.
		$id = JFactory::getApplication()->input->getInt('id');
		$this->setState('companypricelist.id', $id);
	}

	/**
	 * Method to get a menu item.
	 *
	 * @param   integer	The id of the menu item to get.
	 *
	 * @return  mixed  Menu item data object on success, false on failure.
	 */
	public function &getItem($itemId = null) {
		$companyId = (!empty($itemId)) ? $itemId : (int) $this->getState('companypricelist.id');

		// Get a menu item row instance.
		$table = $this->getTable();

		$value = new stdClass();
		$value->id = $companyId;
		$value->companyId = $companyId;
		$value->services = $table->getPriceList($companyId);
		if (empty($value->services)) {
			$service = new stdClass();
			$service->service_name = "";
			$service->service_section = "";
			$service->service_description = "";
			$service->service_price = "";
			$service->service_image = "";
			$service->id = "";
			$value->services = array(
				$service
			);
		}

		$companyTable = $this->getTable('Company');
		if (!empty($value->id)) {
			$value->companyOptions = array($companyTable->getCompany($value->companyId));
		}
		foreach($value->services as $service) {
			$service->translations = JBusinessDirectoryTranslations::getAllTranslations(COMPANY_PRICE_LIST_TRANSLATION, $service->id);
		}

		return $value;
	}

	/**
	 * Method to get the menu item form.
	 *
	 * @param   array  $data		Data for the form.
	 * @param   boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return  JForm	A JForm object on success, false on failure
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true) {
		exit;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 * @since   1.6
	 */
	protected function loadFormData() {
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_jbusinessdirectory.edit.companypricelist.data', array());

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

		return $data;
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  The form data.
	 * @return  boolean  True on success.
	 */
	public function save($data) {
		$appSettings = JBusinessUtil::getApplicationSettings();
		$jinput      = JFactory::getApplication()->input;
		$id	= (!empty($data['id'])) ? $data['id'] : (int) $this->getState('companypricelist.id');

		$defaultLng = JBusinessUtil::getLanguageTag();
		$serviceName = JFactory::getApplication()->input->get('name_'.$defaultLng, '', 'RAW');
		$serviceDesc = JFactory::getApplication()->input->get('description_'.$defaultLng, '', 'RAW');

		if (!empty($serviceName) && empty($data["service_name"])) {
			$data["service_name"] = $serviceName;
		}

		if (!empty($serviceDesc) && empty($data["service_description"])) {
			$data["service_description"] = $serviceDesc;
		}


		$companyId = $data['companyId'];
		$serviceName = isset($data["service_name"])?$data["service_name"]:array();
		$serviceSection = isset($data["service_section"])?$data["service_section"]:array();
		$serviceDesc = isset($data["service_description"])?$data["service_description"]:array();
		$servicePrice = isset($data["service_price"])?$data["service_price"]:array();
		$serviceImage = isset($data["service_image"])?$data["service_image"]:array();
		$servicesId = isset($data["service_id"])?$data["service_id"]:array();
		
		if (!empty($id) && !$this->deleteCompanyServices($servicesId, $companyId)) {
			return false;
		}

		if (!empty($servicesId)) {
			$usedImages = array();
			if (!empty($serviceImage)) {
				foreach ($serviceImage as $img) {
					array_push($usedImages, $img);
				}
			}

			$pictures_path = JBusinessUtil::makePathFile(BD_PICTURES_UPLOAD_PATH);
			$company_pictures_path = JBusinessUtil::makePathFile(PRICE_LIST_PICTURES_PATH.($companyId)."/");
			if (!empty($id)) {
				JBusinessUtil::removeUnusedFiles($usedImages, $pictures_path, $company_pictures_path);
			}

			$companyServiceTable = $this->getTable();
			foreach ($servicesId as $key => $value) {
				if (!empty($serviceImage[$key])) {
					$serviceImage[$key] = JBusinessUtil::moveFile($serviceImage[$key], $companyId, $companyId, PRICE_LIST_PICTURES_PATH);
				}
				$companyServiceTable->id = 0;
				if (!empty($value)) {
					$companyServiceTable->id = $value;
				}
				$companyServiceTable->service_name = $serviceName[$key];
				$companyServiceTable->service_description = $serviceDesc[$key];
				$companyServiceTable->service_section = $serviceSection[$key];
				$companyServiceTable->service_price = JBusinessUtil::convertPriceToMysql($servicePrice[$key]);
				$companyServiceTable->service_image = $serviceImage[$key];
				$companyServiceTable->companyId = $companyId;

				if (!$companyServiceTable->store()) {
					$application = JFactory::getApplication();
					$application->enqueueMessage($companyServiceTable->getError(), 'error');
					return false;
				}

				$languages = JBusinessUtil::getLanguages();
				foreach ($languages as $lng) {
					$description = $jinput->getString('description_' . $lng, '', 'RAW');
					$name        = $jinput->getString('name_' . $lng, '', 'RAW');
		
					$description = $description[$key];
					$name = $name[$key];
					JBusinessDirectoryTranslations::saveTranslation(COMPANY_PRICE_LIST_TRANSLATION, $companyServiceTable->id, $lng, $name, null, $description);
				}
			}
		}

		$this->setState('com_jbusinessdirectory.edit.companypricelist.id', $companyId);

		// Clean the cache
		$this->cleanCache();

		return true;
	}

	public function deleteCompanyServices($servicesIds, $companyId) {
		if (is_array($servicesIds)) {
			$ids = implode(',', array_filter($servicesIds));
		}

		$rowOpt = $this->getTable();

		if ($rowOpt->deleteCompanyServices($companyId, $ids)) {
			$application = JFactory::getApplication();
			$application->enqueueMessage($rowOpt->getError(), 'error');
			return false;
		}
		return true;
	}

	
	/**
	 * Method to delete groups.
	 *
	 * @param   array  An array of item ids.
	 * @return  boolean  Returns true on success, false on failure.
	 */
	public function delete(&$itemIds) {
		// Sanitize the ids.
		$itemIds = (array) $itemIds;
		ArrayHelper::toInteger($itemIds);
	
		// Get a group row instance.
		$table = $this->getTable();

		$companyIds = implode(',', $itemIds);	
		if (!$table->deleteCompanyServices($companyIds)) {
			$this->setError($table->getError());
			return false;
		}
	
		// Clean the cache
		$this->cleanCache();
	
		return true;
	}
}
