<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

// No direct access.
defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

class Djcatalog2Event extends Joomla\CMS\Plugin\CMSPlugin {
	
	public function __construct(&$subject, $config = array())
	{
		parent::__construct($subject, $config);
		
		// Since Joomla! 4
		if (method_exists($this, 'registerListeners')) {
			$this->registerListeners();
		}
	}
	
	public function onContentBeforeSave( $context, $table, $isNew ) {
		switch($context) {
			case 'com_djcatalog2.item' : {
				return $this->onItemBeforeSave($context, $table, $isNew);
				break;
			}
		}
	}
	
	public function onContentAfterSave( $context, $table, $isNew ) {
		switch($context) {
			case 'com_djcatalog2.item' : {
				return $this->onItemAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.category' : {
				return $this->onCategoryAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.producer' : {
				return $this->onProducerAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.producercategory' : {
				return $this->onProducerCategoryAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.field' : {
				return $this->onFieldAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.producerfield' : {
				return $this->onProducerFieldAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.userfield' : {
				return $this->onUserFieldAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.payment' : {
				return $this->onPaymentAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.delivery' : {
				return $this->onDeliveryAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.cartfield' : {
				return $this->onCartFieldAfterSave($context, $table, $isNew);
				break;
			}
			case 'com_djcatalog2.subscription' : {
				return $this->onSubscriptionAfterSave($context, $table, $isNew);
				break;
			}
		}
	}
	public function onContentAfterDelete( $context, $table) {
		switch($context) {
			case 'com_djcatalog2.item' : {
				return $this->onItemAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.category' : {
				return $this->onCategoryAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.producer' : {
				return $this->onProducerAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.producercategory' : {
				return $this->onProducerCategoryAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.field' : {
				return $this->onFieldAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.producerfield' : {
				return $this->onProducerFieldAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.userfield' : {
				return $this->onUserFieldAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.payment' : {
				return $this->onPaymentAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.delivery' : {
				return $this->onDeliveryAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.cartfield' : {
				return $this->onCartFieldAfterDelete($context, $table);
				break;
			}
			case 'com_djcatalog2.subscription' : {
				return $this->onSubscriptionAfterDelete($context, $table);
				break;
			}
		}
	}
	
	public function onItemBeforeSave( $context, $table, $isNew ) {
		$app = JFactory::getApplication();
		
		if ($app->input->getCmd('task') == 'import') {
			return true;
		}
		
		$model = JModelAdmin::getInstance('Item', 'Djcatalog2Model', array());
		if (!$isNew) {
			$attribs = $app->input->get('attribute',array(), 'array');
			if (!$model->validateAttributes($attribs, $table)) {
				$errors = $model->getErrors();
				foreach ($errors as $error) {
					$app->enqueueMessage($error,'error');
				}
				$table->setError(JText::_('JGLOBAL_VALIDATION_FORM_FAILED'));
				return false;
			}
		}
		
		$params = JComponentHelper::getParams('com_djcatalog2');
		
		if (!$isNew && $params->get('stock_notifications', false)) {
			$item = $model->getItem($table->id);
			if (!empty($item)) {
				$stockBefore = ['onstock'=> $item->onstock, 'stock' => $item->stock, 'combinations' => []];
				if (!empty($item->combinations)) {
					foreach($item->combinations as $combination) {
						if ($combination->stock > 0.0000) continue;
						$stockBefore['combinations'][$combination->id] = ['stock' => $combination->stock];
					}
				}
				
				if (count($stockBefore['combinations']) || $stockBefore['stock'] == 0.0000 || $stockBefore['onstock'] == 0){
					$app->setUserState('com_djcatalog2.item.stock_before.' . $item->id, $stockBefore);
				}
			}
		}
	}
	
	public function onItemAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$data		= $app->input->get('jform', array(), 'array');
		
		$task = $app->input->getCmd('task');
		
		// saving additional categories
		$db = JFactory::getDbo();
		
