<?php
/**
 * @package    VP Email Manager
 * @copyright  Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @author     Abhishek Das <info@virtueplanet.com>
 * @link       https://www.virtueplanet.com
 */

defined('_JEXEC') or die;

jimport('joomla.application.component.modeladmin');

use \Joomla\CMS\Table\Table;
use Joomla\Registry\Registry;
use \Joomla\CMS\Factory;
use \Joomla\CMS\Language\Text;
use \Joomla\CMS\Plugin\PluginHelper;

/**
 * Vpem model.
 */
class VpemModelEvent extends \Joomla\CMS\MVC\Model\AdminModel
{
	/**
	 * @var   string   The prefix to use with controller messages.
	 */
	protected $text_prefix = 'COM_VPEM';

	/**
	 * @var   string  Alias to manage history control
	 */
	public $typeAlias = 'com_vpem.event';

	/**
	 * @var null  Item data
	 */
	protected $item = null;

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return    JTable    A database object
	 */
	public function getTable($type = 'Event', $prefix = 'VpemTable', $config = [])
	{
		return Table::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      An optional array of data for the form to interogate.
	 * @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
	 */
	public function getForm($data = [], $loadData = true)
	{
		// Initialise variables.
		$app = Factory::getApplication();

		// Get the form.
		$form = $this->loadForm('com_vpem.event', 'event', ['control' => 'jform', 'load_data' => $loadData]);

		if (empty($form))
		{
			return false;
		}

		return $form;
	}
	
	/**
	 * Method to allow derived classes to preprocess the form.
	 *
	 * @param   JForm   $form   A JForm object.
	 * @param   mixed   $data   The data expected for the form.
	 * @param   string  $group  The name of the plugin group to import (defaults to "content").
	 *
	 * @return  void
	 *
	 * @see     JFormField
	 * @throws  Exception if there is an error in the form event.
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'content')
	{
		if (!empty($form))
		{
			$dataObject = (object) $data;
			
			if (!empty($dataObject->type))
			{
				$form->setFieldAttribute('type', 'readonly', 'true');
			}
			
			$params = JComponentHelper::getParams('com_vpem');
			$config = Factory::getConfig();
			
			$form->setFieldAttribute('mail_from', 'default', $config->get('mailfrom'));
			$form->setFieldAttribute('mail_from_name', 'default', $config->get('fromname'));
			
			$attachment_dir = JPATH_SITE . '/media/com_vpem/attachments';
			$attachment_dir = $params->get('attachment_dir', $attachment_dir);
			$attachment_dir = JPath::clean($attachment_dir);
			
			$form->setFieldAttribute('attachments', 'directory', $attachment_dir);
			
			$base_path_length        = strlen(JPATH_ROOT . DIRECTORY_SEPARATOR);
			$relative_attachment_dir = substr($attachment_dir, $base_path_length) . DIRECTORY_SEPARATOR;
			
			$form->setFieldAttribute('attachments', 'hint', Text::sprintf('COM_VPEM_FORM_HINT_ATTACHMENTS', $relative_attachment_dir));
			
			if (!empty($dataObject->mail_from))
			{
				// $form->setFieldAttribute('mail_from', 'readonly', true);
			}
			
			if (!empty($dataObject->mail_from_name))
			{
				// $form->setFieldAttribute('mail_from_name', 'readonly', true);
			}
		}
		
		parent::preprocessForm($form, $data, $group);
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return   mixed  The data for the form.
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = Factory::getApplication()->getUserState('com_vpem.edit.event.data', []);

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

			$data = $this->item;
		}

		return $data;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer  $pk  The id of the primary key.
	 *
	 * @return  mixed    Object on success, false on failure.
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			$multiple_fields = ['attachments', 'filter_vendor', 'filter_product', 'filter_category', 'filter_manufacturer', 'filter_user', 'filter_shopper_group', 'filter_country', 'filter_st_country', 'filter_status'];

			foreach ($multiple_fields as $multiple_field)
			{
				if (!empty($item->$multiple_field) && is_string($item->$multiple_field))
				{
					$registry = new Registry($item->$multiple_field);

					$item->$multiple_field = $registry->toArray();
				}
			}
		}

		return $item;
	}

	/**
	 * Method to duplicate an Event
	 *
	 * @param   array  &$pks  An array of primary key IDs.
	 *
	 * @return  boolean  True if successful.
	 *
	 * @throws  Exception
	 */
	public function duplicate(&$pks)
	{
		$user = Factory::getUser();

		// Access checks.
		if (!$user->authorise('core.create', 'com_vpem'))
		{
			throw new Exception(Text::_('JERROR_CORE_CREATE_NOT_PERMITTED'));
		}

		$dispatcher = JEventDispatcher::getInstance();
		$context    = $this->option . '.' . $this->name;

		// Include the plugins for the save events.
		PluginHelper::importPlugin($this->events_map['save']);

		$table = $this->getTable();

		foreach ($pks as $pk)
		{
			if ($table->load($pk, true))
			{
				// Reset the id to create a new record.
				$table->id = 0;

				if (!$table->check())
				{
					throw new Exception($table->getError());
				}

				// Trigger the before save event.
				$result = $dispatcher->trigger($this->event_before_save, array($context, &$table, true));

				if (in_array(false, $result, true) || !$table->store())
				{
					throw new Exception($table->getError());
				}

				// Trigger the after save event.
				$dispatcher->trigger($this->event_after_save, array($context, &$table, true));
			}
			else
			{
				throw new Exception($table->getError());
			}
		}

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

		return true;
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 *
	 * @param   JTable  $table  Table Object
	 *
	 * @return void
	 */
	protected function prepareTable($table)
	{
		jimport('joomla.filter.output');
		
		if (!empty($table->body))
		{
			$dom  = new DOMDocument;
			$mock = new DOMDocument;
			
			$dom->loadHTML($table->body);
			
			$body = $dom->getElementsByTagName('body')->item(0);

			foreach ($body->childNodes as $child)
			{
				$mock->appendChild($mock->importNode($child, true));
			}

			$table->body = $mock->saveHTML();
		}

		if (empty($table->id))
		{
			// Set ordering to the last item if not set
			if (@$table->ordering === '')
			{
				$db = Factory::getDbo();
				$db->setQuery('SELECT MAX(ordering) FROM #__vpem_templates');
				
				$max = $db->loadResult();
				$table->ordering = $max + 1;
			}
		}
	}
}
