<?php

/**
* @version 2.7.19
* @package Joomla 1.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
*/
global $members_tmp;
class DT_Fee{

	var $basefee;

	var $memberdiscount;

	var $latefee;

	var $birddiscount;

	var $discountcodefee;

	var $customfee = 0;

	var $tax;

	var $currentfee;

	var $fee;

	var $paid_fee;

	var $payment_method;

	var $changefee;

	var $cancelfee;
    
	var $fieldfee = array();
    
	function getObjectdata() {
		
		$data = new stdClass;
		$data->basefee = $this->basefee;
		$data->memberdiscount = $this->memberdiscount;
		$data->latefee = $this->latefee;
		$data->birddiscount = $this->birddiscount;
		$data->discountcodefee = $this->discountcodefee;
		$data->customfee = $this->customfee;
		$data->tax = $this->tax;
		$data->currentfee = $this->currentfee;
		$data->fee = $this->fee;
		$data->paid_fee = $this->paid_fee;
		$data->payment_method = $this->payment_method;
		$data->changefee = $this->changefee;
		$data->cancelfee = $this->cancelfee;
		if(isset($this->paid_amount)) {
			$data->paid_amount = $this->paid_amount;
		}
		if(!isset($this->fieldfee2)) {
		
			$this->fieldfee2 = array();
		}
		$data->fieldfee = $this->fieldfee2;
		
		return $data;
		
	}
	
	function __construct($event=null,$user=null){
		global $members_tmp;
	   	$this->TableEvent = $event;
        $this->is_changed = false;

		$this->TableUser = $user;
		$this->TableUser->process = DT_Session::get('Setting.process');
		if(isset($this->TableUser->members)) {
			//$this->TableUser->members = array_values($this->TableUser->members);
		}
		//$members_tmp = $this->TableUser->members;
		
		if($user->userId){
		    $this->OldUser = new TableDuser();
			$this->OldUser->load($user->userId);
		    $this->is_changed = !$this->OldUser->compare($this->TableUser);
			$this->OldUserdata = $this->OldUser->getObjData();
			
		}else{
			$this->OldUser = false;
		}
        $fieldtype = DtrModel::getInstance('Fieldtype','DtregisterModel');
		$this->members_fee = array();
		$this->fieldtypes = $fieldtype->getTypes();
		
		//$this->TableUser->members = $members_tmp;
        
    }

	function setPaidAmount($amount){

	  	$this->paid_amount = $amount;

	}

	function setPaidMethod($method){

	  	$this->payment_method = $method;

	}

	function setPaidStatus($status){

	  $this->status = $status;	

	}

	function getFee($ismember=false,$date=null){

	   	global $now;

		if($date != null and is_string($date)){

		   $date = new JDate($date);

		}
        
		if(isset($this->TableUser->userId) && $this->TableUser->userId > 0 && isset($this->TableUser->process) && $this->TableUser->process =='duepayment'){
		  	
			foreach($this->TableUser->fee as $feepart =>$partvalue){
			   if(!in_array($feepart , array('id','user_id'))){
				  
				  $this->$feepart = $partvalue;
				    
			   }		
			}
			  	
		}
		
		if(isset($this->TableUser->process)&& ($this->TableUser->process=='due' || $this->TableUser->process=='duepayment')){

			return $this->currentfee;

		}

		$date = ($date == null)?$now:$date;

		$this->date = $date;

		$this->ismember = $ismember;

		$this->basefee = $this->getBasefee($this->TableUser->memtot);
//pr($this->basefee);
		$this->processFee();
//pr($this->currentfee);
		$this->fee = $this->currentfee;
//pr($this->customfee);
		$this->paid_fee = $this->fee;
       
		return $this->currentfee;

	}