		if ($task == 'import') {
			if ($table->cat_id > 0) {
				$db->setQuery('DELETE FROM #__djc2_items_categories WHERE category_id=\''.$table->cat_id.'\' AND item_id=\''.$table->id.'\'');
				if ($db->execute()) {
					$db->setQuery('INSERT INTO #__djc2_items_categories (item_id, category_id) VALUES (\''.$table->id.'\', \''.$table->cat_id.'\')');
					$db->execute();
				}
			}
		} else {
			$db->setQuery('DELETE FROM #__djc2_items_categories WHERE item_id=\''.$table->id.'\'');
			if ($db->execute()) {
				if (!isset($data['categories'])) {
					$data['categories'] = array();
				}
				$data['categories'][] = $table->cat_id;
				if (!empty($data['categories'])) {
					ArrayHelper::toInteger($data['categories']);
					$data['categories'] = array_unique($data['categories']);
					foreach ($data['categories'] as $cat_id) {
						$db->setQuery('INSERT INTO #__djc2_items_categories (item_id, category_id) VALUES (\''.$table->id.'\', \''.$cat_id.'\')');
						$db->execute();
					}
				}
			}
		}
		if (!isset($data['group_id']) || !is_array($data['group_id'])) {
			$data['group_id'] = array();
		}
		$data['group_id'][] = 0;
		ArrayHelper::toInteger($data['group_id']);
		$data['group_id'] = array_unique($data['group_id']);
		
		if ($task == 'import') {
			$db->setQuery('DELETE FROM #__djc2_items_groups WHERE item_id=\''.$table->id.'\' AND group_id IN ('.implode(',', $data['group_id']).')');
		}
		else {
			$db->setQuery('DELETE FROM #__djc2_items_groups WHERE item_id=\''.$table->id.'\'');
		}
		if ($db->execute()) {
			foreach ($data['group_id'] as $group_id) {
				$db->setQuery('INSERT INTO #__djc2_items_groups (item_id, group_id) VALUES (\''.$table->id.'\', \''.$group_id.'\')');
				$db->execute();
			}
		}
		
		// saving images
		if (!DJCatalog2ImageHelper::saveImages('item',$table, $params, $isNew)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_SAVING_IMAGES'),'error');
		}
		
		// saving attachments
		if (!DJCatalog2FileHelper::saveFiles('item',$table, $params, $isNew)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_SAVING_FILES'),'error');
		}
		
		// saving videos
		if (!DJCatalog2VideoHelper::saveFiles('item',$table, $params, $isNew)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_SAVING_VIDEOS'),'error');
		}
		
		$model = JModelAdmin::getInstance('Item', 'Djcatalog2Model', array());
		
		// saving additional attributes
		$attribs = $app->input->get('attribute',array(), 'array');
		if (!$model->saveAttributes($attribs, $table)) {
			$app->enqueueMessage($model->getError(),'error');
		}
		
		// saving combinations
		$combinations = $app->input->get('combinations',array(), 'array');
		$hasCombinations = $app->input->getInt('hasCombinations');
		if ($hasCombinations == 1) {
			if (!$model->saveCombinations($combinations, $table, $isNew)) {
				$app->enqueueMessage($model->getError(),'error');
			}
		}
		$customisations = $app->input->get('customisations',array(), 'array');
		$hasCustomisations = $app->input->getInt('hasCustomisations');
		if ($hasCustomisations == 1) {
			if (!$model->saveCustomisations($customisations, $table, $isNew)) {
				$app->enqueueMessage($model->getError(),'error');
			}
		}
		
		if (isset($data['price_tiers'])) {
			$query = $db->getQuery(true);
			$query->delete('#__djc2_items_price_tiers')->where('item_id='.$table->id);
			$db->setQuery($query);
			$db->execute();
			
			if (is_array($data['price_tiers']) && count($data['price_tiers'])) {
				$quantities = array();
				foreach($data['price_tiers'] as $k=>$v) {
					$quantity = (int)$v['quantity'];
					$price = floatval($v['price']);
					
					if (!$quantity || $price <= 0.00) {
						continue;
					}
					
					if (array_key_exists($quantity, $quantities)) {
						continue;
					}
					
					$quantities[$quantity] = $price;
				}
				
				if (count($quantities)) {
					$query = $db->getQuery(true);
					$query->insert('#__djc2_items_price_tiers');
					$query->columns(array('item_id', 'quantity', 'price'));
					foreach($quantities as $quantity => $price) {
						$query->values($table->id.','.$quantity.','.$price);
					}
					$db->setQuery($query);
					$db->execute();
				}
			}
		}
		
