<?php
/*
 * @component Calc Builder 
 * @copyright Copyright (C) January 2017. 
 * @license GPL 3.0 
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details. 
 * See <http://www.gnu.org/licenses/>. 
 * More info www.moonsoft.es 
 * gestion@moonsoft.es
 */

// Check to ensure this file is included in Joomla!
defined ( '_JEXEC' ) or die ();

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

require 'wrapper.model.php';
class CalcbuilderModelMatrix extends wrapperMainModel {
	var $_id;
	var $_pageNav;
	
	/**
	 * Constructor that retrieves the ID from the request
	 *
	 * @access public
	 * @return void
	 */
	function __construct() {
		parent::__construct ();
		$this->_id = null;
		$array = MSHelper::__requestGetVarWrapper ( 'cid', - 1, '', 'array' );
		/*
		 * $_class = MSHelper::__requestGetVarWrapper('class', -1); $_obj = MSHelper::__requestGetVarWrapper('obj', -1);
		 */
		$this->setId ( ( int ) $array [0] );
	}
	
	/**
	 * Method to set the hello identifier
	 *
	 * @access public
	 * @param
	 *        	int Hello identifier
	 * @return void
	 */
	function setId($id) {
		$this->_id = $id;
	}
	function getPageNav() {
		return $this->_pageNav;
	}
	
	/**
	 * Returns the query
	 * 
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function _buildQuerySelect($idobj, $class = 0, $id = null) {
		if (! is_numeric ( $idobj ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		if (! is_numeric ( $class ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "select id, name,var, value,main 
          from #__calcbuilder_matrix where class=" . $class . " and idobj=" . $idobj;
		if ($id != null) {
			if (! is_numeric ( $id ))
				JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
			$query .= ' and id=' . $id;
		}
		return $query;
	}
	function _buildQuerySelectCount($idobj, $class) {
		if (! is_numeric ( $idobj ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		if (! is_numeric ( $class ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "select count(*) from #__calcbuilder_matrix where class=" . $class . " and idobj=" . $idobj;
		return $query;
	}
	function _buildQuerySelectDescObj($idobj, $class = 0) {
		if (! is_numeric ( $idobj ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		if (! is_numeric ( $class ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query;
		switch ($class) {
			case 0 :
				$query = "select name from #__calcbuilder_product where id=" . $idobj;
				break;
			case 1 :
				$query = "select name from #__calcbuilder_utility where id=" . $idobj;
				break;
		}
		return $query;
	}
	
	/**
	 * Retrieves the hello data
	 * 
	 * @return array Array of objects containing the data from the database
	 */
	function getData() {
		jimport ( 'joomla.html.pagination' );
		$mainframe = JFactory::getApplication ();
		$limit = MSHelper::__requestGetVarWrapper ( 'limit', $mainframe->getCfg ( 'list_limit' ) );
		$limitstart = MSHelper::__requestGetVarWrapper ( 'limitstart', 0 );
		$idobj = MSHelper::__requestGetVarWrapper ( 'idobj', 0 );
		$class = MSHelper::__requestGetVarWrapper ( 'class', 0 );
		$db = JFactory::getDBO ();
		$query = $this->_buildQuerySelectCount ( $idobj, $class );
		$db->setQuery ( $query );
		$total = $db->loadResult ();
		$query = $this->_buildQuerySelect ( $idobj, $class );
		$db->setQuery ( $query, $limitstart, $limit );
		$this->_pageNav = new JPagination ( $total, $limitstart, $limit );
		return $db->loadObjectList ();
	}
	function getIdobj() {
		$idobj = MSHelper::__requestGetVarWrapper ( 'idobj', 0 );
		return $idobj;
	}
	function getClass() {
		$class = MSHelper::__requestGetVarWrapper ( 'class', 0 );
		return $class;
	}
	function getDscObj() {
		$db = JFactory::getDBO ();
		$idobj = MSHelper::__requestGetVarWrapper ( 'idobj', 0 );
		$class = MSHelper::__requestGetVarWrapper ( 'class', 0 );
		$query = $this->_buildQuerySelectDescObj ( $idobj, $class );
		$db->setQuery ( $query );
		return $db->loadResult ();
	}
	function getDataOne() {
		$db = JFactory::getDBO ();
		$idobj = MSHelper::__requestGetVarWrapper ( 'idobj', 0 );
		$class = MSHelper::__requestGetVarWrapper ( 'class', 0 );
		$query = $this->_buildQuerySelect ( $idobj, $class, $this->_id );
		$db->setQuery ( $query );
		return $db->loadAssoc ();
	}
	
