<?php
/**
 * @version     1.4.7
 * @package     sellacious
 *
 * @copyright   Copyright (C) 2012-2017 Bhartiy Web Technologies. All rights reserved.
 * @license     SPL Sellacious Private License; see http://www.sellacious.com/spl.html
 * @author      Izhar Aazmi <info@bhartiy.com> - http://www.bhartiy.com
 */
// no direct access.
defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Sellacious Shop rule model
 */
class SellaciousModelShippingRule extends SellaciousModelAdmin
{
	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object $record A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission for the component.
	 *
	 * @since   12.2
	 */
	protected function canDelete($record)
	{
		$me      = JFactory::getUser();
		$allowed = $this->helper->access->check('shippingrule.delete') ||
			($me->id == $record->owned_by && $this->helper->access->check('shippingrule.delete.own'));

		return $allowed;
	}

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission for the component.
	 *
	 * @since  12.2
	 */
	protected function canEditState($record)
	{
		return $this->helper->access->check('shippingrule.edit.state');
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array $data The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function save($data)
	{
		$app        = JFactory::getApplication();
		$dispatcher = JEventDispatcher::getInstance();

		/** @var SellaciousTableShippingRule $table */
		$table = $this->getTable();
		$pk    = !empty($data['id']) ? $data['id'] : (int) $this->getState($this->getName() . '.id');
		$isNew = true;

		// Include the plugins for the on save events.
		JPluginHelper::importPlugin('sellacious');

		// Load the row if saving an existing category.
		if ($pk > 0)
		{
			$table->load($pk);

			$isNew = false;
		}

		// Alter the title for save as copy
		if ($app->input->get('task') == 'save2copy')
		{
			list($title) = $this->generateNewTitle(null, null, $data['title']);
			$data['title'] = $title;
		}

		$table->bind($data);
		$table->check();

		// Trigger the onBeforeSave event.
		$context = $this->option . '.' . $this->name;
		$dispatcher->trigger($this->event_before_save, array($context, &$table, $isNew));

		if (!$this->helper->access->check('shippingrule.edit'))
		{
			$table->set('owned_by', JFactory::getUser()->id);
		}

		// Store the data.
		$table->store();

		// Trigger the onAfterSave event.
		$dispatcher->trigger($this->event_after_save, array($context, &$table, $isNew));

		$this->setState($this->getName() . '.id', $table->get('id'));

		return true;
	}

	/**
	 * Method to change the title & alias.
	 *
	 * @param   integer  $parent_id  The id of the category or parent.
	 * @param   string   $alias      The alias.
	 * @param   string   $title      The title.
	 *
	 * @return  array  Contains the modified title and alias.
	 *
	 * @since    12.2
	 */
	protected function generateNewTitle($parent_id, $alias, $title)
	{
		$table = $this->getTable();

		$keys = array('title' => $title);

		while ($table->load($keys))
		{
			$title = Joomla\String\StringHelper::increment($title);

			$keys['title'] = $title;
		}

		return array($title, $alias);
	}

	/**
	 * Override preprocessForm to load the sellacious plugin group instead of content.
	 *
	 * @param  JForm   $form   A form object.
	 * @param  mixed   $data   The data expected for the form.
	 * @param  string  $group  Plugin group to load
	 *
	 * @since  1.6
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'sellacious')
	{
		$obj = is_array($data) ? ArrayHelper::toObject($data) : $data;

		$methods = (array) $this->helper->config->get('seller_shippable_methods', array());

		$form->setFieldAttribute('method_name', 'choices', implode('|', $methods));

		if (empty($obj->method_name) || $obj->method_name != '*')
		{
			$form->removeField('amount');
			$form->removeField('amount_additional');
		}

		if (empty($obj->method_name) || $obj->method_name == '*')
		{
			$form->removeField('packaging_weight');
		}

		parent::preprocessForm($form, $data, $group);
	}
}
