<?php 
namespace JExtstore\Component\JChat\Site\View\Lamessages;
/** 
 * @package JCHAT::LAMESSAGES::administrator::components::com_jchat
 * @subpackage views
 * @subpackage lamessages
 * @author Joomla! Extensions Store
 * @Copyright (C) 2015 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html 
 */
defined ( '_JEXEC' ) or die ( 'Restricted access' );
use Joomla\CMS\Language\Text;
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\Registry\Registry;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Pagination\Pagination;
use Joomla\CMS\Filter\OutputFilter;
use Joomla\CMS\Editor\Editor;
use JExtstore\Component\JChat\Administrator\Framework\View as JChatView;

define ( 'INDEX_WORKED', 'worked');
define ( 'INDEX_CLOSED', 'closed_ticket');

/**
 * User leaved messages view implementation
 *
 * @package JCHAT::MESSAGES::administrator::components::com_jchat
 * @subpackage views
 * @since 2.20
 */
class HtmlView extends JChatView {
	// Template view variables
	protected $joomlaConfig;
	protected $pagination;
	protected $limitstart;
	protected $params;
	protected $order;
	protected $searchword;
	protected $lists;
	protected $orders;
	protected $items;
	protected $dates;
	protected $phoneNumberEnabled;
	protected $record;
	protected $editor;
	protected $nameOfUser;
	
	/**
	 * Default listEntities
	 * @access public
	 */
	public function display($tpl = 'list') {
		$doc = $this->app->getDocument ();
		$this->loadJQuery($doc);
		$this->loadJQueryUI($doc);
		$this->doc->getWebAssetManager()->registerAndUseStyle ( 'jchat.bootstrap-interface', 'components/com_jchat/css/bootstrap-interface.css');
		$this->doc->getWebAssetManager ()->useStyle ( 'fontawesome' ); // Required for checkout icons
		HTMLHelper::_('bootstrap.loadCss');
		
		// Scripts loading
		$cParams = $this->getModel()->getComponentParams(); 
		$defer = $cParams->get('scripts_loading', null) == 'defer' ? true : false;
		$async = $cParams->get('scripts_loading', null) == 'async' ? true : false;
		$this->doc->getWebAssetManager()->registerAndUseScript ( 'jchat.bootstrap-interface', 'components/com_jchat/js/bootstrap-interface.js', [], ['defer'=>$defer, 'async'=>$async], ['jquery']);
		
		// Inject js translations
		$translations = array('COM_JCHAT_SELECT_RECORD');
		$this->injectJsTranslations($translations, $doc);
		
		// Get main records
		$rows = $this->get('Data');
		$lists = $this->get('Filters');
		$total = $this->get('Total');
		
		$orders = array();
		$orders['order'] = $this->getModel()->getState('order');
		$orders['order_Dir'] = $this->getModel()->getState('order_dir');
		// Pagination view object model state populated
		$pagination = new Pagination( $total, $this->getModel()->getState('limitstart'), $this->getModel()->getState('limit') );
		$dates = array('start'=>$this->getModel()->getState('fromPeriod'), 'to'=>$this->getModel()->getState('toPeriod'));
		 
		$this->pagination = $pagination;
		$this->order = $this->getModel()->getState('order');
		$this->searchword = $this->getModel()->getState('searchword');
		$this->limitstart = $this->getModel()->getState('limitstart');
		$this->lists = $lists;
		$this->orders = $orders;
		$this->items = $rows;
		$this->option = $this->getModel()->getState('option');
		$this->dates = $dates;
		$this->phoneNumberEnabled = $this->getModel()->getComponentParams()->get('tickets_form_include_phonenumber', 0);
		
		// Add meta info
		$this->_prepareDocument();
		
		parent::display($tpl);
	}

