<?php
/**
 * Import controller
 *
 * @package		CSVIVirtueMart
 * @author 		Roland Dalmulder
 * @link 		http://www.csvimproved.com
 * @copyright 	Copyright (C) 2006 - 2012 RolandD Cyber Produksi
 * @license 	GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 * @version 	$Id: importfile.php 1892 2012-02-11 11:01:09Z RolandD $
 */

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

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

/**
 * Import Controller
 *
 * Importing a file follows this process:
 * 1. controllers/importfile.php -> importFile
 * 2. models/importfile.php -> prepareImport (sets session values)
 * 3. views/importfile/view.html.php -> display
 * 4. views/importfile/tmpl/default.php JS calls import
 * 5. controllers/importfile.php -> doImport
 * 6. models/importfile.php -> getDoImport (sets session values)
 * 7. views/importfile/view.json.php -> return result
 *
 * @package CSVIVirtueMart
 */
class CsvivirtuemartControllerImportfile extends JController {

	/**
	 * Method to display the view
	 *
	 * @copyright
	 * @author		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function __construct() {
		parent::__construct();
	}

	/**
	 * Load import model files
	 *
	 * Here the models are loaded that are used for import. Special is the
	 * import model file as this is included based on the template type
	 *
	 * @copyright
	 * @author		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since		3.0
	 */
	public function importFile() {
		// Load the import type
		$vtype = (JRequest::getBool('cron', false)) ? 'cron' : 'html';

		if ($vtype == 'html') {
			// Check for request forgeries
			JRequest::checkToken() or jexit( 'Invalid Token' );
		}

		// Set the start time of the import
		$session = JFactory::getSession();
		$option = JRequest::getVar('option');
		$session->set($option.'.runtime', time());

		// Start with a clean session
		$session->set($option.'.select_template', serialize(JRequest::getInt('select_template')));
		$session->set($option.'.global.template', serialize('0'));
		$session->set($option.'.csvicolumnheaders', serialize('0'));
		$session->set($option.'.csvifields', serialize('0'));
		$session->set($option.'.csvifile', serialize('0'));
		$session->set($option.'.csvilog', serialize('0'));
		$session->set($option.'.filepos', serialize('0'));
		$session->set($option.'.recordsprocessed', serialize('0'));
		$session->set($option.'.totalline', serialize('0'));

		$model = $this->getModel('templates');

		// Create the view object
		$view = $this->getView('importfile', $vtype);

		// Load the model
		$view->setModel( $this->getModel( 'importfile', 'CsvivirtuemartModel' ), true );
		// Log functions
		$view->setModel( $this->getModel( 'log', 'CsvivirtuemartModel' ));

		// Load the model
		$model = $this->getModel('importfile');

		// Check which helper files to include
		$helper_files = $model->getHelperFiles();

		if (!$helper_files) {
			if (!JRequest::getBool('cron', false)) {
				// Redirect back to the import page
				$this->setRedirect('index.php?option=com_csvivirtuemart&task=import&view=import', JText::_('COM_CSVIVIRTUEMART_ERROR_IMPORT_FILE'), 'error');
			}
			else {
				// Get the error stack
				$errors = $GLOBALS['_JERROR_STACK'];
				foreach ($errors as $error) {
					echo $error->message."\n";
				}
				// Empty the error stack
				$GLOBALS['_JERROR_STACK'] = array();
				$view->setLayout('cron');
			}
		}
		else {
			// Load helper files
			$view->addHelperPath(JPATH_COMPONENT_ADMINISTRATOR.'/helpers/file/import');
			$view->loadHelper('file');
			$view->loadHelper('template');
			if (!empty($helper_files)) {
				foreach ($helper_files as $helper) {
					$view->loadHelper($helper);
				}
			}

			// Prepare for import
			if ($model->getPrepareImport()) {
				// Start the import
				switch ($vtype) {
					case 'cron':
						$view->setLayout('cron');
						$this->doImport();
						break;
					default:
						$view->display();
						break;
				}
			}
			else {
				// Clean up
				$model->getCleanSession();

				if (!JRequest::getBool('cron', false)) {
					// Redirect back to the import page
					$this->setRedirect('index.php?option=com_csvivirtuemart&task=import&view=import', JText::_('COM_CSVIVIRTUEMART_ERROR_IMPORT_FILE'), 'error');
				}
				else {
					// Get the error stack
					$errors = $GLOBALS['_JERROR_STACK'];
					foreach ($errors as $error) {
						echo $error->message."\n";
					}
					// Empty the error stack
					$GLOBALS['_JERROR_STACK'] = array();
					$view->setLayout('cron');
				}
			}
		}
	}