	/**
	 * Method to store a record
	 *
	 * @access public
	 * @return boolean True on success
	 */
	function store() {
		$row = $this->getTable ();
		// $data = JRequest::get('post');
		$data = $_POST;
		
		// \n
		// $data['csv'] = MSHelper::__requestGetVarWrapper('csv', '', 'post', 'string', JREQUEST_ALLOWRAW);
		$linedelimiter = $data ['linedelimiter'] != '' ? $data ['linedelimiter'] : chr ( 13 );
		$delimiter = $data ['delimiter'] != '' ? $data ['delimiter'] : ';';
		$data ['value'] = trim ( $data ['csv'] );
		if (strlen ( $data ['csv'] ) > 0) {
			$value = 'array(';
			$arrFilas = explode ( $linedelimiter, $data ['csv'] );
			$arrNombreColumna = explode ( $delimiter, $arrFilas [0] );
			for($i = 1; $i < count ( $arrFilas ); $i ++) {
				$arrColumnas = explode ( $delimiter, $arrFilas [$i] );
				if ($i > 1)
					$value .= ",";
				$value .= '"' . trim ( $arrColumnas [0] ) . '"=>array(';
				for($j = 1; $j < count ( $arrColumnas ); $j ++) {
					if ($j > 1)
						$value .= ",";
						// $value.='"'.trim($arrNombreColumna[$j]).'"=>"'.trim($arrColumnas[$j]).'"';
					$value .= '"' . trim ( $arrNombreColumna [$j] ) . '"=>"' . str_replace ( '\"', '&quot;', trim ( $arrColumnas [$j] ) ) . '"';
				}
				$value .= ')';
			}
			$value .= ')';
			$data ['value'] = trim ( $value );
		} else {
			$contadorRowsCorrectas = 0;
			// Si la versión de php es 5.2.17 o menor 
			// $arr_fields = json_decode ( str_replace ( '\\"', '"', $data ['fields'] ), true );
			$arr_fields = json_decode ( $data ['fields'], true );
			$value = 'array(';
			foreach ( $arr_fields as $rowsIn ) {
				// $value.='array(';
				foreach ( $rowsIn as $keyRow => $rows ) {
					if ($contadorRowsCorrectas > 0)
						$value .= ",";
					$value .= '"' . $keyRow . '"=>array(';
					// Rows
					$contador_temp_cols = 0;
					foreach ( $rows as $key => $field ) {
						if ($contador_temp_cols > 0)
							$value .= ",";
						$value .= '"' . $key . '"=>"' . str_replace ( '"', '&quot;', $field ) . '"';
						$contador_temp_cols ++;
					}
					$value .= ')';
					$contadorRowsCorrectas ++;
				}
				// $value.=')';
			}
			$value .= ')';
			$data ['value'] = trim ( $value );
		}
		
		// $data['value']=$data['csv'];
		// Bind the form fields to the hello table
		if (! $row->bind ( $data )) {
			$this->setError ( $row->getError () );
			return false;
		}
		
		// Make sure the hello record is valid
		if (! $row->check ()) {
			$this->setError ( $row->getError () );
			return false;
		}
		
		// Store the web link table to the database
		if (! $row->store ()) {
			$this->setError ( $row->getError () );
			return false;
		}
		return $row->id;
	}
	function stripslashes_deep($value) {
		$value = is_array ( $value ) ? array_map ( "stripslashes_deep", $value ) : stripslashes ( $value );
		return $value;
	}
	
	/**
	 * Method to delete record(s)
	 *
	 * @access public
	 * @return boolean True on success
	 */
	function delete() {
		$cids = MSHelper::__requestGetVarWrapper ( 'cid', array (
				0 
		), 'post', 'array' );
		$row = & $this->getTable ();
		$db = & JFactory::getDBO ();
		foreach ( $cids as $cid ) {
			if (! $row->delete ( $cid )) {
				$this->setError ( $row->getError () );
				return false;
			}
		}
		return true;
	}
}

?>