	function getChangefee(){

	   global $changefee_enable,$changefee_type,$changefee;
	   
	   if(!isset($this->TableUser->process) || $this->TableUser->process != 'change'){
		    $amount = 0;
            
		    $this->changefee = $amount;

	        return $amount;
	   }

       
	   if(isset($this->TableUser->userId) && $this->TableUser->userId != "" && $this->TableUser->status != -1 ){
	    
		 if($this->TableEvent->edit_fee && $this->TableEvent->changefee_enable && $this->is_changed){

			$type = ($this->TableEvent->changefee_type==1)?'amount':'percentage';

	   	    $amount = $this->calculatebytype($type,$this->TableEvent->changefee , $this->currentfee );

		 }else{

		   	 $amount = 0;

		 }

	   }else{

		   	$amount = 0;

	   }

	   $this->changefee = $amount;
//pr(" change fee ".$this->changefee) ;
	   return $amount;

	}

	function getCancelfee(){

	   global $cancelfee_enable,$cancelfee_type,$cancelfee;
	   
	    if(!isset($this->TableUser->process) || $this->TableUser->process != 'cancel'){
		    $amount = 0;
           
		    $this->cancelfee = $amount;

	        return $amount;
	   }
	   
	   if(isset($this->TableUser->userId) && $this->TableUser->userId != "" && $this->TableUser->status != -1 ){

		 if($this->TableEvent->cancel_enable && $this->TableEvent->cancelfee_enable){

			$type = ($this->TableEvent->cancelfee_type==1)?'amount':'percentage';

	   	    $amount = $this->calculatebytype($type,$this->TableEvent->cancelfee, $this->currentfee );

		 }else{
             
		   	 $amount = 0;

		 }

	   }else{

		   	$amount = 0;

	   }

	   $this->cancelfee = $amount;

	   return $amount;

	}

	function processFee(){

	   $this->currentfee = $this->basefee;
	  // pr(" base fee ".$this->basefee);
	   if(isset($this->customfee) && $this->customfee >0 && isset($this->TableUser->process) && $this->TableUser->process == "duepayment"){
	   		$this->currentfee += $this->customfee;
	   }else{
	   	  $this->customfee = 0;	
	   }
	   //pr($this->TableEvent->feeorder);
	   foreach($this->TableEvent->feeorder  as $feeorder){
		   if($feeorder->type != 'field'){
		   		//pr($feeorder->type);
		   		//pr($this->currentfee);
		   }
           
		   if($feeorder->type == "basefee"){

			    continue;

		   }

		   if($feeorder->type == "birddiscount"){

			   $amount = $this->getBirdDiscount();

			   $this->currentfee -= $amount; 

		   }

		   if($feeorder->type == "changefee"){

			  $amount = $this->getChangefee(); 
              
			  $this->currentfee += $amount; 
		   }

		    if($feeorder->type == "cancelfee"){

			  $amount = $this->getCancelfee();

			  $this->currentfee += $amount; 

		   }

		   if($feeorder->type == "discountcode" && $this->TableUser->discount_code_id == $feeorder->reference_id){

		       $amount = $this->getDiscountcodeamount();

			   $this->currentfee -= $amount; 

		   }elseif($feeorder->type == "discountcode"){

			    continue;

		   }

		   if($feeorder->type == "field"){
               
			 
			  $fee = $this->getFieldFee($feeorder->reference_id);
			   if($feeorder->reference_id == 13 || $feeorder->reference_id == 17)  // || $feeorder->reference_id == 13
			  {
				  $fee;
			  }
			 // pr($this->TableUser->process);
			  if(!isset($this->TableUser->process) || $this->TableUser->process != "duepayment"){
				// if($feeorder->reference_id == 13 || $feeorder->reference_id == 57)
			  	 // pr($feeorder->reference_id." ==> ".$fee);
				 //pr("field fee custom ".$feeorder->reference_id." ".$fee." ".$this->currentfee);
				//pr('enter');
				 $this->currentfee += $fee;
				// if($feeorder->reference_id == 13 || $feeorder->reference_id == 57)
     			 // pr($this->currentfee); 
			  	 $this->customfee += $fee;
				 			 
			  }

		   }

		   if($feeorder->type == "memberdiscount"){

			  $this->memberdiscount = $this->getMemberDiscount();

			  $this->currentfee -= $this->memberdiscount;

		   }

		   if($feeorder->type =='latefee'){

		       $this->latefee = $this->getLatefee();

			   $this->currentfee += $this->latefee;
			   
			   // pr(" late fee ".$this->latefee);

		   }

		   if($feeorder->type =='tax'){

			   $this->tax = $this->getTax();

			   $this->currentfee += $this->tax;

		   }

	   }
	   
	  // pr("total field fee ".$this->customfee);
	  // pr($this->fieldfee2);
	  //pr($this->currentfee);
	   //pr($this->members_fee);

	}