	/**
	 * Import records called via JavaScript
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo 		remove global from session vars
	 * @todo
	 * @see 		prepareImport (models/importfile) where the session data is set
	 * @see 		_finishProcess (models/importfile) where the session data is unset
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function doImport() {
		// Create the view object
		$vtype = (JRequest::getBool('cron', false)) ? 'cron' : 'json';
		$view = $this->getView('importfile', $vtype);

		// Load the data from the session
		$session = JFactory::getSession();
		$option = JRequest::getVar('option');

		// Set the run ID
		JRequest::setVar('run_id', $session->get($option.'.run_id'));

		// Check which helper files to include
		$helper_files = unserialize($session->get($option.'.helper_files'));

		// Load helper files
		$view->addHelperPath(JPATH_COMPONENT_ADMINISTRATOR.'/helpers/file/import');
		$view->loadHelper('file');
		$view->loadHelper('template');
		$view->loadHelper('icecat');
		if (!empty($helper_files)) {
			foreach ($helper_files as $helper) {
				$view->loadHelper($helper);
			}
		}

		// The template
		$template = unserialize($session->get($option.'.global.template'));

		if (is_object($template)) {
			// Enable the session
			JRequest::setVar('importsession', true);

			// Set the template
			JRequest::setVar('template', $template);
			// The logger
			JRequest::setVar('csvilog', unserialize($session->get($option.'.csvilog')));
			// Set the file handler
			JRequest::setVar('csvifile', unserialize($session->get($option.'.csvifile')));
			// Load the total line counter
			JRequest::setVar('totalline', unserialize($session->get($option.'.totalline')));
			// Load the total of records processed
			JRequest::setVar('recordsprocessed', unserialize($session->get($option.'.recordsprocessed')));
			// Set the fields found in the import file
			JRequest::setVar('csvifields', unserialize($session->get($option.'.csvifields')));
			// Set the list of available fields
			JRequest::setVar('avfields', unserialize($session->get($option.'.avfields')));
			// Load the column headers
			JRequest::setVar('columnheaders', unserialize($session->get($option.'.csvicolumnheaders')));
			// Load the preview handler
			JRequest::setVar('csvipreview', unserialize($session->get($option.'.csvipreview')));
			// Load the settings
			JRequest::setVar('csvisettings', unserialize($session->get($option.'.csvisettings')));

			// Set the import override
			$app = JFactory::getApplication();
			$overridefile = JPATH_BASE.'/templates/'.$app->getTemplate().'/html/'.$option.'/models/import/'.$template->getValue('import_type').'.php';

			// Add the import model path if override exists
			if (file_exists($overridefile)) $this->addModelPath(JPATH_BASE.'/templates/'.$app->getTemplate().'/html/'.$option.'/models/import');
			else $this->addModelPath(JPATH_COMPONENT_ADMINISTRATOR.'/models/import');

			// Load the model
			$view->setModel($this->getModel('importfile', 'CsvivirtuemartModel'), true);
			// Settings functions
			$view->setModel($this->getModel('settings', 'CsvivirtuemartModel'));
			// Log functions
			$view->setModel($this->getModel('log', 'CsvivirtuemartModel'));
			// General import functions
			$view->setModel($this->getModel('import', 'CsvivirtuemartModel'));
			// General category functions
			$view->setModel($this->getModel('category', 'CsvivirtuemartModel'));
			// Available fields
			$view->setModel($this->getModel('availablefields', 'CsvivirtuemartModel'));

			// Prepare for import
			$view->get('DoImport');
		}
		else {
			JRequest::setVar('importsession', false);
		}

		// Display it
		$view->display();
	}
}
?>
