<?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
 *
 */
defined('_JEXEC') or die( 'Restricted access' );
use Joomla\CMS\MVC\Controller\AdminController;
use Joomla\Utilities\ArrayHelper;
use Joomla\CMS\Language\Text;

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


class Djcatalog2ControllerItems extends AdminController
{
	static $exclude_columns = array('sections', 'sections_source', 'params');
	
	public function __construct($config = array())
	{
		parent::__construct($config);
		$this->registerTask('unfeatured',	'featured');
		$this->registerTask('inavailable',	'available');
		$this->registerTask('listing', 'publish');
		$this->registerTask('unlisting', 'publish');
	}
	
	public function getModel($name = 'Item', $prefix = 'Djcatalog2Model', $config = array())
	{
		$model = parent::getModel($name, $prefix, array('ignore_request' => true));
		return $model;
	}
	function featured()
	{
		// Check for request forgeries
		JSession::checkToken() or die(Text::_('JINVALID_TOKEN'));
		
		$app = JFactory::getApplication();
		
		$session	= JFactory::getSession();
		$registry	= $session->get('registry');

		// Get items to publish from the request.
		$cid	= $app->input->get('cid', array(), 'array');
		$task 	= $this->getTask();
		$value = ($task == 'featured') ? 1 : 0;

		if (empty($cid) ) {
			throw new \Exception(Text::_($this->text_prefix.'_NO_ITEM_SELECTED'), 500);
		}
		else {
			// Get the model.
			$model = $this->getModel();

			// Make sure the item ids are integers
			ArrayHelper::toInteger($cid);

			// Publish the items.
			if (!$model->changeFeaturedState($cid, $value)) {
				throw new Joomla\CMS\MVC\View\GenericDataException(implode("\n", $model->getErrors()), 500);
			}
		}
		$extension = $app->input->get('extension', null, 'cmd');
		$extensionURL = ($extension) ? '&extension=' . $app->input->get('extension', null, 'cmd') : '';
		$this->setRedirect(JRoute::_('index.php?option='.$this->option.'&view='.$this->view_list.$extensionURL, false));
	}
	
	function available()
	{
		// Check for request forgeries
		JSession::checkToken() or die(Text::_('JINVALID_TOKEN'));
	
		$app = JFactory::getApplication();
	
		$session	= JFactory::getSession();
		$registry	= $session->get('registry');
	
		// Get items to publish from the request.
		$cid	= $app->input->get('cid', array(), 'array');
		$task 	= $this->getTask();
		$value = ($task == 'available') ? 1 : 0;
	
		if (empty($cid)) {
			throw new Joomla\CMS\MVC\View\GenericDataException(Text::_($this->text_prefix.'_NO_ITEM_SELECTED'), 500);
		}
		else {
			// Get the model.
			$model = $this->getModel();
	
			// Make sure the item ids are integers
			ArrayHelper::toInteger($cid);
	
			// Publish the items.
			if (!$model->changeAvailableState($cid, $value)) {
				throw new Joomla\CMS\MVC\View\GenericDataException(implode("\n", $model->getErrors()), 500);
			}
		}
		$extension = $app->input->get('extension', null, 'cmd');
		$extensionURL = ($extension) ? '&extension=' . $app->input->get('extension', null, 'cmd') : '';
		$this->setRedirect(JRoute::_('index.php?option='.$this->option.'&view='.$this->view_list.$extensionURL, false));
	}
	