	function getTax(){
      
	  if($this->TableEvent->tax_enable){

	     $tax_amount = $this->currentfee * $this->TableEvent->tax_amount/100;

	   }else{

	      $tax_amount = 0;

	   }

	   return $tax_amount;

	}

	function getMemberDiscount(){
        global $member_discount_group_reg;
		$event = $this->TableEvent;
        if(!$this->ismember){

		   	return 0;

		}
        if(isset($this->TableUser->userId) && $this->TableUser->userId > 0){
			$this->TableUser->fee = (array) $this->TableUser->fee;
			return $this->TableUser->fee['memberdiscount'];
		   	
		}
		$type = ($event->discount_type==1)?'amount':'percentage';

	   	$discount = $this->calculatebytype($type,$event->discount_amount , $this->currentfee );

		if($type=='amount'){

		  if($this->TableUser->type == 'G'){

			  $totmemforDiscount = 0;
              $totmemforDiscount = $this->TableUser->memtot;
			  $totmemforDiscount = 1;
			  if($member_discount_group_reg == "eachmember" && $type != "percentage") {
				$discount *= $this->TableUser->memtot;
		      }
			  
		  }else{

			  $totmemforDiscount = 1;

		  }

		  $discount = $discount * $totmemforDiscount;

		}
        if($member_discount_group_reg == "eachmember" && $type != "percentage") {
				//$discount *= $this->TableUser->memtot;
		}
		if($this->currentfee < $discount){

		    $discount = $this->currentfee;

		}
        for($i=0; $i< $this->TableUser->memtot; $i++) {
			$this->members_fee[$i]['member_discount'] = $discount/$this->TableUser->memtot;
		}
		return $discount;

	}

