<?php
/**
 * Product files import
 *
 * @package		CSVIVirtueMart
 * @subpackage 	Import
 * @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: productfilesimport.php 1892 2012-02-11 11:01:09Z RolandD $
 */

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

/**
 * Processor for product details
 *
 * Main processor for importing categories.
 *
 * @package	CSVIVirtueMart
 * @todo 	Clarify folder structure
 * @todo 	Add product ID <---- important
 */
class CsvivirtuemartModelProductfilesimport extends CsvivirtuemartModelImportfile {

	// Private tables
	/** @var object contains the vm_product_files table */
	private $_vm_product_files = null;
	/** @var object contains the vm_product_attribute table */
	private $_vm_product_attribute = null;
	/** @var string the domainname */
	private $_domainname =  null;

	// Public variables
	/** @var integer contains the product ID of a product */
	public $product_id = null;
	/** @var integer contains the FQDN for the image */
	public $file_url = null;

	public $file_name = null;
	public $file_extension = null;
	public $file_mimetype = null;
	public $file_is_image = null;
	public $file_image_height = null;
	public $file_image_width = null;
	public $file_image_thumb_width = null;
	public $file_image_thumb_height = null;

	// Private variables
	/** @var mixed contains the data of the current field being processed */
	private $_datafield = null;
	/** @var object contains general import functions */
	private $_importmodel = null;
	/** @var object contains the mimetype of a file */
	private $_mimetype = null;
	/** @var bool contains whether or not the product file should be deleted */
	protected $product_files_delete = false;
	/** @var bool contains whether or not the product file is downloadable */
	protected $product_files_download = false;

	/**
	 * Constructor
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.4
	 */
	public function __construct() {
		parent::__construct();
		// Load the tables that will contain the data
		$this->_loadTables();
		$this->loadSettings();

		// Load the domain name
		$this->_domainname = CsviHelper::getDomainName();
    }

    /**
     * Refresh the settings for XML nodes
     *
     * @copyright
     * @author 		RolandD
     * @todo
     * @see
     * @access 		protected
     * @param
     * @return
     * @since 		3.8.2
     */
	protected function refresh() {
		$this->loadSettings();
	}

