<?php

/**
* @version 2.8.14
* @package Joomla 2.5
* @subpackage DT Register
* @copyright Copyright (C) 2006 DTH Development
* @copyright contact dthdev@dthdevelopment.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

class DtregisterModelExport extends DtrModel {
	public static $limit = 20;
	function __construct($config = array()){
	   
	   parent::__construct($config);
	   $this->table = new TableExport($this->getDBO());
	   $this->generalFields = array(
	   							   'event_date'=> JText::_('DT_EVENT_DATE'),
								   'event_time'=> JText::_('DT_EVENT_TIME'),
	                               'type'=> JText::_('DT_USER_TYPE'),
								   'amount'=> JText::_('DT_AMOUNT'),
								   'payment_type'=> JText::_('DT_PAYMENT_TYPE'),
								   'paid'=>JText::_('DT_PAYMENT_STATUS'),
								   'paid_amount'=>JText::_('DT_AMOUNT_PAID'),
								   'memtot'=> JText::_('DT_NUMBER_MEMBERS'),
								   'confirmNum'=> JText::_('DT_CONFIRMATION_NUMBER'),
								   'code'=> JText::_('DT_DISCOUNT_CODE'),
								   'category'=> JText::_('DT_CATEGORY'),
								   'location'=> JText::_('DT_LOCATION'),
								   'user_id'=>JText::_('DT_JOOMLA_USERID'),
								    'attend' =>JText::_('DT_ATTENDED'),
								   'status'=> JText::_('DT_STATUS'),
								   'transaction_id'=> JText::_('DT_TRANSACTION_ID'),
								   'userId'=> JText::_('DT_USER_ID'),
								   'offline_payment_data'=> JText::_('DT_OFFLINE_PAYMENT'),
								   'tax_exemption'=> JText::_('DT_TAX_EXEMPTION') ,
								   
								   'tax_exemption_code'=> JText::_('DT_TAX_EXEMPTION_CODE') ,
	                             );

	}
	
	function prepareEventoptions($events=array()){
	   	$tevt =& DtrTable::getInstance('Event','Table');
		$options = array();
		
		if (count($events) > 0) {
			foreach($events as $event){
				$tevt->load($event->slabId);
				$options[$event->slabId] = $tevt->displayTitleExport();
			}
		}
		return $options;
	}
}

class TableExport extends DtrTable{
    
	var $id;
	var $events = array();
	var $group_export_fields = array();
	var $general_export_fields = array();
	var $individual_export_fields = array();
	var $group_reg = 0;
	
    function __construct( &$db = null ) {

	     $db = &JFactory::getDBO();

	     parent::__construct( '#__dtregister_export_settings', 'id', $db );
		 $this->UserModel =& DtrModel::getInstance('User','DtregisterModel');
		 $this->pmethod =& DtrModel::getInstance('paymentmethod','DtregisterModel');
		 $this->feeModel =& DtrModel::getInstance('fee','DtregisterModel');
		 $this->Tablefield  =& DtrTable::getInstance('Field','Table');
		 $this->generalFields = array(
		 						   'event_date'=> JText::_('DT_EVENT_DATE'),
								   'event_time'=> JText::_('DT_EVENT_TIME'),
	                               'type'=> JText::_('DT_USER_TYPE'),
								   'amount'=> JText::_('DT_AMOUNT'),
								   'payment_type'=> JText::_('DT_PAYMENT_TYPE'),
								   'paid'=>JText::_('DT_PAYMENT_STATUS') ,
								   'paid_amount'=>JText::_('DT_AMOUNT_PAID') ,
								   'memtot'=> JText::_('DT_NUMBER_MEMBERS'),
								   'confirmNum'=> JText::_('DT_CONFIRMATION_NUMBER'),
								   'code'=> JText::_('DT_DISCOUNT_CODE'),
								   'category'=> JText::_('DT_CATEGORY'),
								   'location'=> JText::_('DT_LOCATION'),
								   'user_id'=>JText::_('DT_JOOMLA_USERID'), 
								   'attend' =>JText::_('DT_ATTENDED'),
								   'status'=> JText::_('DT_STATUS'),
								   'transaction_id'=> JText::_('DT_TRANSACTION_ID'),
								   'userId'=> JText::_('DT_USER_ID'),
								   'offline_payment_data'=> JText::_('DT_OFFLINE_PAYMENT'),
								   'tax_exemption'=> JText::_('DT_TAX_EXEMPTION') ,
								   
								   'tax_exemption_code'=> JText::_('DT_TAX_EXEMPTION_CODE') ,
	                             );
		
		$fieldType = DtrModel::getInstance('Fieldtype','DtregisterModel');
        $this->fieldTypes = $fieldType->getTypes();
		
	}
	
	function getUsers_all_import($datefrom="", $dateto="",$last_modified=""){
	   	
		//$where[] = " eventId in(".implode(",",$this->events).") ";
		//$where[] = array("1=1");
		$dateto_con = "";
        $datefrom_con = ""; // CAST('2000-01-01' AS DATE)
	    if($datefrom!=""){
	
		   $datefrom = strftime('%Y-%m-%d %H:%M:%S', strtotime($datefrom));
	       $where[] = " register_date >= '$datefrom' ";
	
		}
	    if($dateto!=""){
	
		   $dateto = strftime('%Y-%m-%d %H:%M:%S', strtotime($dateto." + 1 day"));
	       $where[] = "  register_date  <= '$dateto' "; 
		
		}
		
		 if($last_modified!=""){
	
		   $last_modified = strftime('%Y-%m-%d %H:%M:%S', strtotime($last_modified));
	       $where[] = "  modified_on  >= '$last_modified' ";
		   
		   $modified_on = strftime('%Y-%m-%d %H:%M:%S', strtotime($last_modified." + 1 day"));
	       $where[] = "  modified_on  <= '$modified_on' "; 
		
		}
		/*if(isset($_REQUEST['status']) && count($_REQUEST['status'])){
			
			$where[] = " status in(".implode(",",$_REQUEST['status']).") ";
			
		}else{
			
		   return array();
		   
		}*/
		
		$condition = (isset($where) && count($where)>0)?implode(' and ',$where):null;
	   // $limitstart = $page*DtregisterModelExport::$limit;
		//echo $condition;
		$users = $this->UserModel->table->find($condition,'register_date');
		//$this->totalcount = $this->UserModel->table->getLastCount();
		//pr($this->totalcount);
		return $users;
	}
   	
	function load($id){
	   
	   parent::load($id);
	   
	   $this->events = str_replace("'[","[",$this->events);
	   $this->events = str_replace("]'","]",$this->events);
	   $this->events = str_replace('\"','"',$this->events);
	   
	   $this->general_export_fields = str_replace("'[","[",$this->general_export_fields);
	   $this->general_export_fields = str_replace("]'","]",$this->general_export_fields);
	   $this->general_export_fields = str_replace('\"','"',$this->general_export_fields);
	   
	   $this->group_export_fields = str_replace("'[","[",$this->group_export_fields);
	   $this->group_export_fields = str_replace("]'","]",$this->group_export_fields);
	   $this->group_export_fields = str_replace('\"','"',$this->group_export_fields);
	   
	   $this->individual_export_fields = str_replace("'[","[",$this->individual_export_fields);
	   $this->individual_export_fields = str_replace("]'","]",$this->individual_export_fields);
	   $this->individual_export_fields = str_replace('\"','"',$this->individual_export_fields);
	   $this->events = json_decode($this->events);
	   $this->general_export_fields = ($this->general_export_fields=='')?array():json_decode($this->general_export_fields);
	   $this->group_export_fields = ($this->group_export_fields=='')?array():json_decode($this->group_export_fields);
	   $this->individual_export_fields = ($this->individual_export_fields=='')?array():json_decode($this->individual_export_fields);
	}
	
	function saveFields($general=array(),$individual=array(),$group=array(),$group_reg=0){
	   	
		$sgeneral = json_encode($general);
		$sindividual = json_encode($individual);
		$sgroup = json_encode($group);
		$this->individual_export_fields = $sindividual;
		$this->general_export_fields = $sgeneral;
		$this->group_export_fields = $sgroup;
		$this->loadfirstRow();
		
		if($this->id){
		   	$this->save_field('general_export_fields' , $this->_db->Quote($sgeneral));
			echo $this->_db->getErrorMsg();
			$this->save_field('group_export_fields' , $this->_db->Quote($sgroup));
			echo $this->_db->getErrorMsg();
			$this->save_field('individual_export_fields' , $this->_db->Quote($sindividual));
			echo $this->_db->getErrorMsg();
			
			$this->save_field('group_reg' , $group_reg);
			echo $this->_db->getErrorMsg();
			
		}else{
		   //$this->save(array('events'=> $sevents));	
		}
		
		$this->individual_export_fields = $individual;
		$this->general_export_fields = $general;
		$this->group_export_fields = $group;
	
	}
	function saveEvents($events = array()){
	    $sevents = json_encode($events);
		$this->events = $sevents;
		$this->loadfirstRow();
		if($this->id){
		   	$this->save_field('events', $this->_db->Quote($sevents));
		}else{
		   $this->save(array('events'=> $sevents));	
		}
		
		$this->events = $events;
		
	}
	function loadfirstRow(){
	   
	   $data = $this->find('','',0,1);
	   
	   if($data){
		  $this->load($data[0]->id);   
	   }
	  
	}
	function mergeCustomFieldHeader(){
	  
	  global $csv_separator;
		
	  $group_export_fields = array();
	  $individual_export_fields = array();
	  if (count($this->individual_export_fields) > 0) {
	  		$individual_export_fields = array_combine($this->individual_export_fields,$this->individual_export_fields);
	  }
	  if (count($this->group_export_fields) > 0) {
	  		$group_export_fields = array_combine($this->group_export_fields,$this->group_export_fields);
	  }
	  $merge = array();
	
	   if (count($individual_export_fields) > 0) {
		   foreach($individual_export_fields as $key=>$id){
			   
			   $merge[] = $id;
			   $this->field_settings[$id][] = 'individual';
			   if(isset($group_export_fields[$key])){
				   unset($group_export_fields[$key]);
				   $this->field_settings[$id][] = 'group';
				   
			   }
				
		   }
	   }
	   
	   if (count($group_export_fields) > 0) {
		   foreach($group_export_fields as $field){
			   $this->field_settings[$field][] = 'group';
		   }
	   }
	
	   $merge = array_merge($merge,$group_export_fields);

	   $flds = array();
	   if(count($merge)) {
		 
	       $fields = $this->Tablefield->find( 'id in('.implode(",",$merge).')','ordering ');
		   
		   $temp = array();
		   
		   if (count($fields) > 0) {
			   foreach($fields as $field){
				   
				   $temp[$field->id] = $field->id;
				   $flds[$field->id] = $field;
				   
			   }
		   }
		   $merge = $temp;
	   }

	   $this->customHeaderFields = $merge;
	   $this->customFields = $flds;

	}
	function getUsers($datefrom="", $dateto="",$page=0){
	   	
		$where[] = " eventId in(".implode(",",$this->events).") ";
		$dateto_con = "";
        $datefrom_con = ""; // CAST('2000-01-01' AS DATE)
	    if($datefrom!=""){
	
		   $datefrom = strftime('%Y-%m-%d', strtotime($datefrom)) ." 00:00:00";
	       $where[] = " register_date >= '$datefrom' ";
	
		}
	    if($dateto!=""){
	
		   $dateto = strftime('%Y-%m-%d', strtotime($dateto))." 23:59:59";
	       $where[] = "  register_date  <= '$dateto' "; 
		
		}
		if(isset($_REQUEST['status']) && count($_REQUEST['status'])){
			
			$where[] = " status in(".implode(",",$_REQUEST['status']).") ";
			
		}else{
			
		   return array();
		   
		}
		
		$condition = implode(' and ',$where);
	    $limitstart = $page*DtregisterModelExport::$limit;
		
		$users = $this->UserModel->table->find($condition,'register_date',$limitstart,DtregisterModelExport::$limit);
		$this->totalcount = $this->UserModel->table->getLastCount();
		//pr($this->totalcount);
		return $users;
	}
	
	function getUsers_all(){
	   	
		$where[] = " eventId in(".implode(",",$this->events).") ";
		
		$condition = implode(' and ',$where);
	    		
		$users = $this->UserModel->table->find($condition,'register_date desc');
		//$this->totalcount = $this->UserModel->table->getLastCount();
		//pr($this->totalcount);
		return $users;
	}
	
	function getgeneralHeader(){
	  $generalfields = array();
	  if (count($this->general_export_fields) > 0) {
	  		$generalfields = array_combine($this->general_export_fields,$this->general_export_fields);
	  }
	  if (count($generalfields) > 0) {
		  foreach($generalfields as $field){
			  if($field == 'offline_payment_data') {
			        $this->field_settings['billing_firstname'][] = 'general';
					$this->field_settings['billing_lastname'][] = 'general';
					$this->field_settings['billing_address'][] = 'general';
					$this->field_settings['billing_city'][] = 'general';
					$this->field_settings['billing_state'][] = 'general';
					$this->field_settings['billing_phone'][] = 'general';
					$this->field_settings['billing_country'][] = 'general';
					$this->field_settings['billing_zipcode'][] = 'general';
					$this->field_settings['billing_x_card_num'][] = 'general';
					$this->field_settings['billing_x_exp_date'][] = 'general';
					$this->field_settings['billing_cardtype'][] = 'general';
			  } else {
			   		$this->field_settings[$field][] = 'general';
			  }
		  }
	  }
		
	}
	function makeheader(){
		
		global $csv_separator;
		
	    $header = array();
		$header['register_date'] = JText::_('DT_REGISTER_DATE');
		$header['eventname'] = JText::_('DT_EVENT_NAME');
		$offline_card_included = false;
		if (count($this->general_export_fields) > 0) {
			foreach($this->general_export_fields as $field){
				if($field == 'offline_payment_data') {
				  
					$offline_card_included = true;
				} else {
					$header[$field] = $this->generalFields[$field];
				}
				
			}
		}
		
		if (count($this->customHeaderFields) > 0) {
			foreach($this->customHeaderFields as $field){
				$header[$field] = $this->customFields[$field]->name;
			}
		}
		if($offline_card_included) {
			  $header['billing_firstname'] = JText::_( 'DT_CARD_HOLDER_FIRSTNAME' );
			  $header['billing_lastname'] = JText::_( 'DT_CARD_HOLDER_LASTNAME' );
			  $header['billing_address'] = JText::_( 'DT_BILLING_ADDRESS' );
			  $header['billing_city'] = JText::_( 'DT_BILLING_CITY' );
			  $header['billing_state'] = JText::_( 'DT_BILLING_STATE' );
			  $header['billing_phone'] = JText::_( 'DT_BILLING_PHONE' );
			  $header['billing_country'] = JText::_( 'DT_BILLING_COUNTRY' );
			  $header['billing_zipcode'] = JText::_( 'DT_BILLING_ZIPCODE' );
			  $header['billing_x_card_num'] = JText::_( 'DT_CARD_NUMBER' );
			  $header['billing_x_exp_date'] = JText::_( 'DT_CARD_EXPIRY_DATE' );
			  $header['billing_cardtype'] = JText::_( 'DT_CARD_TYPE' );
			  unset($this->general_export_fields[array_search('offline_payment_data',$this->general_export_fields)]);
			  $this->general_export_fields['billing_firstname'] = 'billing_firstname';
			  $this->general_export_fields['billing_lastname'] = 'billing_lastname';
			  $this->general_export_fields['billing_address'] = 'billing_address';
			  $this->general_export_fields['billing_city'] = 'billing_city';
			  $this->general_export_fields['billing_state'] = 'billing_state';
			  $this->general_export_fields['billing_phone'] = 'billing_phone';
			  $this->general_export_fields['billing_country'] = 'billing_country';
			  $this->general_export_fields['billing_zipcode'] = 'billing_zipcode';
			  $this->general_export_fields['billing_x_card_num'] = 'billing_x_card_num';
			  $this->general_export_fields['billing_x_exp_date'] = 'billing_x_exp_date';
			  $this->general_export_fields['billing_cardtype'] = 'billing_cardtype';
	  }
		$this->header = $header;
		
		if(!isset($_REQUEST['page'])||$_REQUEST['page']==0){
		   $this->csvoutput .= implode("$csv_separator",$header)."\n";
		}
	
	}

	function type($user){
	  	return $user->type;
	}
	function memtot($user){
	  	return $user->memtot;
	}
	
	function confirmNum($user){
	   	return $user->confirmNum;
	}
	
	function code($user){
	   return $user->TableDiscountcode->name;
	}
	function groupId($user){ // not required in MVC
	    return "";
	}
	function user_id($user){
	  return ($user->user_id)?$user->user_id:''; 
	}
	
	function userId($user){
	  return ($user->userId)?$user->userId:''; 
	}
	function category($user){
	  $user->TableEvent->category ;
	   $cats = array();
	  if(is_array($user->TableEvent->category)) {
	    
		 foreach($user->TableEvent->category as $cat_id) {
		   $user->TableEvent->TableCategory->load($cat_id);
		   $cats[] = $user->TableEvent->TableCategory->categoryName;
		 }
		 
	  }
	  return implode(" , ", $cats);
	  return $user->TableEvent->TableCategory->categoryName;
	}
	function location($user){
		//pr($user->TableEvent->location_id);
		//pr($user->TableEvent->TableLocation);
	  return $user->TableEvent->TableLocation->name;
	}
	function amount($user){
	    return $user->fee->fee;	
	}
	function payment_type($user){
		$methods = $this->pmethod->getMergeList();
		return isset($methods[$user->fee->payment_method])?$methods[$user->fee->payment_method]:'';	
	}
	
	function event_date($user){
		return $user->TableEvent->displaydatecolumn_no_html();
			}
	
	function event_time($user){
		return $user->TableEvent->displaytimecolumn(" ");
			}
	
	function paid($user){
	    
		return isset($this->feeModel->table->statustxt[$user->fee->status])?$this->feeModel->table->statustxt[$user->fee->status]:'';	
	}
	
	function paid_amount($user){
	    
		return DTreg::showprice($user->fee->paid_amount);	
	}
	
	function attend($user){   
	     return $user->attendtxt[$user->attend];
	}
	function tax_exemption($user) {
	   return ($user->tax_exemption)?JText::_('DT_YES'):JText::_('DT_NO');
	}
	function tax_exemption_code($user) {
	   return $user->tax_exemption_code;
	}
	function status($user){
	    return $user->statustxt[$user->status];	
	}
	
	function transaction_id($user){
	   	 return ($user->transaction_id)?$user->transaction_id:''; 
	}
	function billing_firstname ($user) {
		return ($user->card->firstname)?$user->card->firstname:'';
	}
	
	function billing_lastname ($user) {
		return ($user->card->lastname)?$user->card->lastname:'';
	}
	function billing_address ($user) {
		return ($user->card->address)?$user->card->address:'';
	}
	
	function billing_city ($user) {
		return ($user->card->city)?$user->card->city:'';
	}
	function billing_state ($user) {
		return ($user->card->state)?$user->card->state:'';
	}
	function billing_phone ($user) {
		return ($user->card->phone)?$user->card->phone:'';
	}
	function billing_country ($user) {
	   
	   $countylist = new TableField();
       $field = $countylist->fingbyName('country');
	   $dropDownDatas=explode("|",$field->values);
	   
		return ($user->card->country)?$dropDownDatas[$user->card->country]:'';
	}
	
	function billing_zipcode ($user) {
		return ($user->card->zipcode)?$user->card->zipcode:'';
	}
	function billing_x_card_num ($user) {
		return ($user->card->x_card_num)?substr(chunk_split($user->card->x_card_num,4,'-'),0,-1):'';
	}
	function billing_x_exp_date ($user) {
		return ($user->card->x_exp_date)?$user->card->x_exp_date:'';
	}
	function billing_cardtype ($user) {
		global $cardtype;
		$cardtypes = array_values($cardtype);
		//pr($cardtypes);
		//pr($user->card->cardtype);
		return (isset($user->card->cardtype))?$cardtypes[$user->card->cardtype]:'';
		
	}
	
	function getUserColumndata($user,$field){
		
	  	if(in_array($field,$this->general_export_fields)){
		    return $this->{$field}($user);
		}else{
			$class = "Field_".$this->fieldTypes[$this->customFields[$field]->type];

		    $fieldTable = new $class();
            
		    $fieldTable->load($field);
			$function = "viewHtml";
			if(method_exists($fieldTable,'exportView')){
			   	$function = "exportView";
			}
		    return $fieldTable->{$function}((array)$user);
		}
	}
	
	function getMemberColumndata($member,$field,$user){
	    
		if(in_array($field,$this->general_export_fields)){
			if($field == 'attend') {
					return  $user->attendtxt[$member->attend];
			} else  if($field == "confirmNum") {
				
				return  $member->confirmnum;
				
			} else {
				if($field == "memtot"){
					return " ";
			    }
				if($field == "code") {
				   return $this->{$field}($member);
				}
		    	return $this->{$field}($user);
				
			}
		}else{
		    $class = "Field_".$this->fieldTypes[$this->customFields[$field]->type];

		    $fieldTable = new $class();
            
		    $fieldTable->load($field);
			$function = "viewHtml";
			if(method_exists($fieldTable,'exportView')){
			   	$function = "exportView";
			}
		    return $fieldTable->{$function}((array)$member);
		}
			
	}
	
	function addCsvRow($data=array()){
		global $csv_separator;
		//pr($data);
		$this->csvoutput .= '"'.implode('"'.$csv_separator.'"',$data).'"'."\n";
	}
	
	function addUsersdata($users=array()){
		
		if (count($users) > 0) {
			foreach($users as $user){
				//pr($user);
				$tUser = new TableDuser();

				$tUser->load($user->userId);
				
				$data = array();
				//pr($this->header);
				if (count($this->header) > 0) {
					foreach($this->header as $field => $value){
						
						$data[$field] = "";
						if(isset($this->field_settings[$field]) && in_array('general',$this->field_settings[$field])){
						   $data[$field] = $this->getUserColumndata($tUser,$field);
						}elseif( isset($this->field_settings[$field]) && in_array('individual',$this->field_settings[$field])){
						   $data[$field] = $this->getUserColumndata($tUser,$field);
						}elseif($field == 'register_date'){
							 $data[$field] = $tUser->register_date;
						}elseif($field == 'eventname'){
							$data[$field] = $tUser->TableEvent->title;
						}else{
						   	$data[$field] = "";
						}
						
					}
					// prd($data);
				}
				if($tUser->type=='G') {
					if($this->group_reg == "0") {
						$this->addCsvRow($data);
					}
				} else {
					$this->addCsvRow($data);
				}
				if($tUser->type=='G'){
						$this->addmembers($tUser);
				}
				unset($tUser);
			}
		}
	}
    function addmembers($user){
	  	
		if (count($user->members) > 0) {
			echo "<pre>";
			print_r($this->header);
			foreach($user->members as $member){
				
				$user->TableMember->load($member->groupMemberId);
				$data = array();
				if (count($this->header) > 0) {
					foreach($this->header as $field => $value){
						$data[$field] = "";
						if(isset($this->field_settings[$field]) && in_array('general',$this->field_settings[$field])){
							 if($field == "attend") {
						   		$data[$field] = $this->getMemberColumndata($user->TableMember,$field,$user);
						
							 }elseif($field == "confirmNum") {
						   		$data[$field] = $this->getMemberColumndata($user->TableMember,$field,$user);	
						   } 
						   elseif($field == "code") {
						   		$data[$field] = $this->getMemberColumndata($user->TableMember,$field,$user);	
						   }
						   else {
						   		  if(in_array($field,array('paid_amount','amount','memtot'))){
									$data[$field] =  " ";
								} else {
									
						   			$data[$field] = $this->getUserColumndata($user,$field);
								}
						   }
						}elseif(isset($this->field_settings[$field]) && in_array('group',$this->field_settings[$field])){
						   $data[$field] = $this->getMemberColumndata($user->TableMember,$field,$user);
						}elseif($field == 'register_date'){
							 $data[$field] = $user->register_date;
						}elseif($field == 'eventname'){
							$data[$field] = $user->TableEvent->title;
						}else{
							 $data[$field] = "";
						}
					}
				}
				$this->addCsvRow($data);
				
			}
		}
		
	}
	function doexport($from=null,$to=null,$page=0){
		global $csv_separator;
		
		$this->csvoutput = "";
		$this->field_settings = array();
		$this->getgeneralHeader();
		$this->mergeCustomFieldHeader();
		//if($page == 0){
			$this->makeheader();	
		//}
		
		$users = $this->getUsers($from, $to,$page);
		$this->addUsersdata($users);
		
		$this->writeTofile($page);
		
	}
	
	function doexport_all(){
		global $csv_separator;
		
		$this->csvoutput = "";
		$this->field_settings = array();
		$this->getgeneralHeader();
		$this->mergeCustomFieldHeader();
		//if($page == 0){
			$this->makeheader();	
		//}
		
		$users = $this->getUsers_all();
		$this->addUsersdata($users);
		
		$this->writeTofile_all();
		
	}
	
	function writeTofile_all(){
		
		
        $tmpPath = $this->config->get('tmp_path');
		if(!isset($_REQUEST['file']) || $_REQUEST['file']=='' ){

			$this->filename = basename(tempnam($tmpPath ,null));
			
		}else{
			$this->filename = stripslashes($_REQUEST['file']);
		}
		file_put_contents($tmpPath."/".$this->filename, trim($this->csvoutput)."\n",FILE_APPEND);
		
		return;
	}
	
	function writeTofile($page){
		
		$confObject = JFactory::getApplication();
        $tmpPath = $confObject->getCfg('tmp_path');
		if(!isset($_REQUEST['file']) || $_REQUEST['file']=='' ){

			$this->filename = basename(tempnam($tmpPath ,null));
			
		}else{
			$this->filename = stripslashes($_REQUEST['file']);
		}
		file_put_contents($tmpPath."/".$this->filename, trim($this->csvoutput)."\n",FILE_APPEND);
		ob_clean();
		
		echo json_encode(array('total'=>$this->totalcount,
							   'file'=>$this->filename,
							   'limit'=> DtregisterModelExport::$limit,
							   'page'=>$page,
							   'csv'=>@file_get_contents($this->filename),
							   'current'=>$this->csvoutput)
						 );
		die;
		prd($this->filename);
	}
	
	function output(){
		ob_clean();
	   if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $_SERVER['HTTP_USER_AGENT'])) {

			$UserBrowser = "Opera";

		}

		elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT'])) {

			$UserBrowser = "IE";

		} else {

			$UserBrowser = '';	
		}
		$mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';

		$filename = "BackupList_Registrations";
		
		header('Content-Type: ' . $mime_type);

		header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');

			if ($UserBrowser == 'IE') {

			    header('Content-Disposition: attachment; filename="' . $filename . '.csv"');

			 	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

			 	header('Pragma: public');

			}

			else {

				header('Content-Disposition: attachment; filename="' . $filename . '.csv"');

				header('Pragma: no-cache');

			}
           $confObject = JFactory::getApplication();
           $tmpPath = $confObject->getCfg('tmp_path');
           echo @file_get_contents($tmpPath."/".$this->filename);

			//echo $this->csvoutput;

		   exit();	
	}
}

?>