	function getFieldFee($field_id){
         
		 // pr($field_id);
		 // prd($this->TableUser->fields);
		 // pr($this->TableUser->fields[$field_id]);
		 if(isset($this->fieldfee[$field_id])){
			 
			return;	 
		 }
		$field = $this->TableEvent->TableField;

        $field->load($field_id);

		$newcontext = "Field_".$this->fieldtypes[$field->type];

	    $obj = new $newcontext();

		$obj->bind((array)$field);

		$field = $obj;

		$fee = 0;
		$i = 0;
		$fee_pass = $this->currentfee;
		$type = ($field->fee_type==1)?'amount':'percentage';
		$member_having_field  = 0;
		if($this->TableUser->type == 'G'){
//prd($this->TableUser->members);
           if(isset($this->TableUser->members) && is_array($this->TableUser->members))		        
		   foreach($this->TableUser->members as $member){
               $field_fee = 0;
			  if(isset($member->fields[$field_id])){
				  
				 if(is_array($member->fields[$field_id])){
					
				    foreach($member->fields[$field_id] as $feekey){
                       $field_fee += $field->getfeeByKey($feekey);
					   $fee += $field->getfeeByKey($feekey);

				    }

				 }else{
					 $field_fee = $field->getfeeByKey($member->fields[$field_id]);
					 $fee += $field->getfeeByKey($member->fields[$field_id]);

				 }
				
                // pr($member);
				 //pr($field_fee);
			  }
			  
			 // if(isset($this->TableUser->members[$i]->fields[$field_id])) {
			 if(isset($member->fields[$field_id])) {
				    
				  	$mfee_pass = $this->add_member_fee($i,$field_id);
					//if($i == 1)
					//pr($mfee_pass);
					$mfee = $this->calculatebytype($type,$field_fee , $mfee_pass );
					//if($i == 1)
					//pr($mfee);
					$this->members_fee[$i]['field_fee'][$field_id]['fee'] = $mfee;
				} 
			  //pr($field_id);

			 // pr($fee);
			  //$this->members_fee[$i]['field_fee'][$field_id]['fee'] = $fee;
			 // $this->members_fee[$i]['field_fee'][$field_id]['type'] = $type;
			  $i++;
		   }   
		  // pr($this->members_fee);
		   if(DT_Session::get('Setting.Member.Index')) {
				$member_index = DT_Session::get('Setting.Member.Index');
				
			} else {
				$member_index = count(DT_Session::get('Setting.User.members'));
			}
		  // $fee_pass = $this->currentfee/count($this->TableUser->members_fee[$member_index]);
		  //pr($this->members_fee);
		 // if($field_id == 17)
		// pr(DT_Session::get("Setting")) ;
		 // pr("member ".$member_index);
		  $fee_pass = $this->add_member_fee($member_index,$field_id);
		 // if($field_id == 17)
		 // pr($fee_pass);
            // $fee = $fee/count($this->TableUser->members);
		}
		$user_fee = 0;
		if(isset($this->TableUser->fields[$field_id])){
           $user_fee = 0;
		   if(is_array($this->TableUser->fields[$field_id])){

			  foreach($this->TableUser->fields[$field_id] as $feekey){
				 $user_fee += $field->fees[$feekey];
				 $fee += $field->fees[$feekey];

			  }

		   }else{

			   $fee += $field->getfeeByKey($this->TableUser->fields[$field_id]);
			   $user_fee += $field->getfeeByKey($this->TableUser->fields[$field_id]);

		   }
		   $user_fee = $this->calculatebytype($type,$fee , $this->currentfee );
		}
		
		$actual_fee = $fee;
        
        $fee = $this->calculatebytype($type,$fee , $fee_pass );
	    
		//prd($this->members_fee);
        $childs = $obj->getchild();
		$child_fee  = 0;
		$this->fieldfee[$field->id] = array('field'=>(object)(array)$field,'fee'=>$fee);
		
		foreach($childs as $child){
			if($field->id == "13") {
			
		     //pr($child->id);
		}
			if(!$child->fee_field){
				continue;
			}
			
			$child_fee += $this->getFieldFee($child->id);
				
		}
		
		$mem_fee = 0;
		if($this->TableUser->type == 'G' && isset($this->TableUser->members) && is_array($this->TableUser->members)) {
			$mem_fee = 0;
			
			for($i=0;$i < $this->TableUser->memtot;$i++){
				
				$temp_fee = $this->add_member_field_fee($i,$field_id);
				//if($field_id == 17 || $field_id == 13)
				//  pr("added fee $i".$temp_fee." ".$field_id);
				  if(isset($this->members_fee[$i][$field_id])){
				  		$mem_fee += $temp_fee + $child_fee;
				  } else {
				  		$mem_fee += $temp_fee;
				  }
				
			}
			
			//if($field_id == 17 || $field_id == 13)
			//pr($mem_fee." ".$field_id);
		}
	//	pr($this->members_fee);
		//$type = ($field->fee_type==1)?'amount':'percentage';

        //$fee = $this->calculatebytype($type,$fee , $this->currentfee );
		// $fee = $user_fee + $memfee;
		
		//pr($user_fee);
		//pr($mem_fee);
		//pr($child_fee);
		if($field->id == "13") {
			
		//	die;
		}
		$fee = $user_fee + $mem_fee  + $child_fee;
		$this->fieldfee2[$field->id] = array('fee'=>($fee - $child_fee) );
		$this->fieldfee[$field->id]['fee'] = $fee - $child_fee;
		/*if($field->id == 13) {
			//pr($field_id."  ==>  ".$fee);
			pr($field->id." user fee ".$user_fee);
			pr($field->id." mem fee ".$mem_fee);
			pr($field->id." child fee ".$child_fee);
			pr($this->members_fee);
			
			//die;
		
		}*/
		
		return $fee;

	}
	
	function add_member_fee($index,$field_id) {
		
		$total = 0;
		//pr($this->members_fee);
		if(isset($this->members_fee[$index]))
		foreach($this->members_fee[$index] as $key => $fee_parts) {
			//pr($fee_parts);
			//foreach($fee_parts as $fee) {
				if($key == $field_id) {
					break;
				}
				if(is_array($fee_parts)) {
					
					foreach($fee_parts as $field_key => $total_part) {
						if($field_key == $field_id) {
							
							break;
							
						}
						$total += $total_part['fee'];
					}
					
				} else {
					if($key == 'member_discount' || $key == 'birddiscount' || $key =='discountcodefee') {
					   $total -= $fee_parts;
					} else {
					  $total += $fee_parts;
					}
					
				}
				
			//}
			
		}
		//pr($total);
		return $total;
		
	}