	public function publish()
	{
		// Check for request forgeries
		$this->checkToken();
		
		// Get items to publish from the request.
		$cid = $this->input->get('cid', array(), 'array');
		$data = array('publish' => 1, 'unpublish' => 0, 'archive' => 2, 'trash' => -2, 'report' => -3, 'listing' => 1, 'unlisting' => 3);
		$task = $this->getTask();
		$value = ArrayHelper::getValue($data, $task, 0, 'int');

		if (empty($cid))
		{
			\JLog::add(Text::_($this->text_prefix . '_NO_ITEM_SELECTED'), \JLog::WARNING, 'jerror');
		}
		else
		{
			// Get the model.
			$model = $this->getModel();
			
			// Make sure the item ids are integers
			$cid = ArrayHelper::toInteger($cid);
			
			// Publish the items.
			try
			{
				$model->publish($cid, $value);
				$errors = $model->getErrors();
				$ntext = null;
				
				if ($value === 1)
				{
					if ($errors)
					{
						\JFactory::getApplication()->enqueueMessage(Text::plural($this->text_prefix . '_N_ITEMS_FAILED_PUBLISHING', count($cid)), 'error');
					}
					else
					{
						$ntext = $this->text_prefix . '_N_ITEMS_PUBLISHED';
					}
				}
				elseif ($value === 0)
				{
					$ntext = $this->text_prefix . '_N_ITEMS_UNPUBLISHED';
				}
				elseif ($value === 2)
				{
					$ntext = $this->text_prefix . '_N_ITEMS_ARCHIVED';
				}
				else
				{
					$ntext = $this->text_prefix . '_N_ITEMS_TRASHED';
				}
				
				if ($ntext !== null)
				{
					$this->setMessage(Text::plural($ntext, count($cid)));
				}
			}
			catch (\Exception $e)
			{
				$this->setMessage($e->getMessage(), 'error');
			}
		}
		
		$extension = $this->input->get('extension');
		$extensionURL = $extension ? '&extension=' . $extension : '';
		$this->setRedirect(\JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $extensionURL, false));
	}
	
	public function export_selected() {
		// Check for request forgeries
		JSession::checkToken() or die(Text::_('JINVALID_TOKEN'));
		
		$app = JFactory::getApplication();
		
		// Get items to publish from the request.
		$cid	= $app->input->get('cid', array(), 'array');
		
		if (empty($cid)) {
			throw new Joomla\CMS\MVC\View\GenericDataException(Text::_( 'COM_DJCATALOG2_NO_ITEM_SELECTED' ), 500);
		}
		else {
			return $this->export_filtered($cid);
		}
	}
	
	public function export_filtered($cid = array()) {
		
		if (!JSession::checkToken('post') && !JSession::checkToken('get')) {
			jexit( 'COM_DJCATALOG2_INVALID_TOKEN' );
		}
		$app = JFactory::getApplication();
		$task 	= $this->getTask();
		
		$path = JPATH_ROOT.'/media/djcatalog2/export/item';
		if (!JFolder::exists($path)) {
			JFolder::create($path);
		}
		
		if (!is_writable($path)) {
			$this->setRedirect( 'index.php?option=com_djcatalog2&view=items', Text::_('COM_DJCATALOG2_FOLDER_NOT_WRITABLE').' '.$path, 'error' );
			return false;
		}
		
		$enclosure = "\"";
		$separator = ",";
		$newline = PHP_EOL;

		$user = JFactory::getUser();
		if (!$user->authorise('core.manage', 'com_djcatalog2')){
			$this->setError(Text::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'));
			$this->setMessage($this->getError(), 'error');
			$this->setRedirect( 'index.php?option=com_djcatalog2&view=items' );
			return false;
		}
		
		jimport('joomla.application.component.modellist');
		
		$model = JModelList::getInstance('Items', 'Djcatalog2Model', array('ignore_request'=>true));

		$state = $model->getState();
		$context = 'com_djcatalog2.items';
		
		$start = $app->input->get('start', 0);
		$limit = 1000;
		
		$model->setState('list.select', 'a.*, c.name as category_name, p.name as producer_name, uc.name AS author');
		if ($task == 'export_selected' && count($cid) > 0) {
			$limit = $start = 0;
			ArrayHelper::toInteger($cid);
			$model->setState('filter.ids', implode(',',$cid));
		} else {
			$search = $model->getUserStateFromRequest($context.'.filter.search', 'filter_search');
			$model->setState('filter.search', $search);
			
			$published = $model->getUserStateFromRequest($context.'.filter.published', 'filter_published', '');
			$model->setState('filter.published', $published);
			
			$category = $model->getUserStateFromRequest($context.'.filter.category', 'filter_category', '');
			$model->setState('filter.category', $category);
			
			$producer = $model->getUserStateFromRequest($context.'.filter.producer', 'filter_producer', '');
			$model->setState('filter.producer', $producer);
		}
		
		$model->setState('list.start', $start);
		$model->setState('list.limit', $limit);
		
		$params = JComponentHelper::getParams('com_djcatalog2');
		$model->setState('params', $params);
		
		$items = $model->getItems();
		
		$db = JFactory::getDbo();
		$db->setQuery('SHOW COLUMNS FROM #__djc2_items');
		$columns = $db->loadColumn(0);
		$columns = array_merge($columns, array('category_name', 'producer_name', 'author'));
		
		
		foreach($columns as $key => $column) {
			if (in_array($column, static::$exclude_columns)) {
				unset($columns[$key]);
			}
		}
		
		if (true) {
			$db->setQuery('SELECT concat("_", alias) FROM #__djc2_items_extra_fields ORDER BY group_id asc, ordering asc');
			$e_fields = $db->loadColumn();
			$columns = array_merge($columns, $e_fields);
		}
		
		$filename = $app->input->get('export_file', 'product-export-'.date("Y-m-d_H-i-s").'.csv', 'raw');
		
		$fp = fopen($path.'/'.$filename, 'a');
		if (!empty($columns) && (!$start || $start == 0)) {
			fputcsv($fp, $columns, $separator, $enclosure);
		}
		
		foreach ($items as $id => $item) {
           
           $itemRow = array();
           
           foreach($columns as $colname) {
           	
           	if (!empty($items[$id]->$colname)) {
           		if (is_array($items[$id]->$colname)) {
           			$items[$id]->$colname = implode(', ',$items[$id]->$colname);
           		}
           		$itemRow[$colname] = $items[$id]->$colname;
           	}
           	 
           	if (!isset($itemRow[$colname])) {
           		$itemRow[$colname] = '';
           	}
           }
           
           fputcsv($fp, $itemRow, $separator, $enclosure);
        }
        
		fclose($fp);
		
		$pagination = $model->getPagination();
		
		$total = $pagination->pagesTotal;
		$current = $pagination->pagesCurrent;
		
		if ($total > $current) {
			header("refresh: 0; url=".JURI::base().'index.php?option=com_djcatalog2&task=items.export_filtered&start='.($start+=$limit).'&export_file='.$filename.'&'.JSession::getFormToken().'=1');
			echo '<p>'.$current.' / '.$total.'</p>';
		} else {
			//header("refresh: 0; url=".JURI::base().'index.php?option=com_djcatalog2&view=items');
			$file_link = '<a href="'.JRoute::_('index.php?option=com_djcatalog2&task=download_file&path='.base64_encode('media/djcatalog2/export/item/'.$filename)).'">'.$filename.'</a>';
			$this->setRedirect( 'index.php?option=com_djcatalog2&view=items', Text::_('COM_DJCATALOG2_EXPORT_SUCCESFULL').' '.$file_link );
		}
		
		return true;
	}
	public function import() {
		if (!JSession::checkToken('post') && !JSession::checkToken('get')) {
			jexit( 'COM_DJCATALOG2_INVALID_TOKEN' );
		}
	
		require_once(JPATH_ROOT.'/administrator/components/com_djcatalog2/helpers/import.php');
	
		$app = JFactory::getApplication();
		$model = $this->getModel('item');
		$files = $app->input->files;
		$db = JFactory::getDbo();
		$user = JFactory::getUser();
		$date = JFactory::getDate();
	
	
		$file = $files->get('csvfile');
		
		$enclosure = ($app->input->get('enclosure', 0) == 0) ? "\"" : "'";
		$separator = ($app->input->get('separator', 0) == 0) ? "," : ";";
	
		$defaults = array();
		$defaults['cat_id'] = (int)$app->input->get('cat_id', 0);
		$defaults['producer_id'] = (int)$app->input->get('producer_id', 0);
		$defaults['group_id'] = (int)$app->input->get('group_id', 0);
		$defaults['price'] = $app->input->get('price', 0.0);
		$defaults['special_price'] = $app->input->get('special_price', 0.0);
		$defaults['published'] = $app->input->get('published', 0);
		$defaults['created_by'] = $app->input->get('created_by', $user->id);
		$defaults['created'] = $app->input->get('created',  $date->toSql());
		
		$query = $db->getQuery(true)
			->select('id')
			->from($db->quoteName('#__viewlevels') . ' AS a')
			->group('a.id, a.title, a.ordering')
			->order('a.ordering ASC');
		
		$db->setQuery($query);
		$defaultAccess = $db->loadResult();
		$defaults['access'] = $app->input->get('access', $defaultAccess);
	
		if ($defaults['cat_id'] > 0) {
			$db->setQuery('select count(*) from #__djc2_categories where id ='. $defaults['cat_id']);
			$result = (bool)$db->loadResult();
			if ($result == false ){
				$defaults['cat_id'] = 0;
			}
		}
		if ($defaults['producer_id'] > 0) {
			$db->setQuery('select count(*) from #__djc2_producers where id ='. $defaults['producer_id']);
			$result = (bool)$db->loadResult();
			if ($result == false ){
				$defaults['producer_id'] = 0;
			}
		}
		if ($defaults['group_id'] > 0) {
			$db->setQuery('select count(*) from #__djc2_items_extra_fields_groups where id ='. $defaults['group_id']);
			$result = (bool)$db->loadResult();
			if ($result == false ){
				$defaults['group_id'] = 0;
			}
		}
	
		$messages = array();
		
		if(!empty($file)) {
			if(!$file['error']) {
				$tempname = $file['tmp_name'];
				
				if (mb_check_encoding(file_get_contents($file['tmp_name']), 'UTF-8') == false) {
					$this->setRedirect(JRoute::_('index.php?option=com_djcatalog2&view=import', false), Text::_('COM_DJCATALOG2_ERROR_INVALID_ENCODING'), 'error');
					return false;
				}
				
				$rows = Djcatalog2ImportHelper::parseCSV(realpath($tempname), $separator, $enclosure);
				if (!empty($rows)) {
					$messages = Djcatalog2ImportHelper::storeRecords($rows, $model, 'item', $defaults);
				}
			}
		}
		
		foreach($messages as $type => $arr) {
			if (!empty($arr) && is_array($arr)){
				foreach($arr as $message) {
					$app->enqueueMessage($message, $type);
				}
			}
		}
		$this->setRedirect(JRoute::_('index.php?option=com_djcatalog2&view=import', false));
		return true;
	}
	
	function geocode()
	{
		// Check for request forgeries
		JSession::checkToken() or die(Text::_('JINVALID_TOKEN'));
	
		$app = JFactory::getApplication();
	
		$session	= JFactory::getSession();
		$registry	= $session->get('registry');
	
		// Get items to publish from the request.
		$cid	= $app->input->get('cid', array(), 'array');
		$task 	= $this->getTask();
		
		if (empty($cid)) {
			throw new Joomla\CMS\MVC\View\GenericDataException(JText::_( 'COM_DJCATALOG2_NO_ITEM_SELECTED' ), 500);
		}
		else {
			// Get the model.
			$model = $this->getModel();
	
			// Make sure the item ids are integers
			ArrayHelper::toInteger($cid);
	
			// Publish the items.
			if (!$model->geocode($cid)) {
				throw new Joomla\CMS\MVC\View\GenericDataException(implode("\n", $model->getErrors()), 500);
			}
		}
		$extension = $app->input->get('extension', null, 'cmd');
		$extensionURL = ($extension) ? '&extension=' . $app->input->get('extension', null, 'cmd') : '';
		$this->setRedirect(JRoute::_('index.php?option='.$this->option.'&view='.$this->view_list.$extensionURL, false));
	}
	
	/*
	public function geocode() {
		if (!JSession::checkToken('post') && !JSession::checkToken('get')) {
			jexit( 'COM_DJCATALOG2_INVALID_TOKEN' );
		}
	
		$app = JFactory::getApplication();
		$model = $this->getModel();
		$db = JFactory::getDbo();
	
		$limit = 2;
	
		$db->setQuery('select id from #__djc2_items where latitude = 0.000000000000000 OR longitude = 0.000000000000000 OR latitude IS NULL or longitude is NULL order by id asc');
		$items = $db->loadColumn();
	
		if (count($items) == 0) {
			$this->setRedirect( 'index.php?option=com_djcatalog2&view=items', Text::_('COM_DJCATALOG2_GEOCODE_COMPLETE'));
			return true;
		}
	
		$messages = array('message'=>array(), 'error'=>array());
	
		if (count($items) < $limit) {
			$limit = count($items);
		}
	
		for ($i = 0; $i < $limit; $i++) {
			$row = $model->getItem($items[$i]);
			usleep(150000);
			if (!$model->geocode($row)) {
				$messages['error'][] = Text::_('COM_DJCATALOG2_GEOCODE_ERROR_ROW').': ['.$items[$i].'] '.$model->getError();
				continue;
			}
		}
	
		$db->setQuery('select count(*) from #__djc2_items where latitude = 0.000000000000000 OR longitude = 0.000000000000000 OR latitude IS NULL or longitude is NULL ');
		$left = $db->loadResult();
	
		$messages['message'][] = Text::sprintf('COM_DJCATALOG2_GEOCODE_ITEMS_LEFT', $left);
	
		foreach($messages as $type => $arr) {
			if (!empty($arr)){
				foreach($arr as $message) {
					$app->enqueueMessage($message, $type);
				}
			}
		}
	
		$this->setRedirect( 'index.php?option=com_djcatalog2&view=items');
		return true;
	} */
	
	public function set_prices() {
		// Check for request forgeries
		JSession::checkToken() or die(Text::_('JINVALID_TOKEN'));
		$app = JFactory::getApplication();
		$db = JFactory::getDbo();
		$user = JFactory::getUser();
		
		if (!$user->authorise('djcatalog2.admin.prices', 'com_djcatalog2') && !$user->authorise('djcatalog2.admin.catalogue'))
		{
			throw new JAccessExceptionNotallowed(Text::_('JERROR_ALERTNOAUTHOR'), 403);
		}

		$prices = $app->input->get('djc_prices', array(), 'array');
		$target = $app->input->get('target', 'items');
		
		if ($target != 'items' && $target != 'combinations') {
			$this->setRedirect( 'index.php?option=com_djcatalog2&view=prices');
			return true;
		}
		
		$rows = array();
		
		if (!empty($prices)) {
			foreach ($prices as $item_id => $price) {
				$row = new stdClass();
				
				$row->price = floatval($price['new']);
				$row->stock = $price['stock'];
				if (isset($price['onstock'])) {
					$row->onstock = $price['onstock'];
				}
				
				$row->length = $price['length'];
				$row->width = $price['width'];
				$row->height = $price['height'];
				if (isset($price['dimensions_unit'])) {
					$row->dimensions_unit = $price['dimensions_unit'];
				}
				
				$row->weight = $price['weight'];
				if (isset($price['weight_unit'])) {
					$row->weight_unit = $price['weight_unit'];
				}
				
				$row->id = $item_id;
				$row->available = $price['available'];
				
				$rows[] = $row;
			}
		}
		
		$group = (int)$app->input->get('filter_customergroup', 0);
	
		if (!empty($rows)) {
			foreach ($rows as $item) {
				if ($group  > 0) {
					if ($target == 'items') {
						$db->setQuery('select id from #__djc2_prices where item_id='.$item->id.' and group_id ='.$group);
					} else if ($target == 'combinations') {
						$db->setQuery('select id from #__djc2_combination_prices where combination_id='.$item->id.' and group_id ='.$group);
					}
					
					$price_id = $db->loadResult();
					$price_item = new stdClass();
					$price_item->id = $price_id;
					
					if ($target == 'items') {
						$price_item->item_id = $item->id;
					} else if ($target == 'combinations') {
						$price_item->combination_id = $item->id;
					}
					
					$price_item->group_id = $group;
					$price_item->price = $item->price;
					$price_item->available = $item->available;
					
					$objName = '#__djc2_prices';
					if ($target == 'combinations') {
						$objName = '#__djc2_combination_prices';
					}
	
					if ($price_id > 0) {
						if (!$db->updateObject($objName, $price_item, 'id', false)) {
							$app->enqueueMessage($db->getErrorMsg(), 'error');
						}
					} else {
						if (!$db->insertObject($objName, $price_item)) {
							$app->enqueueMessage($db->getErrorMsg(), 'error');
						}
					}
				} else {
					$objName = '#__djc2_items';
					if ($target == 'combinations') {
						unset($row->available);
						$objName = '#__djc2_items_combinations';
					} else {
						if ($row->available == -1) {
							unset($row->available);
						}
					}
					
					if (!$db->updateObject($objName, $item, 'id', false)) {
						$app->enqueueMessage($db->getErrorMsg(), 'error');
					}
				}
			}
		}
	
		$this->setRedirect( 'index.php?option=com_djcatalog2&view=prices', Text::_('COM_DJCATALOG2_PRICES_UPDATED'));
	
		return true;
	}
	
	public function import_prices() {
		if (!JSession::checkToken('post') && !JSession::checkToken('get')) {
			jexit( 'COM_DJCATALOG2_INVALID_TOKEN' );
		}
		
		$user = JFactory::getUser();
		if (!$user->authorise('djcatalog2.admin.prices', 'com_djcatalog2') && !$user->authorise('djcatalog2.admin.catalogue'))
		{
			throw new JAccessExceptionNotallowed(Text::_('JERROR_ALERTNOAUTHOR'), 403);
		}
		
		require_once(JPATH_ROOT.'/administrator/components/com_djcatalog2/helpers/import.php');
		
		$app = JFactory::getApplication();
		$model = $this->getModel('item');
		$files = $app->input->files;
		$db = JFactory::getDbo();
		$user = JFactory::getUser();
		$date = JFactory::getDate();
		
		
		$file = $files->get('csvfile');
		
		$enclosure = ($app->input->get('enclosure', 0) == 0) ? "\"" : "'";
		$separator = ($app->input->get('separator', 0) == 0) ? "," : ";";
		
		$defaults = array();
		$defaults['group_id'] = (int)$app->input->get('group_id', 0);
		
		if ($defaults['group_id'] > 0) {
			$db->setQuery('select count(*) from #__djc2_customer_groups where id ='. $defaults['group_id']);
			$result = (bool)$db->loadResult();
			if ($result == false ){
				$defaults['group_id'] = 0;
			}
		}
		
		$inserted = 0;
		$updated = 0;
		$ignored = 0;
		$failed = 0;
		
		$messages = array('info'=>array(), 'warning' => array(), 'error'=>array());
		
		if(!empty($file)) {
			if(!$file['error']) {
				$tempname = $file['tmp_name'];
				
				if (mb_check_encoding(file_get_contents($file['tmp_name']), 'UTF-8') == false) {
					$this->setRedirect(JRoute::_('index.php?option=com_djcatalog2&view=import', false), Text::_('COM_DJCATALOG2_ERROR_INVALID_ENCODING'), 'error');
					return false;
				}
				
				$rows = Djcatalog2ImportHelper::parseCSV(realpath($tempname), $separator, $enclosure);
				$prices = array();
				foreach ($rows as $row) {
					if (empty($row['sku']) && empty($row['id'])) {
						$ignored++;
						continue;
					}
					if (!isset($row['group_id']) || (int)$row['group_id'] == 0) {
						$row['group_id'] = $defaults['group_id'];
					}
					
					$row['price'] = floatval(str_replace(',', '.', $row['price']));
					
					$item_ids = array();
					if (!empty($row['sku'])) {
						$db->setQuery('select id from #__djc2_items WHERE sku LIKE '.$db->quote(trim($row['sku'])));
						$item_ids = $db->loadColumn();
					} else if (!empty($row['id'])) {
						$item_ids[] = $row['id'];
					}
					
					if (count($item_ids)) {
						foreach($item_ids as $item_id) {
							$prices[] = array('item_id' => $item_id, 'group_id' => $row['group_id'], 'price' => $row['price']);
						}
					} else {
						$ignored++;
					}
				}
				
				if (!empty($prices)) {
					foreach($prices as $row) {
						if (!isset($row['price'])) {
							continue;
						}
						
						if ($row['group_id'] == 0) {
							// UPDATE djc2_items table
							$db->setQuery('UPDATE #__djc2_items SET price='.$row['price'].' WHERE id='.$row['item_id']);
							if ($db->execute()){
								$updated++;
							} else {
								$failed++;
							}
						} else {
							// UPDATE djc2_prices table
							$db->setQuery('SELECT * FROM #__djc2_prices WHERE group_id='.$row['group_id'] .' AND item_id='.$row['item_id']);
							$price_row = $db->loadObject();
							if ($price_row) {
								if ($price_row->price == $row['price']) {
									$ignored++;
									continue;
								}
								$row['id'] = $price_row->id;
							} else {
								$row['id'] = 0;
							}
							
							$obj = ArrayHelper::toObject($row);
							if ($obj->id > 0) {
								if ($db->updateObject('#__djc2_prices', $obj, 'id', false)) {
									$updated++;
								} else {
									$failed++;
								}
							} else {
								if($db->insertObject( '#__djc2_prices', $obj, 'id')){
									$inserted++;
								} else {
									$failed++;
								}
							}
						}
						
					}
				}
			}
		}
		
		$messages['info'][] = Text::_('COM_DJCATALOG2_IMPORT_INSERTED').': '.$inserted;
		$messages['info'][] = Text::_('COM_DJCATALOG2_IMPORT_UPDATED').': '.$updated;
		
		if ($ignored > 0) {
			$messages['warning'][] = Text::_('COM_DJCATALOG2_IMPORT_IGNORED').': '.$ignored;
		}
		if ($failed > 0) {
			$messages['error'][] = Text::_('COM_DJCATALOG2_IMPORT_FAILED').': '.$failed;
		}
		
		foreach($messages as $type => $arr) {
			if (!empty($arr)){
				foreach($arr as $message) {
					$app->enqueueMessage($message, $type);
				}
			}
		}
		
		$this->setRedirect(JRoute::_('index.php?option=com_djcatalog2&view=import', false));
		return true;
	}
}