	/**
	 * Mostra la visualizzazione dettaglio del record singolo
	 * @param Object& $row
	 * @access public
	 */
	public function editEntity(&$row) {
		// Sanitize HTML Object2Form
		OutputFilter::objectHTMLSafe( $row );
		
		// Load JS Client App dependencies
		$doc = $this->app->getDocument();
		$base = Uri::root();
		$this->loadJQuery($doc);
		$this->loadJQueryUI($doc);
		$this->loadValidation($doc);
		
		$this->doc->getWebAssetManager()->registerAndUseStyle ( 'jchat.bootstrap-interface', 'components/com_jchat/css/bootstrap-interface.css');
		
		// Scripts loading
		$cParams = $this->getModel()->getComponentParams();
		$defer = $cParams->get('scripts_loading', null) == 'defer' ? true : false;
		$async = $cParams->get('scripts_loading', null) == 'async' ? true : false;
		$this->doc->getWebAssetManager()->registerAndUseScript ( 'jchat.bootstrap-interface', 'components/com_jchat/js/bootstrap-interface.js', [], ['defer'=>$defer, 'async'=>$async], ['jquery']);
		
		// Inject js translations
		$translations = array( 'COM_JCHAT_VALIDATION_ERROR', 
							   'COM_JCHAT_VALIDATION_ERROR_SUBJECT' );
		$this->injectJsTranslations($translations, $doc);
		
		$lists = $this->getModel()->getLists($row);
		$this->record = $row;
		$this->lists = $lists;
		$this->editor = Editor::getInstance(Factory::getApplication()->getConfig()->get('editor'));
		$this->nameOfUser = $this->user->name;
		$this->phoneNumberEnabled = $this->getModel()->getComponentParams()->get('tickets_form_include_phonenumber', 0);
		
		// Add meta info
		$this->_prepareDocument();
		
		parent::display ( 'edit' );
	}
	
	/**
	 * Effettua l'output view del file in attachment al browser
	 *
	 * @access public
	 * @param string $contents
	 * @param int $size
	 * @param array& $fieldsFunctionTransformation
	 * @return void
	 */
	public function sendCSVMessages($data, &$fieldsFunctionTransformation) {
		$delimiter = ';';
		$enclosure = '"';
		// Clean dirty buffer
		ob_end_clean();
		// Open buffer
		ob_start();
		// Open out stream
		$outstream = fopen("php://output", "w");
		// Funzione di scrittura nell'output stream
		$outputCSV = function (&$vals, $key, $userData) {
			// Fields value transformations 
			if(isset($vals[INDEX_WORKED])) {
				$vals[INDEX_WORKED] = $vals[INDEX_WORKED] == 1 ? Text::_('COM_JCHAT_YESWORKED') : Text::_('COM_JCHAT_NOWORKED');
			}
			if(isset($vals[INDEX_CLOSED])) {
				$vals[INDEX_CLOSED] = $vals[INDEX_CLOSED] == 1 ? Text::_('JYES') : Text::_('JNO');
			}
			
			fputcsv($userData[0], $vals, $userData[1], $userData[2]); // add parameters if you want
		};
		// Echo delle intestazioni
		$outputCSV($fieldsFunctionTransformation, null, array($outstream, $delimiter, $enclosure));
		// Output di tutti i records
		array_walk($data, $outputCSV, array($outstream, $delimiter, $enclosure));
		fclose($outstream);
		// Recupero output buffer content
		$contents = ob_get_clean();
		$size = strlen($contents);
	
	
		header ( 'Pragma: public' );
		header ( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
		header ( 'Expires: ' . gmdate ( 'D, d M Y H:i:s' ) . ' GMT' );
		header ( 'Content-Disposition: attachment; filename="tickets.csv"' );
		header ( 'Content-Type: text/plain' );
		header ( "Content-Length: " . $size );
		echo $contents;
			
		exit ();
	}
	
	/**
	 * Prepares the document
	 */
	protected function _prepareDocument() {
		$app = Factory::getApplication();
		$menus = $app->getMenu();
		$title = null;
	
		// Because the application sets a default page title,
		// we need to get it from the menu item itself
		$menu = $menus->getActive();
		if(is_null($menu)) {
			return;
		}
	
		$this->params = new Registry();
		$menuParams = $menu->getParams()->toString();
		$this->params->loadString($menuParams);
	
		$title = $this->params->get('page_title', Text::_('COM_JCHAT_TICKETS'));
		
		$this->setDocumentTitle($title);
	}
	
	/**
	 * Class constructor
	 *
	 * @param array $config
	 */
	public function __construct($config = array()) {
		// Parent view object
		parent::__construct ( $config );
	
		$joomlaConfig = $this->app->getConfig ();
		$this->joomlaConfig = $this->user->getParam ( 'timezone', $joomlaConfig->get ( 'offset' ) );
	}
}