<?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 CalcbuilderModelUtility 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' );
		$this->setId ( ( int ) $array [0] );
	}
	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($id = null) {
		$query = "select u.* from #__calcbuilder_utility u ";
		if ($id != null) {
			if (! is_numeric ( $id ))
				JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
			$query .= 'where u.id=' . $id;
		}
		$query .= " order by u.id desc";
		return $query;
	}
	function _buildQuerySelectCount() {
		$query = "select count(*) from #__calcbuilder_utility ";
		return $query;
	}
	function _buildQuerySelectFieldsOne($id, $class = 1) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		if (! is_numeric ( $class ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
			// $query = "select id, idobj,name,var, type, `decimal` , limit0, limit1,multivalue,mandatory,class,size,`order`
		$query = "select * from #__calcbuilder_field  where idobj=" . $id . " and class=" . $class . " order by `order` asc";
		return $query;
	}
	
	/*
	 * function _buildQuerySelectEvents($id){ if (!is_numeric($id)) JError::raiseError(500,JText::_('INTERNAL SERVER ERROR')); $query = "select j.* from #__calcbuilder_jsevents j where j.idutility=".$id; return $query; }
	 */
	function _buildQuerySelectAllFieldsLayout($id) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "select * from #__calcbuilder_field where idobj=" . $id;
		return $query;
	}
	function _buildQuerySelectLayoutPreference($id) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "select name, val from #__calcbuilder_layout_preferences where idutility=" . $id;
		return $query;
	}
	function _buildQuerySelectSection($id) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "select s.*,group_concat(f.idfield) as fields from #__calcbuilder_section s left join #__calcbuilder_section_field f on s.id=f.idsection 
        			where s.idutility=" . $id . " group by s.id";
		return $query;
	}
	function _buildQuerySelectSectionFields($idsection) {
		if (! is_numeric ( $idsection ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "select * from #__calcbuilder_section_field where idsection=" . $idsection;
		return $query;
	}
	function _buildQuerySelectMatrices($id, $class = 1) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		if (! is_numeric ( $class ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "select id, idobj, class, main, name, var, value
          from #__calcbuilder_matrix  where idobj=" . $id . " and class=" . $class;
		return $query;
	}
	function _buildDeleteAllFields($id, $class = 1, $arrValidFields) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		if (! is_numeric ( $class ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "delete from #__calcbuilder_field where idobj=" . $id . " and class=" . $class;
		if (strlen ( trim ( implode ( ',', $arrValidFields ) ) ) > 0) {
			$query .= " and id not in (" . implode ( ',', $arrValidFields ) . ")";
		}
		return $query;
	}
	function _buildDeleteAllMultivalues($id, $arrValidMVs) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "delete from #__calcbuilder_field_multivalue where idobj=" . $id;
		if (strlen ( trim ( implode ( ',', $arrValidMVs ) ) ) > 0) {
			$query .= " and id not in (" . implode ( ',', $arrValidMVs ) . ")";
		}
		return $query;
	}
	function _buildDeleteAllMatrices($id, $class = 1) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		if (! is_numeric ( $class ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "delete from #__calcbuilder_matrix where idobj=" . $id . " and class=" . $class;
		return $query;
	}
	function _buildDeleteAllStats($id) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "delete from #__calcbuilder_stats where idobj=" . $id;
		return $query;
	}
	function _buildDeleteAllLayoutPreferences($id) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "delete from #__calcbuilder_layout_preferences where idutility=" . $id;
		return $query;
	}
	
	/*
	 * function _buildDeleteAllEvents($id){ if (!is_numeric($id)) JError::raiseError(500,JText::_('INTERNAL SERVER ERROR')); $query = "delete from #__calcbuilder_jsevents where idutility=".$id; return $query; }
	 */
	function _buildDeleteAllSectionsField($idsection) {
		if (! is_numeric ( $idsection ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "delete from #__calcbuilder_section_field where idsection=" . $idsection;
		return $query;
	}
	function _buildDeleteAllSection($ids, $idutility) {
		if (! is_numeric ( $idutility ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "delete from #__calcbuilder_section where idutility=" . $idutility;
		if (count ( $ids ) > 0)
			$query .= " and id not in(" . implode ( ',', $ids ) . ")";
		return $query;
	}
	function _buildSelectMultivalues($id) {
		if (! is_numeric ( $id ))
			JError::raiseError ( 500, JText::_ ( 'INTERNAL SERVER ERROR' ) );
		$query = "select * from #__calcbuilder_field_multivalue where idobj=" . $id . " order by ord";
		return $query;
	}
	function _buildQueryInsertSection($section) {
		$query = "insert into #__calcbuilder_section ('idutility','name','addbutton','defaultsections','limitsections','layout')
    		values ('" . $section ['idutility'] . "','" . $section ['name'] . "','" . $section ['addbutton'] . "','" . $section ['defaultsections'] . "',
    		'" . $section ['limitsections'] . "','" . $section ['layout'] . "')";
		return $query;
	}
	function getData() {
		jimport ( 'joomla.html.pagination' );
		$mainframe = JFactory::getApplication ();
		$limit = MSHelper::__requestGetVarWrapper ( 'limit', $mainframe->getCfg ( 'list_limit' ) );
		$limitstart = MSHelper::__requestGetVarWrapper ( 'limitstart', 0 );
		$db = JFactory::getDBO ();
		$query = $this->_buildQuerySelectCount ();
		$db->setQuery ( $query );
		$total = $db->loadResult ();
		$query = $this->_buildQuerySelect ();
		$db->setQuery ( $query, $limitstart, $limit );
		$this->_pageNav = new JPagination ( $total, $limitstart, $limit );
		return $db->loadObjectList ();
	}
	function getDataOne() {
		$db = JFactory::getDBO ();
		$query = $this->_buildQuerySelect ( $this->_id );
		$db->setQuery ( $query );
		return $db->loadAssoc ();
	}
	function getDataFields() {
		$db = JFactory::getDBO ();
		$query = $this->_buildQuerySelectFieldsOne ( $this->_id, 1 );
		$db->setQuery ( $query );
		return $db->loadObjectList ();
	}
	
	/*
	 * function getDataEvents() { $db = JFactory::getDBO(); $query = $this->_buildQuerySelectEvents($this->_id); $db->setQuery($query); return $db->loadObject(); }
	 */
	function getDataAllFieldsLayout() {
		$db = JFactory::getDBO ();
		$query = $this->_buildQuerySelectAllFieldsLayout ( $this->_id );
		$db->setQuery ( $query );
		return $db->loadObjectList ( 'id' );
	}
	function getDataSections() {
		$db = JFactory::getDBO ();
		$query = $this->_buildQuerySelectSection ( $this->_id );
		$db->setQuery ( $query );
		return $db->loadObjectList ();
	}
	function getDataLayoutPreference() {
		$db = JFactory::getDBO ();
		$query = $this->_buildQuerySelectLayoutPreference ( $this->_id );
		$db->setQuery ( $query );
		return $db->loadObjectList ( 'name' );
	}
	function getMatrices() {
		$db = JFactory::getDBO ();
		$query = $this->_buildQuerySelectMatrices ( $this->_id, 1 );
		$db->setQuery ( $query );
		return $db->loadObjectList ();
	}
	function getMultivalues() {
		$db = JFactory::getDBO ();
		$query = $this->_buildSelectMultivalues ( $this->_id );
		$db->setQuery ( $query );
		return $db->loadObjectList ();
	}
	function getExcel(){
		$excel=$this->_getTableObjectArray('#__calcbuilder_excel','idobj='.$this->_id)->getProperty('data');
		if($excel&&isset($excel['id'])):
			$mappings=$this->_getTableObjectArray('#__calcbuilder_excel_mapping','idexcel='.$excel['id'],null,true)->getProperty('data');
			return array('excel'=>$excel,'mapping'=>$mappings);
		else:
			return array();
		endif;
	}
	
	/**
	 * Method to store a record
	 *
	 * @access public
	 * @return boolean True on success
	 */
	function store() {
		$db = JFactory::getDBO ();
		$row = $this->getTable ();
		// $data = JRequest::get( 'post' );
		$data = $_POST;
		$data ['code'] = MSHelper::__requestGetVarWrapper ( 'code', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['preformhtml'] = MSHelper::__requestGetVarWrapper ( 'preformhtml', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['precalcprint'] = MSHelper::__requestGetVarWrapper ( 'precalcprint', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['poscalcprint'] = MSHelper::__requestGetVarWrapper ( 'poscalcprint', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['precalcprintpdf'] = MSHelper::__requestGetVarWrapper ( 'precalcprintpdf', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['poscalcprintpdf'] = MSHelper::__requestGetVarWrapper ( 'poscalcprintpdf', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['js_event_code'] = MSHelper::__requestGetVarWrapper ( 'js_event_code', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['js_functions'] = MSHelper::__requestGetVarWrapper ( 'js_functions', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['js_pre_calc_button'] = MSHelper::__requestGetVarWrapper ( 'js_pre_calc_button', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['js_post_calc_button'] = MSHelper::__requestGetVarWrapper ( 'js_post_calc_button', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data ['js_reset_button'] = MSHelper::__requestGetVarWrapper ( 'js_reset_button', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		// 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;
		}
		
		// Fields
		$a_fields = json_decode ( $_POST['fields'], true );
		$arrValidFields = array ();
		$arrValidMVs = array ();
		if ($a_fields != null) {
			foreach ( $a_fields as $field ) {
				$rowField = $this->getTable ( 'field' );
				$isValid = (($field ['name'] != null && $field ['name'] != '') && ($field ['var'] != null && $field ['var'] != ''));
				if ($isValid) {
					$field ['idobj'] = $row->id;
					$field ['class'] = 1;
					if (isset ( $field ['id'] ))
						$rowField->load ( $field ['id'] );
					if (! $rowField->bind ( $field )) {
						$this->setError ( $row->getError () );
						return false;
					}
					if (! $rowField->check ()) {
						$this->setError ( $row->getError () );
						return false;
					}
					if (! $rowField->store ()) {
						$this->setError ( $row->getError () );
						return false;
					}
					// Multivalue
					$arr_mv_name = $field ['mvname'];
					$arr_mv_val = $field ['mvval'];
					$arr_mvid = $field ['mvid'];
					$arrInsertMultivalue = null;
					for($i = 0; $i < count ( $arr_mv_name ); $i ++) {
						$rowFieldMultivalue = $this->getTable ( 'fieldmultivalue' );
						$arrInsertMultivalue = array ();
						$arrInsertMultivalue ['idfield'] = $rowField->id;
						$arrInsertMultivalue ['idobj'] = $row->id;
						$arrInsertMultivalue ['name'] = $arr_mv_name [$i];
						$arrInsertMultivalue ['value'] = $arr_mv_val [$i];
						$arrInsertMultivalue ['id'] = $arr_mvid [$i];
						$arrInsertMultivalue ['ord'] = $i;
						if (strlen ( $arrInsertMultivalue ['id'] ) > 0)
							$rowFieldMultivalue->load ( $arrInsertMultivalue ['id'] );
						if (! $rowFieldMultivalue->bind ( $arrInsertMultivalue )) {
							$this->setError ( $rowFieldMultivalue->getError () );
							return false;
						}
						if (! $rowFieldMultivalue->check ()) {
							$this->setError ( $rowFieldMultivalue->getError () );
							return false;
						}
						if (! $rowFieldMultivalue->store ()) {
							$this->setError ( $rowFieldMultivalue->getError () );
							return false;
						}
						$arrValidMVs [] = $rowFieldMultivalue->id;
					}
					$arrValidFields [] = $rowField->id;
				}
			}
			// Delete fields
			$query = $this->_buildDeleteAllFields ( $row->id, 1, $arrValidFields );
			$db->setQuery ( $query );
			if (! $db->query ()) {
				$this->setError ( $row->getError () );
			}
			// Delete multivalues
			$query = $this->_buildDeleteAllMultivalues ( $row->id, $arrValidMVs );
			$db->setQuery ( $query );
			if (! $db->query ()) {
				$this->setError ( $row->getError () );
			}
		}
		
		// Sections
		$a_sections = json_decode ( MSHelper::__requestGetVarWrapper ( 'sections' ), true );
		$arr_Insertadas = array ();
		if ($a_sections):
			foreach ( $a_sections as $section ) {
				$rowSection = $this->getTable ( 'cbsection' );
				$section ['idutility'] = $row->id;
				if ($section ['id'] != null)
					$rowSection->load ( $section ['id'] );
				if (! $rowSection->bind ( $section )) {
					$this->setError ( $rowSection->getError () );
					return false;
				}
				if (! $rowSection->check ()) {
					$this->setError ( $rowSection->getError () );
					return false;
				}
				if (! $rowSection->store ()) {
					$this->setError ( $rowSection->getError () );
					return false;
				}
				$query = $this->_buildDeleteAllSectionsField ( $rowSection->id );
				$db->setQuery ( $query );
				if (! $db->query ()) {
					$this->setError ( 'Delete Error' );
				}
				$arr_fields = $section ['fields'];
				foreach ( $arr_fields as $fieldsec ) {
					$arrInsertField = array ();
					$arrInsertField ['idsection'] = $rowSection->id;
					$arrInsertField ['idfield'] = $fieldsec;
					$rowSectionField = & $this->getTable ( 'cbsectionfield' );
					if (! $rowSectionField->bind ( $arrInsertField )) {
						$this->setError ( $rowSectionField->getError () );
						return false;
					}
					if (! $rowSectionField->check ()) {
						$this->setError ( $rowSectionField->getError () );
						return false;
					}
					if (! $rowSectionField->store ()) {
						$this->setError ( $rowSectionField->getError () );
						return false;
					}
				}
				$arr_Insertadas [] = $rowSection->id;
			}
		endif;
		$query = $this->_buildDeleteAllSection ( $arr_Insertadas, $row->id );
		$db->setQuery ( $query );
		if (! $db->query ()) {
			$this->setError ( 'Delete Error' );
		}
		/*SHPInit3*/
		// VM Products
		$query = $this->_buildDeleteAllVMProducts($row->id);
		$db->setQuery( $query );
		if (!$db->query()) {
			$this->setError('Delete Error');
		}
		$arrProducts=JRequest::getVar('vm_product',null,'post','array');
		for ($i=0;$i<count($arrProducts);$i++){
			$product=$arrProducts[$i];
			$idproduct=$arrIdProducts[$i];
			$dataVM=array();
			$dataVM['idvmproduct']=$product;
			$dataVM['idobj']=$row->id;
			$rowVMProduct =$this->getTable('vmproducts');
			if (!$rowVMProduct->bind($dataVM)) {
				$this->setError($rowVMProduct->getErrorMsg());
				return false;
			}
			if (!$rowVMProduct->check()) {
				$this->setError($rowVMProduct->getErrorMsg());
				return false;
			}
			if (!$rowVMProduct->store()) {
				$this->setError($rowVMProduct->getErrorMsg());
				return false;
			}
		}
		/*SHPEnd3*/
		
		return $row->id;
	}
	function importsave() {
		$utility = array ();
		$arrFields = array ();
		$matrices = array ();
		$sections = array ();
		$multivalues = array ();
		$arrEvents = array ();
		$excel = array ();
		$excelmappings = array ();
		$importfile = MSHelper::__requestGetVarWrapper ( 'datafile', null, 'files', 'array' );
		if (isset ( $importfile )) {
			$filename = JFile::makeSafe ( $importfile ['name'] );
			if ($filename) {
				$xml = simplexml_load_file ( $importfile ['tmp_name'] );
				foreach ( $xml->utility->children () as $flds ) {
					if (strlen ( ( string ) $flds ) > 0 && $flds->getName () != 'id')
						$utility [$flds->getName ()] = ( string ) $flds;
				}
				$arrField = array ();
				foreach ( $xml->fields->children () as $field ) {
					foreach ( $field->children () as $flds ) {
						if ($flds->getName () == 'id')
							$arrField ['idant'] = ( string ) $flds;
						elseif (strlen ( ( string ) $flds ) > 0)
							$arrField [$flds->getName ()] = ( string ) $flds;
					}
					$arrMV = array ();
					if (strlen ( ( string ) $field->multivalue ) > 0) {
						$multivalues = explode ( '&', $field->multivalue );
						for($i = 0; $i < count ( $multivalues ); $i ++) {
							$arrmulti = array ();
							$option = explode ( '#', $multivalues [$i] );
							$arrmulti ['name'] = ( string ) $option [0];
							$arrmulti ['value'] = ( string ) $option [1];
							$arrMV [] = $arrmulti;
						}					
					}
					foreach ( $field->multivalues->children () as $multivalue ) {
						$arrmulti = array ();
						strlen ( ( string ) $multivalue->name ) > 0 ? $arrmulti ['name'] = ( string ) $multivalue->name : '';
						strlen ( ( string ) $multivalue->value ) > 0 ? $arrmulti ['value'] = ( string ) $multivalue->value : '';
						$arrMV [] = $arrmulti;
					}
					$arrField ['multivalues'] = $arrMV;
					$arrFields [] = $arrField;
					unset ( $arrField );
				}
				foreach ( $xml->matrices->children () as $matrix ) {
					foreach ( $matrix->children () as $flds ) {
						if (strlen ( ( string ) $flds ) > 0)
							$arrField [$flds->getName ()] = ( string ) $flds;
					}
					$matrices [] = $arrField;
					unset ( $arrField );
				}
				foreach ( $xml->sections->children () as $section ) {
					foreach ( $section->children () as $flds ) {
						if (strlen ( ( string ) $flds ) > 0)
							$arrField [$flds->getName ()] = ( string ) $flds;
					}
					$arrSecFields = array ();
					foreach ( $section->section_field->children () as $field ) {
						$arrSecField = array ();
						strlen ( ( string ) $field->idfield ) > 0 ? $arrSecField ['idfield'] = ( string ) $field->idfield : '';
						$arrSecFields [] = $arrSecField;
					}
					$arrField ['section_fields'] = $arrSecFields;
					
					$sections [] = $arrField;
					unset ( $arrField );
				}
				// Excel
				if (isset($xml->excel)):
					foreach ( $xml->excel->children () as $flds ) {
						if (strlen ( ( string ) $flds ) > 0 && $flds->getName () != 'id')
							$excel [$flds->getName ()] = ( string ) $flds;
					}
					// Excel Mappings
					foreach ( $xml->excelmapping->children () as $mapping ) {
						foreach ( $mapping->children () as $flds ) {
							if (strlen ( ( string ) $flds ) > 0 && $flds->getName () != 'id')
								$arrField [$flds->getName ()] = ( string ) $flds;
						}
						$excelmappings [] = $arrField;
						unset ( $arrField );
					}
				endif;
			}
		}
		
		$db = JFactory::getDBO ();
		$row = $this->getTable ( 'utility' );
		if (!$row->bind ( $utility )) {
			$this->setError ( $row->getError () );
			return false;
		}
		if (!$row->check ()) {
			$this->setError ( $row->getError () );
			return false;
		}
		if (!$row->store ()) {
			$this->setError ( $row->getError () );
			return false;
		}
		$idobj = $row->id;
		$fields_ant = array ();
		
		foreach ( $arrFields as $fieldelem ) {
			$row = $this->getTable ( 'field' );
			$fieldelem ['idobj'] = $idobj;
			$fieldelem ['id'] = null;
			if (! $row->bind ( $fieldelem )) {
				$this->setError ( $row->getError () );				
				return false;
			}
			if (! $row->check ()) {
				$this->setError ( $row->getError () );				
				return false;
			}
			if (! $row->store ()) {
				$this->setError ( $row->getError () );
				return false;
			}
			foreach ( $fieldelem ['multivalues'] as $multivalue ) {
				$rowMV = $this->getTable ( 'fieldmultivalue' );
				$multivalue ['idfield'] = $row->id;
				$multivalue ['idobj'] = $idobj;
				$multivalue ['id'] = null;
				if (! $rowMV->bind ( $multivalue )) {
					$this->setError ( $rowMV->getError () );
					return false;
				}
				if (! $rowMV->check ()) {
					$this->setError ( $rowMV->getError () );
					return false;
				}
				if (! $rowMV->store ()) {
					$this->setError ( $rowMV->getError () );
					return false;
				}
			}
			$fields_ant [$fieldelem ['idant']] = $row->id;
		}
		foreach ( $matrices as $fieldelem ) {
			$row = $this->getTable ( 'matrix' );
			$fieldelem ['idobj'] = $idobj;
			$fieldelem ['id'] = null;
			if (! $row->bind ( $fieldelem )) {
				$this->setError ( $row->getError () );
				return false;
			}
			if (! $row->check ()) {
				$this->setError ( $row->getError () );
				return false;
			}
			if (! $row->store ()) {
				$this->setError ( $row->getError () );
				return false;
			}
		}		
		foreach ( $sections as $fieldelem ) {						
			$row = $this->getTable ( 'cbsection' );
			$fieldelem ['idutility'] = $idobj;
			unset ( $fieldelem ['id'] );
			if (! $row->bind ( $fieldelem )) {
				$this->setError ( $row->getError () );
				return false;
			}
			if (! $row->check ()) {
				$this->setError ( $row->getError () );
				return false;
			}
			if (! $row->store ()) {
				$this->setError ( $row->getError () );
				return false;
			}
			$secId = $row->id;
			foreach ( $fieldelem ['section_fields'] as $secfields ) {
				$rowField = $this->getTable ( 'cbsectionfield' );
				$secfields ['idsection'] = $secId;
				$secfields ['idfield'] = $fields_ant [$secfields ['idfield']];
				unset ( $secfields ['id'] );
				if (! $rowField->bind ( $secfields )) {
					$this->setError ( $rowField->getError () );
					return false;
				}
				if (! $rowField->check ()) {
					$this->setError ( $rowField->getError () );
					return false;
				}
				if (! $rowField->store ()) {
					$this->setError ( $rowField->getError () );
					return false;
				}
			}			
		}

		/*SHPInit1*/
		// Excel
		if (count($excel)>0):
			$excel['idobj']=$idobj;
			$idexcel=$this->_storeArray('#__calcbuilder_excel', $excel);
			// ExcelMapping
			foreach ($excelmappings as $mapping):
				$mapping['idexcel']=$idexcel;
				$this->_storeArray('#__calcbuilder_excel_mapping', $mapping);
			endforeach;
		endif;
		/*SHPEnd1*/
		return $idobj;
	}
	
	/**
	 * 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->getErrorMsg () );
				return false;
			}
			$query = $this->_buildDeleteAllFields ( $cid, 1 );
			$db->setQuery ( $query );
			if (! $db->query ()) {
				$this->setError ( $row->getError () );
			}
			$query = $this->_buildDeleteAllMatrices ( $cid, 1 );
			$db->setQuery ( $query );
			if (! $db->query ()) {
				$this->setError ( $row->getError () );
			}
			$query = $this->_buildDeleteAllStats ( $cid );
			$db->setQuery ( $query );
			if (! $db->query ()) {
				$this->setError ( $row->getError () );
			}
			$idexcel=$this->_getTableObject('#__calcbuilder_excel','idobj='.$cid)->getProperty('data');
			if($idexcel):			
				$this->_delete('#__calcbuilder_excel_mapping','idexcel='.$idexcel->id);
				$this->_delete('#__calcbuilder_excel','idobj='.$cid);
			endif;
		}
		return true;
	}
	function storeexitlayout() {
		// $data = JRequest::get( 'post' );
		$data = $_POST;
		$db = & JFactory::getDBO ();
		$tem_arr = array ();
		$tem_arr ['id'] = $data ['id'];
		$tem_arr ['exitlayout'] = MSHelper::__requestGetVarWrapper ( 'exitlayout', '', 'post', 'string', JREQUEST_ALLOWHTML );
		$row = & $this->getTable ( 'utility' );
		$row->load ( $data ['id'] );
		if (! $row->bind ( $tem_arr )) {
			$this->setError ( $row->getError () );
			return false;
		}
		if (! $row->check ()) {
			$this->setError ( $row->getError () );
			return false;
		}
		if (! $row->store ()) {
			$this->setError ( $row->getError () );
			return false;
		}
		return $data ['id'];
	}
	function storelayout() {
		// $data = JRequest::get( 'post' );
		$data = $_POST;
		$db = JFactory::getDBO ();
		$tem_arr = array ();
		$tem_arr ['id'] = $data ['id'];
		// $tem_arr['formtype']=$data['formtype'];
		$tem_arr ['layout'] = MSHelper::__requestGetVarWrapper ( 'layout_A', '', 'post', 'string', JREQUEST_ALLOWHTML );
		$tem_arr ['layout_position'] = MSHelper::__requestGetVarWrapper ( 'layout_position' );
		$tem_arr ['form_layout_width'] = MSHelper::__requestGetVarWrapper ( 'form_layout_width' );
		$row = & $this->getTable ( 'utility' );
		$row->load ( $data ['id'] );
		if (! $row->bind ( $tem_arr )) {
			$this->setError ( $row->getError () );
			return false;
		}
		if (! $row->check ()) {
			$this->setError ( $row->getError () );
			return false;
		}
		if (! $row->store ()) {
			$this->setError ( $row->getError () );
			return false;
		}
		
		$secciones = $this->getDataSections ();
		foreach ( $secciones as $seccion ) {
			$row = & $this->getTable ( 'cbsection' );
			$row->load ( $seccion->id );
			$arr_elems = array ();
			$arr_elems ['layout'] = MSHelper::__requestGetVarWrapper ( 'layout_' . $seccion->id, '', 'post', 'string', JREQUEST_ALLOWHTML );
			if (! $row->bind ( $arr_elems )) {
				$this->setError ( $row->getError () );
				return false;
			}
			if (! $row->check ()) {
				$this->setError ( $row->getError () );
				return false;
			}
			if (! $row->store ()) {
				$this->setError ( $row->getError () );
				return false;
			}
		}
		
		return $data ['id'];
	}
/*SHPInit2*/
	function _buildDeleteAllVMProducts($idutility){
		$query = "delete from #__calcbuilder_vm_products where idobj=".$idutility;
		return $query;
	}
	
	function _buildSelectVmproducts($id){
		$query = "select * from #__calcbuilder_vm_products where idobj=".$id;
		return $query;
	}
	function getVmproducts(){
		$db = JFactory::getDBO();
		$query = $this->_buildSelectVmproducts($this->_id);
		$db->setQuery($query);
		$listProducts=$db->loadObjectList();
		$ret=array();
		if ($this->validateComponent('com_virtuemart','011')){
			if (!class_exists( 'VmConfig' )) require(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_virtuemart'.DS.'helpers'.DS.'config.php');
			VmConfig::loadConfig();
			foreach($listProducts as $product){
				$productModel = VmModel::getModel('Product');
				$vmproduct=$productModel->getProduct($product->idvmproduct);
				$ret[$product->idvmproduct]=$vmproduct->product_name;
			}
		}
		return $ret;
	}
	
	function getVMExport(){
		$db = JFactory::getDBO();
		$query = $this->_buildSelectVmproducts($this->_id);
		$db->setQuery($query);
		return $db->loadAssocList();
	}
/*SHPEnd2*/
	
}

?>