    function add_member_field_fee($index,$field_id) {
			$total = 0;
		//pr($this->members_fee);
		foreach($this->members_fee[$index] as $key => $fee_parts) {
			//pr($fee_parts);
			//foreach($fee_parts as $fee) {
				
				if(is_array($fee_parts)) {
					
					foreach($fee_parts as $field_key => $total_part) {
						if($field_key == $field_id) {
							$total += $total_part['fee'];
						}
						
					}
					
				} 
			//}
			
		}
		//pr($total);
		return $total;
	}

	function getDiscountcodeamount(){
        global $discount_code_group_reg;
	    if(isset($this->TableUser->userId) && $this->TableUser->userId > 0){
			$this->TableUser->fee = (array) $this->TableUser->fee;
			return $this->TableUser->fee['discountcodefee'];
		   	
		}
		if($this->TableUser->discount_code_id){
            $this->TableEvent->TableEventdiscountcode->TableDiscountcode->load($this->TableUser->discount_code_id);
			$type = ($this->TableEvent->TableEventdiscountcode->TableDiscountcode->discount_type==1)?'amount':'percentage';

			$this->discountcodefee = $this->calculatebytype($type,$this->TableEvent->TableEventdiscountcode->TableDiscountcode->amount , $this->currentfee );
            
			if($discount_code_group_reg == "eachmember" && $type != "percentage") {
				$this->discountcodefee *= $this->TableUser->memtot;
			}
			
			if($this->currentfee < $this->discountcodefee){

			   	$this->discountcodefee = $this->currentfee;

			}
            
			return $this->discountcodefee;

		}else{

			return 0;

		}

	}

	function getLatefee(){

		global $now,$late_fee_group_reg;
         if(isset($this->TableUser->userId) && $this->TableUser->userId > 0 && $this->TableUser->memtot == $this->OldUser->memtot){
			 $this->TableUser->fee = (array) $this->TableUser->fee;
			 $latefee = $this->TableUser->fee['latefee'];
			 for($i=0; $i<$this->TableUser->memtot; $i++) {
				$this->members_fee[$i]['latefee'] = $latefee/$this->TableUser->memtot;
			 }
			 return $this->TableUser->fee['latefee'];
		   	
		}
		
		if(strtotime($this->date->toFormat()) > strtotime(trim($this->TableEvent->latefeedate." ".$this->TableEvent->latefeetime))){

			  if($this->TableUser->type == 'G'){

			   if($this->TableEvent->group_registration_type !="detail"){
				   
				  $totmemforDiscount = $this->TableUser->memtot;
				   
				  $totmemforDiscount = 1;
				  if($late_fee_group_reg == "eachmember" ) { // && $type != "percentage"
					$totmemforDiscount = $this->TableUser->memtot;
				  }
				   
			   }else{

			      $totmemforDiscount = 0;
				  $totmemforDiscount = $this->TableUser->memtot;
				  $totmemforDiscount = 1;
				  if($late_fee_group_reg == "eachmember"  ) { // && $type != "percentage"
					$totmemforDiscount = $this->TableUser->memtot;
				  }

			   }

		  }else{

			  $totmemforDiscount = 1;

		  }
            if($this->OldUser !== false){
				
			}
			$latefee = $this->TableEvent->latefee*$totmemforDiscount;
			//pr($this->TableUser->memtot);
            for($i=0; $i<$this->TableUser->memtot; $i++) {
				$this->members_fee[$i]['latefee'] = $latefee/$this->TableUser->memtot;
			}
			return $latefee;

		}else{

		   return 0;

		}

	}