		if ($task != 'import') {
			$query = $db->getQuery(true);
			$query->delete('#__djc2_labels_items')->where('item_id='.$table->id);
			$db->setQuery($query);
			$db->execute();
			
			if (isset($data['labels'])) {
				ArrayHelper::toInteger($data['labels']);
				
				if (is_array($data['labels']) && count($data['labels'])) {
					$query = $db->getQuery(true);
					$query->insert('#__djc2_labels_items');
					$query->columns(array('item_id', 'label_id'));
					foreach($data['labels'] as  $label_id) {
						$query->values($table->id.','.$label_id);
					}
					$db->setQuery($query);
					$db->execute();
				}
			}
		}
		
		if (!$isNew && $params->get('stock_notifications', false)) {
			$beforeState = $app->getUserState('com_djcatalog2.item.stock_before.' . $table->id);
			if (!empty($beforeState) && is_array($beforeState)) {
				$onStock = (bool)($table->onstock >= 2 || $table->onstock == 1 && $table->stock > 0.0000);
				$outStockBefore = (bool)($beforeState['onstock'] == 0 || ($beforeState['onstock'] == 1 && $beforeState['stock'] == 0.0000));
				
				$sentMain = $sentCombo = 0;
				if ($onStock && $outStockBefore) {
					$sentMain = $model->notifyStockUpdates($table->id, 'item', $table);
				}
				
				foreach($beforeState['combinations'] as $combination_id => $combination_stock) {
					
					$id_idx = false;
					foreach($combinations['id'] as $pos => $value) {
						if ($value == $combination_id) {
							$id_idx = $pos;
						}
					}
					if ($id_idx === false) continue;
					
					if (isset($combinations['stock']) && isset($combinations['stock'][$id_idx])) {
						if ($combinations['stock'][$id_idx] > 0.0000 && $combination_stock['stock'] == 0.0000) {
							$sentCombo = $model->notifyStockUpdates($combination_id, 'combination', $table);
						}
					}
				}
				
				if ($sentMain || $sentCombo) {
					$link = JRoute::_('index.php?option=com_djcatalog2&view=messages&filter_search=' . $table->name);
					$app->enqueueMessage(JText::sprintf('COM_DJCATALOG2_ON_STOCK_NOTIFICATIONS_HAVE_BEEN_SENT', $sentMain + $sentCombo, $link));
				}
			}
		}
		$app->setUserState('com_djcatalog2.item.stock_before.' . $table->id, null);
	}
	public function onItemAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		
		$db = JFactory::getDbo();
		$db->setQuery('DELETE FROM #__djc2_items_categories WHERE item_id=\''.$table->id.'\'');
		$db->execute();
		
		$db = JFactory::getDbo();
		$db->setQuery('DELETE FROM #__djc2_items_groups WHERE item_id=\''.$table->id.'\'');
		$db->execute();
		
		$db->setQuery('DELETE FROM #__djc2_items_related WHERE item_id=\''.$table->id.'\' OR related_item=\''.$table->id.'\'');
		$db->execute();
		
		$db->setQuery('DELETE FROM #__djc2_items_extra_fields_values_text WHERE item_id=\''.$table->id.'\'');
		$db->execute();
		
		$db->setQuery('DELETE FROM #__djc2_items_extra_fields_values_int WHERE item_id=\''.$table->id.'\'');
		$db->execute();
		
		$db->setQuery('DELETE FROM #__djc2_items_extra_fields_values_date WHERE item_id=\''.$table->id.'\'');
		$db->execute();
		
		if (!DJCatalog2ImageHelper::deleteImages('item',$table->id)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_DELETING_IMAGES'),'error');
		}
		if (!DJCatalog2FileHelper::deleteFiles('item',$table->id)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_DELETING_FILE'),'error');
		}
		if (!DJCatalog2VideoHelper::deleteFiles('item',$table->id)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_DELETING_VIDEO'),'error');
		}
		
		$db->setQuery('SELECT id FROM #__djc2_items_combinations WHERE item_id=\''.$table->id.'\'');
		$combination_ids = $db->loadColumn();
		if (count($combination_ids) > 0) {
			$db->setQuery('DELETE FROM #__djc2_items_combinations WHERE item_id=\''.$table->id.'\'');
			$db->execute();
			
			$db->setQuery('DELETE FROM #__djc2_items_combinations_fields WHERE combination_id IN ('.implode(',', $combination_ids).')');
			$db->execute();
			
			foreach ($combination_ids as $combinationId) {
				DJCatalog2ImageHelper::deleteImages('combination', $combinationId);
			}
		}
		
		$db->setQuery('DELETE FROM #__djc2_items_customisations WHERE item_id=\''.$table->id.'\'');
		$db->execute();
	}
	public function onCategoryAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		if (!DJCatalog2ImageHelper::saveImages('category',$table, $params, $isNew)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_SAVING_IMAGES'),'error');
		}
	}
	public function onCategoryAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		if (!DJCatalog2ImageHelper::deleteImages('category',$table->id)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_DELETING_IMAGES'),'error');
		}
	}
	public function onProducerAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		
		$model = JModelAdmin::getInstance('Producer', 'Djcatalog2Model', array());
		
		// saving additional attributes
		$attribs = $app->input->get('attribute',array(), 'array');
		if (!$model->saveAttributes($attribs, $table)) {
			$app->enqueueMessage($model->getError(),'error');
		}
		
		if (!DJCatalog2ImageHelper::saveImages('producer',$table, $params, $isNew)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_SAVING_IMAGES'),'error');
		}
	}
	public function onProducerAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$db = JFactory::getDbo();
		
		$db->setQuery('DELETE FROM #__djc2_producers_extra_fields_values_text WHERE item_id=\''.$table->id.'\'');
		$db->execute();
		
		$db->setQuery('DELETE FROM #__djc2_producers_extra_fields_values_int WHERE item_id=\''.$table->id.'\'');
		$db->execute();
		
		$db->setQuery('DELETE FROM #__djc2_producers_extra_fields_values_date WHERE item_id=\''.$table->id.'\'');
		$db->execute();
		
		if (!DJCatalog2ImageHelper::deleteImages('producer',$table->id)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_DELETING_IMAGES'),'error');
		}
	}
	public function onProducerCategoryAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		if (!DJCatalog2ImageHelper::saveImages('producercategory',$table, $params, $isNew)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_SAVING_IMAGES'),'error');
		}
	}
	public function onProducerCategoryAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		if (!DJCatalog2ImageHelper::deleteImages('producercategory',$table->id)) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_ERROR_DELETING_IMAGES'),'error');
		}
	}
	public function onFieldAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$values = ($app->input->get('fieldtype',array(),'array'));
		$model = JModelAdmin::getInstance('Field', 'Djcatalog2Model', array());
		if (!$model->saveOptions($values, $table, $isNew)) {
			$app->enqueueMessage($model->getError(),'error');
		}
	}
	public function onFieldAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$model = JModelAdmin::getInstance('Field', 'Djcatalog2Model', array());
		if (!$model->deleteOptions($table)) {
			$app->enqueueMessage($model->getError(),'error');
		}
	}
	
	
	public function onPaymentAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$db = JFactory::getDbo();
		$data		= $app->input->get('jform', array(), 'array');
		
		$task = $app->input->getCmd('task');
		
		$db->setQuery('DELETE FROM #__djc2_deliveries_payments WHERE payment_id=\''.$table->id.'\'');
		if ($db->execute()) {
			if (!empty($data['deliveries'])) {
				ArrayHelper::toInteger($data['deliveries']);
				$data['deliveries'] = array_unique($data['deliveries']);
				foreach ($data['deliveries'] as $delivery_id) {
					$db->setQuery('INSERT INTO #__djc2_deliveries_payments (payment_id, delivery_id) VALUES (\''.$table->id.'\', \''.$delivery_id.'\')');
					$db->execute();
				}
			}
		}
		
		$db->setQuery('DELETE FROM #__djc2_payments_currencies WHERE payment_id=\''.$table->id.'\'');
		if ($db->execute()) {
			if (!empty($data['currencies'])) {
				ArrayHelper::toInteger($data['currencies']);
				$data['currencies'] = array_unique($data['currencies']);
				foreach ($data['currencies'] as $currency_id) {
					$db->setQuery('INSERT INTO #__djc2_payments_currencies (payment_id, currency_id) VALUES (\''.$table->id.'\', \''.$currency_id.'\')');
					$db->execute();
				}
			}
		}
	}
	
	public function onPaymentAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		
		$db = JFactory::getDbo();
		$db->setQuery('DELETE FROM #__djc2_deliveries_payments WHERE payment_id=\''.$table->id.'\'');
		$db->execute();
		
		$db = JFactory::getDbo();
		$db->setQuery('DELETE FROM #__djc2_payments_currencies WHERE payment_id=\''.$table->id.'\'');
		$db->execute();
	}
	
	public function onDeliveryAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$db = JFactory::getDbo();
		$data		= $app->input->get('jform', array(), 'array');
		
		$task = $app->input->getCmd('task');
		
		$db->setQuery('DELETE FROM #__djc2_deliveries_gauges WHERE delivery_id=\''.$table->id.'\'');
		if ($db->execute()) {
			if (!empty($data['gauges'])) {
				ArrayHelper::toInteger($data['gauges']);
				$data['gauges'] = array_unique($data['gauges']);
				foreach ($data['gauges'] as $gauges_id) {
					$db->setQuery('INSERT INTO #__djc2_deliveries_gauges (delivery_id, gauge_id) VALUES (\''.$table->id.'\', \''.$gauges_id.'\')');
					$db->execute();
				}
			}
		}
	}
	
	public function onDeliveryAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		
		$db = JFactory::getDbo();
		$db->setQuery('DELETE FROM #__djc2_deliveries_gauges WHERE delivery_id=\''.$table->id.'\'');
		$db->execute();
	}
	
	public function onCartFieldAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$values = ($app->input->get('fieldtype',array(),'array'));
		$model = JModelAdmin::getInstance('CartField', 'Djcatalog2Model', array());
		if (!$model->saveOptions($values, $table, $isNew)) {
			$app->enqueueMessage($model->getError(),'error');
		}
	}
	public function onCartFieldAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$model = JModelAdmin::getInstance('CartField', 'Djcatalog2Model', array());
		if (!$model->deleteOptions($table)) {
			$app->enqueueMessage($model->getError(),'error');
		}
	}
	public function onProducerFieldAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$values = ($app->input->get('fieldtype',array(),'array'));
		$model = JModelAdmin::getInstance('Producerfield', 'Djcatalog2Model', array());
		if (!$model->saveOptions($values, $table, $isNew)) {
			$app->enqueueMessage($model->getError(),'error');
		}
	}
	public function onProducerFieldAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$model = JModelAdmin::getInstance('Producerfield', 'Djcatalog2Model', array());
		if (!$model->deleteOptions($table)) {
			$app->enqueueMessage($model->getError(),'error');
		}
	}
	public function onUserFieldAfterSave( $context, $table, $isNew ) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$values = ($app->input->get('fieldtype',array(),'array'));
		$model = JModelAdmin::getInstance('Userfield', 'Djcatalog2Model', array());
		if (!$model->saveOptions($values, $table, $isNew)) {
			$app->enqueueMessage($model->getError(),'error');
		}
	}
	public function onUserFieldAfterDelete( $context, $table) {
		$params = JComponentHelper::getParams( 'com_djcatalog2' );
		$app = JFactory::getApplication();
		$model = JModelAdmin::getInstance('Userfield', 'Djcatalog2Model', array());
		if (!$model->deleteOptions($table)) {
			$app->enqueueMessage($model->getError(),'error');
		}
	}
	
	public function onSubscriptionAfterSave($context, $table, $isNew) {
		$app = JFactory::getApplication();
		$db = JFactory::getDbo();
		$date = JFactory::getDate();
		
		// get current user groups
		$db->setQuery('SELECT group_id FROM #__user_usergroup_map WHERE user_id='.$table->user_id);
		$groups = $db->loadColumn();
		
		$granted_groups = [];
		if (is_array($table->granted_usergroups)) {
			$granted_groups = $table->granted_usergroups;
		}
		else if ($table->granted_usergroups && $table->granted_usergroups != '[]'){
			$granted_groups = json_decode($table->granted_usergroups, true);
		}
		if (empty($granted_groups)) return;
		$granted_groups = array_unique($granted_groups);
		
		// update granted usergroup
		// check status and expire date
		if($table->status==1 && intval($table->expire_date) && JFactory::getDate($table->expire_date)->toUnix() > $date->toUnix()) {
			// grant usergroup if user is not already assigned to this group
			foreach($granted_groups as $granted_group) {
				if(!in_array($granted_group, $groups)) {
					$db->setQuery('INSERT INTO #__user_usergroup_map (user_id, group_id) VALUES ('.$table->user_id.','.$granted_group.')');
					if (!$db->execute()) {
						$app->enqueueMessage($db->getErrorMsg(), 'error');
					}
				}
			}
		} else {
			// remove user from this usergroup if there is no more active subscriptions related with this group
			foreach($granted_groups as $granted_group) {
				if(in_array($table->granted_usergroup, $groups)) {
					$db->setQuery('SELECT count(id) FROM #__djc2_subscriptions WHERE id!='.$table->id.' AND status=1 AND user_id='.$table->user_id.' AND granted_usergroups LIKE '.$db->quote('%["' . $granted_group . '"]%').' AND expire_date > '.$db->quote($date->toSql()));
					$count = $db->loadResult();
					if(!$count) { // no active subscriptions
						// remove user-group assigments
						$db->setQuery('DELETE from #__user_usergroup_map WHERE user_id='.$table->user_id .' AND group_id='.$granted_group);
						if(!$db->execute()) {
							$app->enqueueMessage($db->getErrorMsg(), 'error');
							die($db->getErrorMsg());
						}
					}
				}
			}
		}
	}
	
	public function onSubscriptionAfterDelete($context, $table) {
		
		$app = JFactory::getApplication();
		$db = JFactory::getDbo();
		$date = JFactory::getDate();
		
		// get current user groups
		$db->setQuery('SELECT group_id FROM #__user_usergroup_map WHERE user_id='.$table->user_id);
		$groups = $db->loadColumn();
		
		$granted_groups = [];
		if (is_array($table->granted_usergroups)) {
			$granted_groups = $table->granted_usergroups;
		}
		else if ($table->granted_usergroups && $table->granted_usergroups != '[]'){
			$granted_groups = json_decode($table->granted_usergroups, true);
		}
		if (empty($granted_groups)) return;
		$granted_groups = array_unique($granted_groups);
		
		// update granted usergroup
		foreach($granted_groups as $granted_group) {
			if(in_array($granted_group, $groups)) {
				// remove user from this usergroup if there is no more active subscriptions related with this group
				$db->setQuery('SELECT count(id) FROM #__djc2_subscriptions WHERE id!='.$table->id.' AND status=1 AND user_id='.$table->user_id.' AND granted_usergroups LIKE '.$db->quote('%["' . $granted_group . '"]%').' AND expire_date > '.$db->quote($date->toSql()));
				$count = $db->loadResult();
				if(!$count) { // no active subscriptions
					// remove user-group assigments
					$db->setQuery('DELETE from #__user_usergroup_map WHERE user_id='.$table->user_id .' AND group_id='.$granted_group);
					if(!$db->execute()) {
						$app->enqueueMessage($db->getErrorMsg(), 'error');
						die($db->getErrorMsg());
					}
				}
			}
		}
	}
}