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

defined('_JEXEC') or die;

/**
 * VPAdvancedUserModelCustomfield model.
 *
 * @since  1.0
 */
class VPAdvancedUserModelCustomfield extends JModelAdmin
{
	/**
	 * @var     string    The prefix to use with controller messages.
	 * @since   1.6
	 */
	protected $text_prefix = 'COM_VPADVANCEDUSER';

	/**
	 * @var     string    Alias to manage history control
	 * @since   3.2
	 */
	public $typeAlias = 'com_vpadvanceduser.customfield';

	/**
	 * @var     null      Item data
	 * @since   1.6
	 */
	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
	 *
	 * @since    1.6
	 */
	public function getTable($type = 'Customfield', $prefix = 'VPAdvancedUserTable', $config = array())
	{
		return JTable::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
	 *
	 * @since    1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_vpadvanceduser.customfield', 'customfield', array('control' => 'jform', 'load_data' => $loadData));

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

		return $form;
	}

	/**
	 * 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_vpadvanceduser.edit.customfield.data', array());

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

			$data = $this->item;
		}

		return $data;
	}

	/**
	 * Override JModelAdmin::preprocessForm to ensure the correct plugin group is loaded.
	 *
	 * @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
	 *
	 * @since   1.6
	 * @throws  Exception if there is an error in the form event.
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'content')
	{
		$name = '';
		
		if(is_object($data))
		{
			$name = $data->name;
		}
		elseif(is_array($data))
		{
			$name = $data['name'];
		}
		
		$core_fields = $this->getCoreFields();
		
		if($name != 'profile_picture')
		{
			$form->setFieldAttribute('type', 'disable_avatar', 1);
		}
		
		if(in_array($name, $core_fields))
		{
			$form->setFieldAttribute('label', 'readonly', true);
			$form->setFieldAttribute('name', 'readonly', true);
			$form->setFieldAttribute('type', 'readonly', true);
		}
		
		
		parent::preprocessForm($form, $data, $group);
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer  $pk  The id of the primary key.
	 *
	 * @return  mixed    Object on success, false on failure.
	 *
	 * @since    1.6
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			$item->custom_type = isset($item->params['custom_type']) ? (string) $item->params['custom_type'] : '';
		}

		return $item;
	}

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

		if(isset($data['params']) && is_array($data['params']) && isset($data['custom_type']))
		{
			$data['params']['custom_type'] = $data['custom_type'];
		}

		// Alter the label & name for save as copy
		if ($input->get('task') == 'save2copy')
		{
			$origTable = clone $this->getTable();
			$origTable->load($input->getInt('id'));

			if ($data['label'] == $origTable->label)
			{
				list($label, $name) = $this->generateNewLabel($data['label'], $data['name']);
				$data['label'] = $label;
				$data['name']  = $name;
			}
			elseif($data['name'] == $origTable->name)
			{
				$data['name'] = '';
			}

			$data['state'] = 0;
		}
		
		// Automatic handling of name when the field is empty
		if (in_array($input->get('task'), array('apply', 'save', 'save2new')) && (!isset($data['id']) || (int) $data['id'] == 0))
		{
			if (empty($data['name']))
			{
				$data['name'] = str_replace(' ', '_', $data['label']);
				$data['name'] = (string) preg_replace('/[^A-Z0-9_]/i', '', $data['name']);
				$data['name'] = @strtolower($data['name']);

				$table = JTable::getInstance('Customfield', 'VPAdvancedUserTable');

				if ($table->load(array('name' => $data['name'])))
				{
					$msg = JText::_('COM_VPADVANCEDUSER_SAVE_NAME_WARNING');
				}

				if($input->get('task') == 'save2new' && $data['type'] == 'avatar')
				{
					// Can not have multiple Avatar fields
					$data['type'] = 'text';
				}

				list($label, $name) = $this->generateNewLabel($data['label'], $data['name']);
				$data['name'] = $name;

				if (isset($msg))
				{
					JFactory::getApplication()->enqueueMessage($msg, 'warning');
				}
			}
		}
		
		return parent::save($data);
	}

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

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

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

		// Include the plugins for the save events.
		JPluginHelper::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;
				
				// Change the label and name
				list($label, $name) = $this->generateNewLabel($table->label, $table->name);
				$table->label = $label;
				$table->name  = $name;
				
				if($table->type == 'avatar')
				{
					// Can not have multiple Avatar fields
					$table->type = 'text';
				}
				
				// Disable the new field
				$table->state = 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;
	}

	/**
	 * Method to change the show state of one or more records.
	 *
	 * @param   string   $column   Table field name
	 * @param   array    &$pks     A list of the primary keys to change.
	 * @param   integer  $value    The value of the published state.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.0
	 */
	public function show($column, &$pks, $value = 1)
	{
		$dispatcher = JEventDispatcher::getInstance();
		$user       = JFactory::getUser();
		$table      = $this->getTable();
		$pks        = (array) $pks;
		$context    = $this->option . '.' . $this->name;

		// Include the plugins for the change of state event.
		JPluginHelper::importPlugin($this->events_map['change_state']);
		
		if(!property_exists($table, $column))
		{
			$this->setError('Invalid column name. Column does not exist in the database table.');
			return false;
		}
		
		// Access checks.
		foreach ($pks as $i => $pk)
		{
			if ($table->load($pk, true))
			{
				if (!$this->canEditState($table))
				{
					// Prune items that you can't change.
					unset($pks[$i]);
					JLog::add(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), JLog::WARNING, 'jerror');

					return false;
				}
			}
		}

		// Attempt to change the show state of the records.
		foreach ($pks as $i => $pk)
		{
			if ($table->load($pk, true))
			{
				// Set the new value against the column
				$table->$column = (int) $value;
				
				if (!$table->check())
				{
					$this->setError($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())
				{
					$this->setError($table->getError());
				}

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

		// Clear the component's cache
		$this->cleanCache();

		return true;
	}

	/**
	 * 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)
	{
		// Get list of core fields
		$coreFields = $this->getCoreFields();
		
		if(in_array($record->name, $coreFields))
		{
			// Can not delete core fields
			$label = JText::_($record->label);
			$this->setError(JText::sprintf('COM_VPADVANCEDUSER_ERROR_CAN_NOT_DELETE_CORE_FIELDS', $label));
			return false;
		}

		return JFactory::getUser()->authorise('core.delete', $this->option);
	}

	/**
	 * Method to change the label & name.
	 *
	 * @param   string   $label        The label.
	 * @param   string   $name         The name.
	 *
	 * @return  array  Contains the modified label and name.
	 *
	 * @since 1.0
	 */
	protected function generateNewLabel($label, $name)
	{
		// Alter the label & name
		$table = $this->getTable();

		while ($table->load(array('name' => $name)))
		{
			$label = JString::increment($label);
			$name  = JString::increment($name, 'dash');
			$name  = str_replace('-', '_', $name);
		}

		return array($label, $name);
	}
	
	public function getCoreFields()
	{
		$field_name = array(
		    'profile', 'profile_picture',
		    'firstname', 'lastname',
		    'gender', 'address',
		    'country', 'region',
		    'city', 'zip',
		    'dob', 'description',
		    'social_media', 'google_plus',
		    'facebook', 'twitter',
		    'tos', 'privacy'
		);
		
		return $field_name;
	}
}