	function getBirdDiscount(){

		global $now,$bird_discount_group_reg;
		if(isset($this->TableUser->userId) && $this->TableUser->userId > 0 && $this->TableUser->memtot == $this->OldUser->memtot){
			$this->TableUser->fee = (array) $this->TableUser->fee;
			//pr($this->TableUser->fee['birddiscount']);
			 $latefee = $this->TableUser->fee['latefee'];
			 $this->birddiscount = $this->TableUser->fee['birddiscount'];
			 for($i=0; $i<$this->TableUser->memtot; $i++) {
				$this->members_fee[$i]['birddiscount'] = $this->birddiscount/$this->TableUser->memtot;
			 }
			return $this->TableUser->fee['birddiscount'];
		   	
		}
		if(strtotime($this->date->toFormat()) < strtotime(trim($this->TableEvent->bird_discount_date." ".$this->TableEvent->bird_discount_time)) 

		&& $this->TableEvent->bird_discount_type != 0 ){
     
		    $type = ($this->TableEvent->bird_discount_type==1)?'amount':'percentage';

			if(!isset($this->slab)){

			   $this->slab = $this->getSlab($this->TableUser->memtot);

			}

			if($this->slab->type != 'flat' && $type=="amount" && $this->TableUser->type='G' ){
			  
                if($this->TableEvent->group_registration_type !="detail"){
				   
				   $totmemforDiscount = $this->TableUser->memtot;
				   
			   }else{
				  $totmemforDiscount = 0;
				  $totmemforDiscount = $this->TableUser->memtot;

			  }

			  if(isset($this->TableUser->userId) && $this->TableUser->userId != ""){

			     $this->birddiscount = $this->TableUser->TableFee->birddiscount;

			  }else{

			     $this->birddiscount = $this->calculatebytype($type,$this->TableEvent->bird_discount_amount , $this->currentfee );
                  //$this->birddiscount = $this->birddiscount*$this->TableUser->memtot;
			  }

			}else{

			    $this->birddiscount = $this->calculatebytype($type,$this->TableEvent->bird_discount_amount , $this->currentfee );

			 }
             if($bird_discount_group_reg == "eachmember" && $type != "percentage") {
			      $this->birddiscount *= $this->TableUser->memtot;
			 }

			if($this->currentfee < $this->birddiscount){

			   	$this->birddiscount = $this->currentfee;

			}
            for($i=0; $i<$this->TableUser->memtot; $i++) {
				$this->members_fee[$i]['birddiscount'] = $this->birddiscount/$this->TableUser->memtot;
			}
			return $this->birddiscount;

		}else{

		   return 0;

		}

	}

	function calculatebytype($type='amount',$factor,$amount){

	    if($type == 'percentage'){

		   $per = $factor/100;

		   $amount= $amount*$per;

		}elseif($type == 'amount'){

		   $amount = $factor;   

		}

		return $amount;

    }

	function getBasefee($memtot=1){
		
	   $return= '';
	   $this->slab = $this->getSlab($memtot);
		
	   if ($this->slab) {
		   $type = $this->slab->type;
		   $amount = $this->slab->amount;
	
		   if($type == "flat"){
	
			  $return = $amount;
	
		   } else {
	
			  $return = $amount * $memtot;
	
		   }
	   }
       
	     for($i=0; $i<$memtot; $i++) {
				$this->members_fee[$i]['basefee'] = $return/$memtot;
			}
	   
		// echo '<pre>'; print_r($return); exit;	   

		return $return;

	}

	function getSlab($memtot=1){
        
	   	return $this->TableEvent->getSlab($memtot);

	}

	function cancel_fee($amount=0){

		 global $cancelfee_type,$cancelfee_enable,$cancelfee;

		 if($amount == 0){

		   //return 0;

		 }

		if($cancelfee_enable){

		    $type = ($cancelfee_type==1)?'amount':'percentage';

		    $cancelfee = self::calculatebytype($type,$cancelfee,$amount);

			return $cancelfee;

		 }else{

		   return 0;

		 }

     }

	 function change_fee($amount=0){

	   global $changefee_enable,$changefee_type,$changefee;

	   if($changefee_enable){

		 $type = ($changefee_type==1)?'amount':'percentage';

		 $changefee = self::calculatebytype($type,$changefee,$amount);

		 return $changefee;

	   }else{

		  return 0;   

	   }	 

	 }

}

?>