<?php
/**
 * @package     Joomla.Plugin
 * @subpackage  System.Vm_uploader
 *
 * @copyright   Copyright (C) 2015 Studio42, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Virtuemart uploader Plugin.
 *
 * @since  1.6
 * @deprecate  4.0  Obsolete
 */
class PlgSystemVm_uploader extends JPlugin
{
	

	/**
	 * Method to catch the onAfterInitialise event.
	 *
	 * Check if we have a vm upload
	 *
	 * @return  boolean  True on success
	 *
	 */
	public function onAfterInitialise()
	{
		// Check that we are in the site application.
		if (JFactory::getApplication()->isSite())
		{
			return true;
		}
		// Set the variables.
		$input = JFactory::getApplication()->input;
		$extension = $input->get('option', '', 'cmd');
		// Check if is virtuemart.
		if ($extension !== 'com_virtuemart')
		{
			return true;
		}
		$upload = $input->get('vm_upload', '', 'int');
		$type = $input->get('type', '', 'cmd');
		if($upload && $type) {
			jimport('joomla.filesystem.folder');
			error_reporting(E_ALL | E_STRICT);
			if (!class_exists( 'VmConfig' )) require(JPATH_ROOT.'/administrator/components/com_virtuemart/helpers/config.php');
			VmConfig::loadConfig();
			$relUrl = '/images';
			if($type == 'product' || $type == 'products'){
				$type = 'product';
				$relUrl = VmConfig::get('media_product_path');
			}
			else if($type == 'category' || $type == 'categories'){
				$type ='category';
				$relUrl = VmConfig::get('media_category_path');
			}
			else if($type == 'shop'){
				$relUrl = VmConfig::get('media_path');
			}
			else if($type == 'vendor' || $type == 'vendors'){
				$relUrl = VmConfig::get('media_vendor_path');
				$type = 'vendor';
			}
			else if($type == 'manufacturer' || $type == 'manufacturers'){
				$relUrl = VmConfig::get('media_manufacturer_path');
				$type = 'manufacturer';
			} else return true;
			
			// echo ' '.$relUrl;
			if(substr($relUrl,-1) !=='/') $relUrl .= '/';
			// echo ' --- '.$relUrl.' ';
			$resizeDir = $relUrl.'resized/';
			if($subFolder = $input->get('addfolder', '', 'CMD')) {
				if(!is_dir(JPATH_ROOT . '/'.$relUrl.'/'.$subFolder) ) JFolder::create(JPATH_ROOT . '/'.$relUrl.'/'.$subFolder);
				$resizeDir .=  $subFolder.'/';
				$relUrl .=  $subFolder.'/';
			}			
			else if($subFolder = $input->get('subfolder', '', 'CMD')) {
				if(is_dir(JPATH_ROOT . '/'. $relUrl.'/'.$subFolder) ) {
				$resizeDir .=  $subFolder.'/';
				$relUrl .=  $subFolder.'/';
				}
			}
			// echo $resizeDir.' '.$relUrl;
			// jexit();
			// if(!VmConfig::isSuperVendor()) return true;
			$lang = JFactory::getLanguage();
			$lang->load('com_media', JPATH_ADMINISTRATOR);
			
			$post_max_size = $this->to_bytes('post_max_size');
			$upload_max_filesize =  $this->to_bytes('upload_max_filesize');
			if($upload_max_filesize > $post_max_size) $upload_max_filesize = $post_max_size;
			$chunksize = $upload_max_filesize-1;
			$watermark = $this->params->get('watermark','');
			if ($watermark) $no_cache = 0;
			else $no_cache = 0;
			$watermark_position = $this->params->get('watermark_position','');
			$watermark_padding = $this->params->get('watermark_padding','');
			$acceptFileTypes = 'gif|jpe?g|png';
			if( $type == 'product' && $filter = $this->params->get('filter', null)) {
				$filter = preg_replace("/[^A-Za-z0-9,]/", '', $string);
				$exts = explode(",", $filter);
				$valideExt = array();
				foreach($exts as $ext) {
					if(strlen($ext)) $valideExt[] = $ext;
				}
				if(!empty($valideExt)) $acceptFileTypes = implode ("|", $valideExt);
			}


			$options = array(
				'script_url' => 'index.php?option=com_virtuemart&vm_upload=1&type='.$type,
				'upload_dir' => JPATH_ROOT . '/'.$relUrl,
				'upload_url' => juri::root().$relUrl,
				'max_file_size' => $upload_max_filesize,
				'readfile_chunk_size' => $chunksize,
				'watermark' => $watermark,
				'watermark_position' => $watermark_position,
				'watermark_padding' => $watermark_padding,
				'accept_file_types' => '/\.('.$acceptFileTypes.')$/i'
			);
			// resize big image
			if ($this->params->get('big_image_resize', 0)) {
				$options['image_versions'][] = array(
					'max_width' => (int)$this->params->get('big_image_width', 1920),
					'max_height' => (int)$this->params->get('big_image_height', 1080),
					'crop' =>  (bool)$this->params->get('big_image_crop', 0)
				);
			}
			// resize product medium image
			if ($this->params->get('product_medium_resize', 0) && $type === 'product') {
				$options['image_versions']['medium'] = array(
					'max_width' => (int)$this->params->get('product_medium_width', 1920),
					'max_height' => (int)$this->params->get('product_medium_height', 1080),
					'crop' =>  (bool)$this->params->get('product_medium_crop', 0)
				);
			}
			// resize thumb
			if (VmConfig::get('img_resize_enable', 1)) {
				if ($this->params->get($type.'_thumb_resize', 0)) {
					$options['image_versions']['resized'] = array(
						'max_width' => (int)$this->params->get($type.'_thumb_width', 200),
						'max_height' => (int)$this->params->get($type.'_thumb_height', 200),
						'crop' =>  (bool)$this->params->get($type.'_thumb_crop', 0),
						'upload_dir' => $resizeDir,
						'upload_url' => juri::root().$resizeDir
					);
				} else {
					$options['image_versions']['resized'] = array(
						'max_width' => (int)VmConfig::get('img_width', 90),
						'max_height' => (int)VmConfig::get('img_height', 90),
						'upload_dir' => $resizeDir,
						'upload_url' => juri::root().$resizeDir
					);
				}
			}

			require(dirname(__FILE__).'/uploader/UploadHandler.php');
			$uploaded = new UploadHandler($options);
			// $files = (array)$files;
			$rSize = strlen(juri::root());
		if (isset($uploaded->response) && isset($uploaded->response['files'])) $file = $uploaded->response['files'];
			if (!class_exists( 'VmTable' )) require(JPATH_ROOT.'/administrator/components/com_virtuemart/helpers/vmtable.php');
			
				// echo json_encode($file);
			if(!empty($file)) {
				if (isset($file[0])) $file = $file[0];
			// foreach ($files as $file) {
				$data = array();
				$table = VmTable::getInstance('medias', 'table');
				$data['virtuemart_vendor_id'] = 1 ;
				$data['file_title'] = $file->name;
				$data['file_description'] = '' ;
				$data['file_meta'] = '' ;
				$data['file_class'] = '' ;
				$data['file_mimetype'] = $file->type ;
				$data['file_type'] = $type ;
				$data['file_url'] = substr($file->url , $rSize);
				if(empty($file->resizedUrl)) $data['file_is_downloadable'] =1 ;
				$data['file_url_thumb'] = '' ; //substr($file->resizedUrl, $rSize);
				$data['file_is_product_image'] = (int)($type === 'product') ;
				$data['file_is_forSale'] = 0 ;
				$data['file_params'] = '' ;
				$data['file_lang'] = '' ;
				$data['shared'] = 0 ;
				$data['published'] = 1 ;
				// created_on	created_by	modified_on	modified_by	locked_on	locked_by
				//set the relations

				// return $table->virtuemart_media_id;
				// Bind the form fields to the country table
				$table->bindChecknStore($data);
				$file->virtuemart_media_id = $table->virtuemart_media_id ;
				$files = array( 0 => $file);
				echo json_encode(array('files' => $files ));
				// TODO, return media ID echo json_encode($table);
			} else echo '{"bad":"error"}';
			// echo json_encode($files['files']) ;
			// }
			jexit();
		}
		return true;
	}
	/**
	 * Method to catch the onAfterDispatch event.
	 *
	 * The gallery is done with JavaScript so we just
	 * need to check a few parameters and add the javascripts.
	 *
	 * @return  boolean  True on success
	 *
	 */
	public function onAfterDispatch()
	{
		// Check that we are in the site application.
		if (JFactory::getApplication()->isSite())
		{
			return true;
		}
		// Set the variables.
		$input = JFactory::getApplication()->input;
		$extension = $input->get('option', '', 'cmd');
		// Check if is virtuemart.
		if ($extension !== 'com_virtuemart')
		{
			return true;
		}
		$view = $input->get('view', '', 'cmd');
		jimport('joomla.filesystem.folder');
		// Check if view is product
		if ($view !== 'product' && $view !== 'category' && $view !== 'manufacturer' && $view !== 'shop') return true;
		if ($input->get('task', '', 'cmd') !== 'edit') return true;
		// add the button in the bar
		JToolbar::getInstance('toolbar')->appendButton('Standard', 'upload','IMAGE', 'image', false);
		
		// settings
		$resize = $this->params->get('client_side_resize', 0);
		$width = $this->params->get('client_side_width', 1920);
		$height = $this->params->get('client_side_height', 1080);

		$lang = JFactory::getLanguage();
		$lang->load('com_media', JPATH_ADMINISTRATOR);
		$post_max_size = $this->to_bytes('post_max_size');
		$upload_max_filesize =  $this->to_bytes('upload_max_filesize');
		if($upload_max_filesize > $post_max_size) $upload_max_filesize = $post_max_size;
		$chunksize = $upload_max_filesize-1;
		
		// add to component buffer.
		$doc = JFactory::getDocument();
		$buf = $doc->getBuffer('component');
		ob_start();
		include 'assets/basic-plus.php';
		$template = ob_get_contents();
		ob_end_clean();
		$buf = $buf . $template;
		$doc->setBuffer($buf, 'component');
		return true;
	}
	private function to_bytes($key) {
		
		$val = ini_get($key);
		$val = trim($val);
		$last = strtolower($val[strlen($val)-1]);
		switch($last) {
			// Le modifieur 'G' est disponible depuis PHP 5.1.0
			case 'g':
				$val *= 1024;
			case 'm':
				$val *= 1024;
			case 'k':
				$val *= 1024;
		}

		return $val;
}
}