	/**
	 * Here starts the processing
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo		Redo the validateInput
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getStart() {
		// Load the data
		$this->loadData();

		// Get the logger
		$csvilog = JRequest::getVar('csvilog');

		// Get the file_product_id
		$this->file_product_id = $this->getProductId();

		// Load ICEcat data if user wants to
		$this->getIcecat();

		if ($this->file_product_id > 0) {
			// Check if the fields match the data
			if (count($this->_csvifields) > count(JRequest::getVar('csvi_data'))) {
				$csvilog = JRequest::getVar('csvilog');
				$message =  JText::sprintf('COM_CSVIVIRTUEMART_INCORRECT_COLUMN_COUNT', count($this->_csvifields), count($this->csvi_data));
				$message .= '<br />'.JText::_('COM_CSVIVIRTUEMART_FIELDS');
				foreach($this->_csvifields as $fieldname => $field_details) {
					$message .= '<br />'.$field_details['order'].': '.$fieldname;
				}
				$message .= '<br />'.JText::_('COM_CSVIVIRTUEMART_VALUE');
				if (!empty($this->csvi_data)) {
					foreach ($this->csvi_data AS $key => $data) {
						$message .= '<br />'.$key.': '.$data;
					}
				}
				$csvilog->AddStats('incorrect', $message, true);
				return false;
			}
			else {
				// Process any other fields
				foreach ($this->_csvifields as $name => $details) {
					if ($details['published']) {
						$this->_datafield = $this->validateInput($name);
						if ($this->_datafield !== false) {
							// Check if we are dealing with the last field
							if ($details == $this->_lastfield) $details['combine'] = false;

							// See if we are combining the field
							if ($details['combine']) $this->setCombineField($this->_datafield, $name);
							else {
								// Check if there are any fields to be combined
								if (!empty($this->combine_fields)) {
									// Get the fieldname the combine is for
									$name = $this->combine_settings['fieldname'];
									// Add the current data
									$this->setCombineField($this->_datafield);
									// Get the combined data
									$this->_datafield = $this->getCombineField();
								}
								// Check if the field needs extra treatment
								switch ($name) {
									case 'product_files_download':
										if (strtoupper($this->_datafield) == 'Y') $this->product_files_download = true;
										break;
									case 'product_files_file_name':
										if (!is_array($this->_datafield)) $this->$name = array($this->_datafield);
										else $this->$name = $this->_datafield;
										break;
									case 'product_files_file_title':
										if (!is_array($this->_datafield)) $this->$name = array($this->_datafield);
										else $this->$name = $this->_datafield;
										break;
									case 'product_files_file_description':
										$this->file_description = $this->_datafield;
										break;
									case 'product_files_file_url':
										if (!is_array($this->_datafield)) $this->$name = array($this->_datafield);
										else $this->$name = $this->_datafield;
										break;
									case 'product_files_file_published':
										if (strtoupper($this->_datafield) == 'Y') $this->file_published = 1;
										else $this->file_published = 0;
										break;
									default:
										$this->$name = $this->_datafield;
										break;
								}
							}
						}
					}
				}
			}
			return true;
		}
		else {
			$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_NO_PRODUCT_ID_FOUND'));
			$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_NO_PRODUCT_ID_FOUND'), true);
			return false;
		}
	}

	/**
	 * Process each record and store it in the database
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getProcessRecord() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');

		// Do we need to delete a product file?
		if (strtoupper($this->product_files_delete) == 'Y') {
			foreach ($this->product_files_file_name as $fkey => $this->file_name) {
				// Let's see if we have a file_id
				$q = "SELECT file_id
					FROM #__vm_product_files
					WHERE file_name = ".$db->Quote($this->file_name)." AND file_product_id = ".$this->file_product_id;
				$db->setQuery($q);
				$this->file_id = $db->loadResult();
				if ($this->file_id) {
					$this->_vm_product_files->bind($this);
					if ($this->_vm_product_files->delete()) $csvilog->AddStats('deleted', JText::_('COM_CSVIVIRTUEMART_PRODUCT_FILE_HAS_BEEN_DELETED'));
					else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_FILE_HAS_NOT_BEEN_DELETED'));
				}
				else {
					$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_FILE_HAS_NOT_BEEN_FOUND'));
				}
				$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_PRODUCTFILE_DELETE_QUERY'), true);
			}
		}
		else {
			// Go through all the files
			foreach ($this->product_files_file_name as $fkey => $this->file_name) {
				// Execute the functions in the correct order
				if ($this->_productFilesFileName()) {
					// Let's see if the user has a downloadable product
					if ($this->product_files_download) {
						// Load file functions
						jimport('joomla.filesystem.file');

						// Set fixed values for download products
						$this->file_description = '';
						$this->file_extension = '';
						$this->file_mimetype = '';
						$this->file_url = '';
						$this->file_published = 0;
						$this->file_is_image = 0;
						$this->file_image_height = 0;
						$this->file_image_width = 0;
						$this->file_image_thumb_height = 0;
						$this->file_image_thumb_width = 0;

						// Set the downloadable properties
						$this->_vm_product_attribute->setValue('product_id', $this->file_product_id);
						$this->_vm_product_attribute->setValue('attribute_name', 'download');
						$this->_vm_product_attribute->setValue('attribute_value', basename($this->file_name));
						$this->_vm_product_attribute->store();

						// Get the download path
						$vm_config = new CsviVmConfig();
						$this->file_name = $vm_config->getSetting('DOWNLOADROOT').basename($this->file_name);
						$this->file_title = basename($this->file_name);
					}
					else {
						$this->_productFilesFileUrl($fkey);

						// Get the file title
						$this->_productFilesFileTitle($fkey);
					}

					// All data should be loaded, bind the data
					$this->_vm_product_files->bind($this);

					// Check if we already have a file ID
					$this->_vm_product_files->check();

					// Store the data
					if ($this->_vm_product_files->store()) {
						if ($this->queryResult() == 'UPDATE') $csvilog->AddStats('updated', JText::_('COM_CSVIVIRTUEMART_UPDATE_PRODUCTFILE'));
						else $csvilog->AddStats('added', JText::_('COM_CSVIVIRTUEMART_ADD_PRODUCTFILE'));

					}
					else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_PRODUCTFILE_NOT_ADDED', $this->_vm_product_files->getError()));

					// Store the debug message
					$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_PRODUCTFILE_QUERY'), true);

					// Reset the file ID
					$this->_vm_product_files->setValue('file_id', null);
				}
			}
		}

		// Clean the tables
		$this->cleanTables();
	}

	/**
	 * Load the product files related tables
	 *
	 * @copyright
	 * @author		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return
	 * @since 		3.0
	 */
	private function _loadTables() {
		$this->_vm_product_files = $this->getTable('vm_product_files');
		$this->_vm_product_attribute = $this->getTable('vm_product_attribute');
	}

	/**
	 * Cleaning the product files related tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		protected
	 * @param
	 * @return
	 * @since 		3.0
	 */
	protected function cleanTables() {
		$this->_vm_product_files->reset();
		$this->_vm_product_attribute->reset();

		// Clean local variables
		$class_vars = get_class_vars(get_class($this));
		foreach ($class_vars as $name => $value) {
			if (substr($name, 0, 1) != '_') {
				$this->$name = $value;
			}
		}
	}

