<?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' );
jimport('joomla.application.component.controlleradmin');


class Djcatalog2ControllerProducers extends JControllerAdmin
{
	public function getModel($name = 'Producer', $prefix = 'Djcatalog2Model', $config = array())
	{
		$model = parent::getModel($name, $prefix, array('ignore_request' => true));
		return $model;
	}
	
	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/producer';
		if (!JFolder::exists($path)) {
			JFolder::create($path);
		}
	
		if (!is_writable($path)) {
			$this->setRedirect( 'index.php?option=com_djcatalog2&view=producers', JText::_('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(JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'));
			$this->setMessage($this->getError(), 'error');
			$this->setRedirect( 'index.php?option=com_djcatalog2&view=producers' );
			return false;
		}
	
		jimport('joomla.application.component.modellist');
	
		$model = JModelList::getInstance('Producers', 'Djcatalog2Model', array('ignore_request'=>true));
	
		$state = $model->getState();
		$context = 'com_djcatalog2.producers';
	
		$start = $app->input->get('start', 0);
		$limit = 1000;
	
		$model->setState('list.select', 'a.*, uc.name AS author');
		$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);
			
		$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_producers');
		$columns = $db->loadColumn(0);
		$columns = array_merge($columns, array('author'));
	
		$filename = $app->input->get('export_file', 'producer-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)) {
					$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=producers.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/producer/'.$filename)).'">'.$filename.'</a>';
			$this->setRedirect( 'index.php?option=com_djcatalog2&view=producers', JText::_('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('producer');
		$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['published'] = (int)$app->input->get('published', 0);
		$defaults['created_by'] = (int)$app->input->get('created_by', $user->id);
		$defaults['created'] = $app->input->get('created',  $date->toSql());
	
		$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), JText::_('COM_DJCATALOG2_ERROR_INVALID_ENCODING'), 'error');
					return false;
				}
				
				$rows = Djcatalog2ImportHelper::parseCSV(realpath($tempname), $separator, $enclosure);
				if (!empty($rows)) {
					$messages = Djcatalog2ImportHelper::storeRecords($rows, $model, 'producer', $defaults);
				}
			}
		}
	
		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;
	}
}