	/**
	 * Get the products filename
	 *
	 * Images are stored in the array $this->product_files_file_name
	 *
	 * @copyright
	 * @author		RolandD
	 * @todo 		Fix the image handling
	 * @see
	 * @access 		private
	 * @param
	 * @return
	 * @since 		3.0
	 */
	private function _productFilesFileName() {
		// Load some settings
		$csvilog = JRequest::getVar('csvilog');
		$template = JRequest::getVar('template');

		// Check if the file is to be deleted
		if (!$this->product_files_delete && !$this->product_files_download) {
			// Image handling
			$imagehelper = new ImageHelper;

			// Image path
			$imagepath = JPath::clean($template->getValue('file_location_product_images', 'path'), '/');
			// Non-image path
			$mediapath = JPath::clean($template->getValue('file_location_media', 'path'), '/');

			// See if we are dealing with an image or non-image file
			if ($imagehelper->isImage($imagepath.'/'.$this->file_name)) {
				// Process the image file
				$file_details = $imagehelper->ProcessImage($this->file_name, $this->file_name, $imagepath);
				$workpath = $imagepath;
			}
			else {
				// Process the image file
				$file_details = $imagehelper->ProcessImage($this->file_name, $this->file_name, $mediapath);
				$workpath = $mediapath;
			}

			if ($file_details['full_image']['exists']) {
				// Fix the image name, it must be preceded by the path to the image
				if ($file_details['full_image']['isremote']) {
					$csvilog->addDebug('Workpath:'.$workpath);
					$csvilog->addDebug('JPath site:'.JPATH_SITE);
					$this->file_name = str_ireplace(JPath::clean(JPATH_SITE, '/'), '', JPath::clean($workpath, '/'));
					$csvilog->addDebug('File step 1:'.$this->file_name);
					$this->file_name .= '/'.$file_details['full_image']['output_name'];
					$csvilog->addDebug('File step 2:'.$this->file_name);
					$this->file_name = JPath::clean($this->file_name, '/');
					$csvilog->addDebug('File step 3:'.$this->file_name);
				}
				else {
					$csvilog->addDebug('Workpath:'.$workpath);
					$csvilog->addDebug('JPath site:'.JPATH_SITE);
					$this->file_name = str_ireplace(JPath::clean(JPATH_SITE, '/'), '', JPath::clean($workpath, '/'));
					$csvilog->addDebug('File step 1:'.$this->file_name);
					$this->file_name .= (empty($file_details['full_image']['output_folder'])) ? '/'.$file_details['full_image']['output_name'] : $file_details['full_image']['output_folder'].'/'.$file_details['full_image']['output_name'];
					$csvilog->addDebug('File step 2:'.$this->file_name);
					$this->file_name = JPath::clean($this->file_name, '/');
					$csvilog->addDebug('File step 3:'.$this->file_name);
				}
				$this->file_extension = $file_details['full_image']['output_extension'];
				$this->file_is_image = $file_details['full_image']['isimage'];
				if ($this->file_is_image) {
					$this->file_mimetype = $file_details['full_image']['mime_type'];
					$this->file_image_height = $file_details['full_image']['image_height'];
					$this->file_image_width = $file_details['full_image']['image_width'];
					if (array_key_exists('thumb_image', $file_details)) {
						$this->file_image_thumb_width = $file_details['thumb_image']['output_width'];
						$this->file_image_thumb_height = $file_details['thumb_image']['output_height'];
					}
				}
				else {
					$this->file_mimetype = 'application/x-download';
				}
				return true;
			}
			else {
				if ($template->getValue('ignore_non_exist', 'product_files', true)) {
					$csvilog->addDebug(JText::sprintf('COM_CSVIVIRTUEMART_DEBUG_PRODUCT_FILE_NOT_EXIST_SKIPPING', $this->file_name));
					return false;
				}
				else return true;
			}
		}
		else return true;
	}

	/**
	 * Get the file URL of the product file
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		int	$fkey	the array posistion to use
	 * @return
	 * @since 		3.0
	 */
	private function _productFilesFileUrl($fkey) {
		if (isset($this->product_files_file_url) && array_key_exists($fkey, $this->product_files_file_url)) $this->file_url = $this->product_files_file_url[$fkey];

		if (empty($this->file_url) && !$this->product_files_download) {
			$template = JRequest::getVar('template');
			$csvilog = JRequest::getVar('csvilog');
			$csvilog->addDebug(JText::sprintf('COM_CSVIVIRTUEMART_DEBUG_FILE_URL_FROM', $this->file_name));
			$csvilog->addDebug(JText::sprintf('COM_CSVIVIRTUEMART_DEBUG_DOMAINNAME', $this->_domainname));
			// Construct the path
			$path = str_ireplace(JPath::clean(JPATH_SITE, '/'), '', $template->getValue('file_location_media', 'path'));
			$filename = str_ireplace($path, '', $this->file_name);
			$this->file_url = $this->_domainname.JPath::clean('/'.$path.'/'.$filename, '/');
		}
	}

	/**
	 * Get the file title of the product file
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		int	$fkey	the array posistion to use
	 * @return
	 * @since 		3.0
	 */
	private function _productFilesFileTitle($fkey) {
		if (isset($this->product_files_file_title) && array_key_exists($fkey, $this->product_files_file_title)) {
			$this->file_title = $this->product_files_file_title[$fkey];
		}
	}
}
?>
