<?php
/**
	* 
	* Start 
	* Create Date: 17 Jun, 2016
	* This module file using for commmonly used method in all controller.
	* Created saravana kumar.
	* @see no link
	* Last Updated: 23 Jun, 2016
	* End
	* 
*/
namespace App\Models;
use CodeIgniter\Model;

Class Commissions extends Model {
public function __construct(){
		//$this->db = \Config\Database::connect();
	}
	// Direct commissions check
	public function index($userid,$amount,$description){

		$db      = \Config\Database::connect();
		$uusers_matrix = $db->table('uusers_matrix');
		$uusers_matrix =  $uusers_matrix->where('uusersid',$userid)->get()->getRow();
		
		$referral_id = $uusers_matrix->referral_id;
		$user_rank = $uusers_matrix->rankid;


		$uusers = $db->table('uusers')->where('uusersid',$userid)->get()->getRow();
		$usermail = $uusers->email;

		$referral_matrix = $db->table('uusers_matrix');
		$referral_matrix =  $referral_matrix->where('uusersid',$referral_id)->get()->getRow();
		$referral_id = $referral_matrix->uusersid;

		$referral_rank = $referral_matrix->rankid;


		if(empty($referral_rank))
			$referral_rank = '4';

		$rewardsettings = $db->table('rewardsettings');
		$rewardsettings =  $rewardsettings->where('id',$referral_rank)->get()->getRow();
		
		// Direct commission check

		$commission = $amount * $rewardsettings->direct_push_award / 100;
		if($commission > 0)
		{
		//$this->directcommission($referral_id,$commission,$description,$usermail);
		}

	   //reward_activation check
		$reward_activation_check = explode(',', $rewardsettings->reward_activation);
        
        //remove direct activation
        //$reward_level = array_shift($reward_activation_check);
        
        //check array count
        $reward_count = count($reward_activation_check);

        //check activation type
        $activation_type = $rewardsettings->activation_type;

        echo"<pre>";
        print_r($reward_activation_check);
        echo"</pre>";


        if($reward_count>0)
        {
            $this->session = session();
            $this->session->set('usermail',$usermail);
            $this->session->set('total_comm',0);
            $this->session->set('missing_comm','0');
            $this->session->set('same_rank4',0);
            echo"<pre>";
            print_r("first referral_id");
            print_r($referral_id);
            echo"</pre>";
            $this->reward_activation_commision($referral_id,$description,'0',$usermail,$activation_type,$reward_activation_check,$amount,$referral_rank,$user_rank);
        }
        $this->session->remove('usermail');
        $this->session->remove('total_comm');
        $this->session->remove('missing_comm');
        for($i=0; $i<=11; $i++){
        	$this->session->remove('same_rank'.$i);
        }    
	}

        
   public function reward_activation_commision($referral_id,$description,$i,$usermail,$activation_type,$reward_activation_check,$amount,$referral_rank,$user_rank)
		{

		$admin_share = 10;
        $db  = \Config\Database::connect();
        $this->session = session();


		$i=$i;
		echo"<pre>";
		print_r($i);
		print_r(" next \n");
		echo"</pre>";
		if($i == 0)
		$getlevel = $reward_activation_check[$i];
	    else
		$getlevel = $reward_activation_check[1];


		if($activation_type==1)
		{
		$commission = $getlevel;
		}
		else
		{
		$commission = ($amount / 100) * $getlevel;
		}

		echo"<pre>";
	    print_r("commission");
		print_r($commission);
		echo"</pre>";

		$ids = $referral_id;

		$user_upline=$referral_id;

        echo"<pre>";
        print_r("referral id");
        print_r($ids);
        echo"</pre>";

		if($user_upline)
		{
		
		if($commission!="")
		{
       if($i==0)
       {
          $commission_cal = $commission;
	    $direct_data = array(
			'uusersid' => $referral_id,
			'type' => 'commissions',
			'description' => 'Direct commission'.$description,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $this->session->get('usermail')
		);
		
       }
       else
       {
   
       if($referral_rank==$user_rank && $this->session->get('same_rank'.$referral_rank) == 0)
       {

          $reward_get = $db->table('rewardsettings');
		  $reward_get =  $reward_get->where('id',$user_rank)->get()->getRow();

		  $get_same_activation =  $reward_get->PWR_reward;

		  $commission_cal1 = $get_same_activation;

		if($get_same_activation>0.00000)
		{

			$direct_data = array(
				'uusersid' => $referral_id,
				'type' => 'commissions',
				'description' => $reward_get->rank_name.' Same Rank activation commissions',
				'date' => date('Y-m-d H:i:s'),
				'amount' => $get_same_activation, 
				'from_email' => $this->session->get('usermail')
			);

			// $history = $db->table('history');
   //          $confirm = $db->table('history')->where('uusersid',$referral_id)->where('type','activation')->where('status',1)->get()->getRow();
	  //   if($confirm)
   //          $history_status=$history->insert($direct_data);

		}
           $this->session->set('same_rank'.$referral_rank,1);
        }
        else 
        {


          $reward_get = $db->table('rewardsettings');
		  $reward_get =  $reward_get->where('id',$referral_rank)->get()->getRow();
		  $getreward_level = $reward_get->reward_activation; 
		  $get_user_level = explode(',', $getreward_level)[1];
		  $get_original_comm = explode(',', $getreward_level)[0];


		
		// if($get_user_level[$i])
		// {
			if($activation_type==1)
			{
			   $commission = $get_user_level;
			}
			else
			{
			   $commission = ($amount / 100) * $get_user_level;
			}
            $last_rank = $db->table('rewardsettings')->orderBy('id','DESC')->get()->getRow();
			if($i > 0){
             $history = $db->table('history');
            $current_commission_amount1 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Direct commission for activation')->get()->getRow();
   
             $current_commission_amount2 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Reward Activation')->get()->getRow();
    



      
            
            $current_commission_amount = floatval($current_commission_amount1->amount)  + floatval($current_commission_amount2->amount);
      
            $total_count_comm = floatval($current_commission_amount) + floatval($commission) + floatval($this->session->get('missing_comm'));



            if($total_count_comm != $get_original_comm){
        
            	$pending_comm = floatval($get_original_comm) - floatval(($current_commission_amount + $this->session->get('missing_comm')));
            	$commission = $pending_comm;
      
            }


			}

           





         if($referral_rank > $user_rank){ 
			$commission_cal = $commission;
			$direct_data = array(
			'uusersid' => $referral_id,
			'type' => 'commissions',
			'description' => 'Reward Activation '.$reward_get->rank_name." Level commissions",
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $this->session->get('usermail')
			);
		}
        }
       }
        
		
		$history = $db->table('history');
		if($referral_rank >= $user_rank && !empty($direct_data)){

	    $confirm = $db->table('history')->where('uusersid',$referral_id)->where('type','activation')->where('status',1)->get()->getRow();

	    if($confirm) {

	    	echo"<pre>";
	        print_r("original comm : ");
	    	print_r($get_original_comm);
	    	echo "<br>";
	    	print_r("current commissions : ");
	    	print_r($current_commission_amount);
	    	echo "<br>";
	    	print_r("missing comm : ");
	    	print_r($this->session->get('missing_comm'));
	    	print_r($direct_data);
	    	echo"</pre>";
		$history_status=$history->insert($direct_data);
		$total_comm = $this->session->get('total_comm') + $commission_cal;
		$this->session->set('total_comm',$total_comm);

	    }else{

	    $missing_comm = $this->session->get('missing_comm') + $commission_cal;
		$this->session->set('missing_comm',$missing_comm);

	    }
		}

		

		}

		}

	    $uusers_matrix = $db->table('uusers_matrix');
		$uusers_matrix =  $uusers_matrix->where('uusersid',$referral_id)->get()->getRow();
		$referral_id1 = $uusers_matrix->referral_id;
		if($referral_rank < $user_rank){
			$user_ranks = $user_rank;
		}else{
		$user_ranks = $uusers_matrix->rankid;
		}

		$uusers = $db->table('uusers')->where('uusersid',$referral_id)->get()->getRow();
		$usermail = $uusers->email;

		$uusers1 = $db->table('uusers_matrix')->where('uusersid',$referral_id1)->get()->getRow();
		$referral_rank = $uusers1->rankid;

		$rewardsettings = $db->table('rewardsettings');
		$rewardsettings =  $rewardsettings->where('id',$referral_rank)->get()->getRow();

		$reward_activation_check = explode(',', $rewardsettings->reward_activation);

		if($referral_rank > $user_ranks){
			$this->session->set('same_rank'.$referral_rank,0);
		}


		if($referral_rank=="")
		{
			$referral_ranks = 4;
		}
		else
		{
			$referral_ranks = $referral_rank;
		}

		if($user_ranks=="")
		{
			$user_rankss = 4;
		}
		else
		{
			$user_rankss = $user_ranks;
		}


		if($referral_id1!="")
		{
		$i++;
		echo"<pre>";
		print_r($i);
		echo"</pre>";
		$this->reward_activation_commision($referral_id1,$description,$i,$usermail,$activation_type,$reward_activation_check,$amount,$referral_ranks,$user_rankss);
		}
		else if($referral_id == 0){
			$history = $db->table('history');
            $current_commission_amount1 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Direct commission for activation')->get()->getRow();
            $current_commission_amount2 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Reward Activation')->get()->getRow();
            $current_commission_amount3 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Same Rank')->get()->getRow();

      
            
            $current_commission_amount = $current_commission_amount1->amount  + $current_commission_amount2->amount + $current_commission_amount3->amount;
			$remain_comm = 60 - $current_commission_amount;
			// $admin_share = $admin_share + $remain_comm + $this->session->get('missing_comm');
			$direct_data = array(
			'uusersid' => 0,
			'type' => 'admin_id_reward',
			'description' => "Reward ID Activation Company Profit",
			'date' => date('Y-m-d H:i:s'),
			'amount' => $remain_comm, 
			'from_email' => $this->session->get('usermail')
			);
			echo"<pre>";
			print_r($direct_data);
			echo"</pre>";
			$history = $db->table('history');
			if($remain_comm > 0)
			$history_status=$history->insert($direct_data);
			return true;	
		}
	}

	//trading profit commission

	   public function trading_profit_commission($referral_id,$description,$i,$usermail,$activation_type,$reward_activation_check,$amount,$referral_rank,$user_rank,$order_id)
		{

		$admin_share = 25;
        $db  = \Config\Database::connect();
        $this->session = session();


		$i=$i;
		echo"<pre>";
		print_r($i);
		print_r(" next \n");
		echo"</pre>";
		if($i == 0)
		$getlevel = $reward_activation_check[$i];
	    else
		$getlevel = $reward_activation_check[1];


		// if($activation_type==1 || 0)
		// {
		// $commission = $getlevel;
		// }
		// else
		// {
		$commission = ($amount) * ($getlevel / 100);
		// }

		echo"<pre>";
		print_r($commission);
		echo"</pre>";

		$ids = $referral_id;

		$user_upline=$referral_id;

        echo"<pre>";
        print_r($ids);
        echo"</pre>";

		if($user_upline)
		{
		
		if($commission!="")
		{
       if($i==0)
       {
          $commission_cal = $commission;
	    $direct_data = array(
			'uusersid' => $referral_id,
			'type' => 'commissions',
			'description' => "Direct trading profit commission - ".$order_id,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $this->session->get('usermail')
		);
		
       }
       else
       {
   
       if($referral_rank==$user_rank && $this->session->get('same_rank'.$referral_rank) == 0)
       {

          $reward_get = $db->table('rewardsettings');
		  $reward_get =  $reward_get->where('id',$user_rank)->get()->getRow();

		  $get_same_activation =  $amount *  ($reward_get->global_dividend / 100);

		  $commission_cal1 = $get_same_activation;

		if($get_same_activation > 0.00000)
		{

			$direct_data = array(
				'uusersid' => $referral_id,
				'type' => 'commissions',
				'description' => $reward_get->rank_name.' Same Rank trading profit -'.$order_id,
				'date' => date('Y-m-d H:i:s'),
				'amount' => $get_same_activation, 
				'from_email' => $this->session->get('usermail')
			);
		}
           $this->session->set('same_rank'.$referral_rank,1);
        }
        else 
        {


          $reward_get = $db->table('rewardsettings');
		  $reward_get =  $reward_get->where('id',$referral_rank)->get()->getRow();
		  $getreward_level = $reward_get->reward_profit; 
		  $get_user_level = explode(',', $getreward_level)[1];
		  $get_original_comm1 = explode(',', $getreward_level)[0];
          $get_original_comm = $amount * ($get_original_comm1/100);
          $commission = $amount * ($get_user_level / 100);

          echo"<pre>";
          print_r("prev comm ".$commission);
          echo"</pre>";
		
		// if($get_user_level[$i])
		// {
			// if($activation_type==1)
			// {
			//    $commission = $get_user_level;
			// }
			// else
			// {
			   // $commission = $amount * ($get_user_level / 100);
			// }
            $last_rank = $db->table('rewardsettings')->orderBy('id','DESC')->get()->getRow();
			if($i > 0){
             $history = $db->table('history');
             $current_commission_amount = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description',"commission - ".$order_id)->get()->getRow();

             // echo"<pre>";
             // print_r($db->getLastQuery());
             // echo"</pre>";
  
             // $current_commission_amount2 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Trading profit Level')->get()->getRow();
      
            
            // $current_commission_amount = $current_commission_amount1->amount  + $current_commission_amount2->amount;
      
            $total_count_comm = $current_commission_amount->amount + $commission + $this->session->get('missing_comm');



            if($total_count_comm != $get_original_comm){
        
            	$pending_comm = $get_original_comm - ($current_commission_amount->amount + $this->session->get('missing_comm'));
            	$commission = $pending_comm;
      
            }


			}



           





         if($referral_rank > $user_rank){ 

            echo"<pre>";
			print_r("get original commission count ");
			print_r($get_original_comm);
			print_r("current commission amount ");
			print_r($current_commission_amount);
			print_r("total commission amount ");
			print_r($total_count_comm);
			print_r("commission ");
			print_r($commission);
			print_r("referral rank ");
			print_r($referral_rank);
			print_r("user rank ");
			print_r($user_rank);
			print_r("missing_comm ");
			print_r($this->session->get('missing_comm'));
			echo"</pre>";
         	
			$commission_cal = $commission;

			$direct_data = array(
			'uusersid' => $referral_id,
			'type' => 'commissions',
			'description' => 'Trading profit Level '.$reward_get->rank_name.' commission - '.$order_id,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $this->session->get('usermail')
			);
		}
        }
       }
        
		
		$history = $db->table('history');
		if($referral_rank >= $user_rank && !empty($direct_data)){
	    $confirm = $db->table('history')->where('uusersid',$referral_id)->where('type','activation')->where('status',1)->get()->getRow();
	    if($confirm){
	    	echo"<pre>";
	        print_r("original comm : ");
	    	print_r($get_original_comm);
	    	echo "<br>";
	    	print_r("current commissions : ");
	    	print_r($current_commission_amount);
	    	echo "<br>";
	    	print_r("missing comm : ");
	    	print_r($this->session->get('missing_comm'));
	    	print_r($direct_data);
	    	print_r("<br>");
	    	print_r("Before Insert");
	    	echo"</pre>";
		$history_status=$history->insert($direct_data);
		$total_comm = $this->session->get('total_comm') + $commission_cal;
		$this->session->set('total_comm',$total_comm);
	    }else{
	    $missing_comm = $this->session->get('missing_comm') + $commission_cal;
		$this->session->set('missing_comm',$missing_comm);
	    }
		}

		

		}

		}

	    $uusers_matrix = $db->table('uusers_matrix');
		$uusers_matrix =  $uusers_matrix->where('uusersid',$referral_id)->get()->getRow();
		$referral_id1 = $uusers_matrix->referral_id;
		if($referral_rank < $user_rank){
			$user_ranks = $user_rank;
		}else{
		$user_ranks = $uusers_matrix->rankid;
		}

		$uusers = $db->table('uusers')->where('uusersid',$referral_id)->get()->getRow();
		$usermail = $uusers->email;

		$uusers1 = $db->table('uusers_matrix')->where('uusersid',$referral_id1)->get()->getRow();
		$referral_rank = $uusers1->rankid;

		$rewardsettings = $db->table('rewardsettings');
		$rewardsettings =  $rewardsettings->where('id',$referral_rank)->get()->getRow();

		$reward_activation_check = explode(',', $rewardsettings->reward_profit);

		if($referral_rank > $user_ranks){
			$this->session->set('same_rank'.$referral_rank,0);
		}


		if($referral_rank=="")
		{
			$referral_ranks = 4;
		}
		else
		{
			$referral_ranks = $referral_rank;
		}

		if($user_ranks=="")
		{
			$user_rankss = 4;
		}
		else
		{
			$user_rankss = $user_ranks;
		}


		if($referral_id1!="")
		{
		$i++;
		echo"<pre>";
		print_r($i);
		print_r("commission ".$commission);
		echo"</pre>";
		$this->trading_profit_commission($referral_id1,$description,$i,$usermail,$activation_type,$reward_activation_check,$amount,$referral_ranks,$user_rankss,$order_id);
		}
		else if($referral_id == 0){
			$history = $db->table('history');
         // $current_commission_amount1 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Direct trading profit commission')->get()->getRow();
          $current_commission_amount2 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','commission - '.$order_id)->get()->getRow();
          $current_commission_amount3 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Same Rank trading profit -'.$order_id)->get()->getRow();

      
            
            $current_commission_amount =  $current_commission_amount2->amount + $current_commission_amount3->amount;
			$remain_comm = $this->session->get('fuel_amount') - $current_commission_amount;
			// $admin_share = $admin_share + $remain_comm + $this->session->get('missing_comm');
			$direct_data = array(
			'uusersid' => 0,
			'type' => 'admin_id_reward',
			'description' => "Reward ID Activation Company Trading Profit - ".$order_id,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $remain_comm, 
			'from_email' => $this->session->get('usermail')
			);
			echo"<pre>";
			print_r($direct_data);
			echo"</pre>";
			$history = $db->table('history');
			if($remain_comm > 0)
			$history_status=$history->insert($direct_data);
			return true;	
		}
	}


	// Team Reward or peer reward check
	public function teamreaward_check($userid,$amount,$description,$trade_process_id,$i,$order_id,$referral_ranks="",$user_rankss=""){

        $i=$i;
        $db  = \Config\Database::connect();

        $this->session = session();
        if($i==0){
		$uusers_matrix = $db->table('uusers_matrix');
		$uusers_matrix =  $uusers_matrix->where('uusersid',$userid)->get()->getRow();
		$uusers = $db->table('uusers')->where('uusersid',$userid)->get()->getRow();

		$usermail = $uusers->email;
		$referral_id = $uusers_matrix->referral_id;
		$user_rank = $uusers_matrix->rankid;

		$referral_matrix = $db->table('uusers_matrix');
		$referral_matrix =  $referral_matrix->where('uusersid',$referral_id)->get()->getRow();
		$referral_rank = $referral_matrix->rankid;


			if($referral_rank < $user_rank){
				$user_rank = $user_rank;
			}else{
				$user_rank = $uusers_matrix->rankid;
			}



			if($referral_rank=="")
			{
			$referral_ranks = 4;
			}
			else
			{
			$referral_ranks = $referral_rank;
			}

			if($user_rank=="")
			{
			$user_rankss = 4;
			}
			else
			{
			$user_rankss = $user_rank;
			}
		}
    



		$reward_get = $db->table('rewardsettings');
		$reward_get =  $reward_get->where('id',$referral_ranks)->get()->getRow();

		$profit_type = $reward_get->profit_type;
		if($i == 0)
		$get_user_level = explode(',', $reward_get->reward_profit)[0];
	    else
        $get_user_level = explode(',', $reward_get->reward_profit)[1];

        echo"<pre>";
		print_r("user id : ");
		print_r($userid);
		print_r("<br>");
		print_r("user rank : ");
		print_r($user_rankss);
		print_r("referral id :");
		print_r($referral_id);
		print_r("<br>");
		print_r("referral rank : ");
		print_r($referral_ranks);
		echo"</pre>";
        


       

        if($referral_id)
		{

		 if($get_user_level)
		 {

			if($profit_type==1)
			{
			   $commission = $get_user_level;
			}
			else
			{
			   $commission = ($amount / 100) * $get_user_level;
			}

			if($i == 0){
			if($commission>0.000000)
			{

			$peer_reward_data = array(
			'uusersid' => $referral_id,
			'type' => 'commissions',
			'description' => "Direct trading profit commission - ".$order_id,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $this->session->get('usermail'),
			'trade_process_id' => $trade_process_id
			);

			}
		}else {

		  if($referral_ranks==$user_rankss && $this->session->get('same_rank'.$referral_ranks) == 0)
		  {

		  	$same_rank_profit = $reward_get->global_dividend;
		  	$commission = ($amount / 100) * $same_rank_profit;

		  	if($commission>0.000000)
		  	{

            $peer_reward_data = array(
			'uusersid' => $referral_id,
			'type' => 'commissions',
			'description' => $reward_get->rank_name.' Same Rank trading profit -'.$order_id,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $this->session->get('usermail'),
			'trade_process_id' => $trade_process_id
		   );

           }

           $this->session->set('same_rank'.$referral_ranks,1);

		  }
		  else
		  {

		  $reward_get = $db->table('rewardsettings');
		  $reward_get =  $reward_get->where('id',$referral_ranks)->get()->getRow();
		  $getreward_level = $reward_get->profit_type; 
		  $get_user_level = explode(',', $getreward_level)[1];

		  $get_original_comm1 = explode(',', $getreward_level)[0];

          $get_original_comm = $amount * ($get_original_comm1 / 100);
		  	if($i==0)
		  		$description_new = "Direct trading profit commission -".$order_id;
		  	else
		  		$description_new = 'Trading profit Level '.$reward_get->rank_name.' commission -'.$order_id;

		    if($i > 0){
             $history = $db->table('history');
            $current_commission_amount1 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Direct trading profit commission')->get()->getRow();
             $current_commission_amount2 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Trading profit Level')->get()->getRow();

      
            
            $current_commission_amount = $current_commission_amount1->amount  + $current_commission_amount2->amount;
      
            $total_count_comm = $current_commission_amount + $commission + $this->session->get('missing_comm');



            if($total_count_comm != $get_original_comm){
        
            	$pending_comm = $get_original_comm - ($current_commission_amount + $this->session->get('missing_comm'));
            	$commission = $pending_comm;
      
            }


			}

			if($commission>0.000000 && $referral_ranks > $user_rankss)
			{

		    $commission_cal = $commission;

			$j=$i;
			$j++;

			$peer_reward_data = array(
			'uusersid' => $referral_id,
			'type' => 'commissions',
			'description' => $description_new,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $this->session->get('usermail'),
			'trade_process_id' => $trade_process_id
			);

			}

		  }
		}

		if($peer_reward_data)
		{
	     echo"<pre>";
	     print_r($peer_reward_data);
	     echo"</pre>";
		$history = $db->table('history');
		$confirm = $history->where('uusersid',$referral_id)->where('type','activation')->where('status',1)->get()->getRow();
	    if($confirm){
		$history = $history->insert($peer_reward_data);	
	    $total_comm = $this->session->get('total_comm') + $commission_cal;
		$this->session->set('total_comm',$total_comm);
	    }else{
        $missing_comm = $this->session->get('missing_comm') + $commission_cal;
		$this->session->set('missing_comm',$missing_comm);
	    }
		}
		}
		}


	    $uusers_matrix = $db->table('uusers_matrix');
		$uusers_matrix =  $uusers_matrix->where('uusersid',$userid)->get()->getRow();
		$referral_id = $uusers_matrix->referral_id;
		if($referral_rank < $user_rank){
			$user_ranks = $user_rank;
		}else{
		$user_ranks = $uusers_matrix->rankid;
		}

		$uusers = $db->table('uusers')->where('uusersid',$userid)->get()->getRow();
		$usermail = $uusers->email;

		$uusers1 = $db->table('uusers_matrix')->where('uusersid',$referral_id)->get()->getRow();
		$referral_rank = $uusers1->rankid;

		$rewardsettings = $db->table('rewardsettings');
		$rewardsettings =  $rewardsettings->where('id',$referral_rank)->get()->getRow();

	$reward_activation_check = explode(',', $rewardsettings->reward_activation);

		if($referral_rank > $user_ranks){
			$this->session->set('same_rank'.$referral_rank,0);
		}


		if($referral_rank=="")
		{
			$referral_ranks = 4;
		}
		else
		{
			$referral_ranks = $referral_rank;
		}

		if($user_ranks=="")
		{
			$user_rankss = 4;
		}
		else
		{
			$user_rankss = $user_ranks;
		}

		if($referral_id!="")
		{
		$i++;
		$this->teamreaward_check($referral_id,$amount,$description,$trade_process_id,$i,$order_id,$referral_ranks,$user_rankss);
		}
	    else if($referral_id == 0){
			$history = $db->table('history');
          $current_commission_amount1 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Direct trading profit commission')->get()->getRow();
          $current_commission_amount2 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Trading profit Level')->get()->getRow();
          $current_commission_amount3 = $history->selectSum('amount')->where('type','commissions')->where('from_email',$this->session->get('usermail'))->like('description','Same Rank trading profit -'.$order_id)->get()->getRow();

      
            
            $current_commission_amount = $current_commission_amount1->amount  + $current_commission_amount2->amount + $current_commission_amount3->amount;
			$remain_comm = $this->session->get('fuel_amount') - $current_commission_amount;
			// $admin_share = $admin_share + $remain_comm + $this->session->get('missing_comm');
			$direct_data = array(
			'uusersid' => 0,
			'type' => 'admin_id_reward',
			'description' => "Company Trading Profit -".$order_id,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $remain_comm, 
			'from_email' => $this->session->get('usermail')
			);
			echo"<pre>";
			print_r($direct_data);
			print_r($remain_comm);
			echo"</pre>";
			$history = $db->table('history');
			if($remain_comm > 0)
			$history_status=$history->insert($direct_data);
			return true;	
		}

	}

	// Team Reward or peer reward check
	// public function teamreaward_check($userid,$amount,$description,$trade_process_id){
	// 	$db      = \Config\Database::connect();
	// 	$uusers_matrix = $db->table('uusers_matrix');
	// 	$uusers_matrix =  $uusers_matrix->where('uusersid',$userid)->get()->getRow();

	// 	$uusers = $db->table('uusers')->where('uusersid',$userid)->get()->getRow();
		
	// 	$usermail = $uusers->email;

	// 	$referral_id = $uusers_matrix->referral_id;

	// 	$referral_matrix = $db->table('uusers_matrix');
	// 	$referral_matrix =  $referral_matrix->where('uusersid',$referral_id)->get()->getRow();

	// 	$referral_id = $referral_matrix->uusersid;
		
	// 	$referral_rank = $referral_matrix->rankid;

	// 	if(empty($referral_rank))
	// 		$referral_rank='4';

	// 	if(empty($uusers_matrix->rankid))
	// 		$uusers_matrix->rankid ='4';


	// 	$rewardsettings = $db->table('rewardsettings');
	// 	$rewardsettings =  $rewardsettings->where('id',$referral_rank)->get()->getRow();

	// 	$last_rank = $db->table('rewardsettings')->orderBy('id','DESC')->get()->getRow();

	// 	if ($uusers_matrix->rankid >= $referral_rank) {
			
	// 		if ($rewardsettings->PWR_reward > 0) {
	// 			$commission = $amount * $rewardsettings->PWR_reward / 100;
 //                if($commission > 0)
	// 			$this->peer_reward($referral_id,$commission,$description,$usermail,$trade_process_id);
	// 		}

	// 	}else{
			
			
	// 		if ($rewardsettings->team_reward > 0) {
	// 			$commission = $amount * $rewardsettings->team_reward / 100;
 //                if($commission > 0)
	// 			$this->teamreaward($referral_id,$commission,$description,$usermail,$trade_process_id);

	// 		}
	// 	}


	// 	// if($referral_rank == $last_rank->id){
	// 	// 	$commission = $amount * $last_rank->global_dividend / 100;
 //  //               if($commission > 0)
	// 	// 		$this->global_reward($referral_id,$commission,$description,$usermail,$trade_process_id);
	// 	// } 


	// }

	// Strategy check

	public function strategy_check($userid,$profit,$trade_process_id,$order_id,$id) {
		$db      = \Config\Database::connect();
		$user_strategy = $db->table('trade_process');
		$user_strategy =  $user_strategy->where('id',$trade_process_id)->where('uusersid',$userid)->get()->getRow();
			
		if ( $user_strategy->sync_strategy_status == '' || $user_strategy->sync_strategy_status == '0' ) {
			
			// Without strategy profit

			$profit_data = array(
				'uusersid' => $userid,
				'type' => 'trade_profit',
				'description' => 'Profit for order no '.$order_id,
				'date' => date('Y-m-d H:i:s'),
				'amount' => $profit, 
				'from_email' => '',
				'trade_process_id' => $trade_process_id
			);

			$history = $db->table('history');
            if($profit > 0 && $profit != '') 
			    $history = $history->insert($profit_data);

		}else{

            $strategy_id = $user_strategy->strategy_id;
			if ($strategy_id != '' && $user_strategy->sync_strategy_status == 1) {
				$strategy_get = $db->table('trader')->where('id',$strategy_id)->get()->getRow();
				if ($strategy_get->profit > 0 && $strategy_get != '') {

					$usercommission_per =  100 - $strategy_get->profit;

					$admincommission_per = $strategy_get->profit; 
$trade_details = $db->table('api_trade_history')->where('id',$id)->get()->getRow();
					// with strategy profit

					$profit_data = array(
						'uusersid' => $userid,
						'type' => 'trade_profit',
						'description' => 'Profit for order no '.$order_id,
						'date' => date('Y-m-d H:i:s'),
						'amount' => $profit * $usercommission_per / 100, 
						'from_email' => '',
						'statagy_id' => $strategy_get->id,
						'pair' => $trade_details->pair,
						'btc_amount' => $trade_details->profit_percentage,
						'trade_process_id' => $trade_process_id
					);
					
					$history = $db->table('history');
                    if($profit > 0 || $profit != '') 
					$history = $history->insert($profit_data);

					$uusers = $db->table('uusers');
					$uusers = $uusers->where('uusersid',$userid)->get()->getRow();
					$uusers_circle = $db->table('uusers')->where('uusersid',$strategy_get->uusersid)->get()->getRow();
				

					// strategy admin profit
					
					$profit_data = array(
						'uusersid' => $strategy_get->uusersid,
						'type' => 'circle_profit',
						'description' => 'Circle Profit for order no'.$order_id,
						'date' => date('Y-m-d H:i:s'),
						'amount' => $profit * $admincommission_per / 100, 
						'from_email' => $uusers->email,
						'statagy_id' => $strategy_get->id,
						'pair' => $trade_details->pair,
						'btc_amount' => $trade_details->profit_percentage,
						'trade_process_id' => $trade_process_id
					);

					$deduct_data = array(
						'uusersid' => $userid,
						'type' => 'circle_deduct',
						'description' => 'Sync deduction for order no'.$order_id,
						'date' => date('Y-m-d H:i:s'),
						'amount' => $profit * $admincommission_per / 100, 
						'from_email' => $uusers_circle->email,
						'trade_process_id' => $trade_process_id
					);

					$history = $db->table('history');
                if($profit * $admincommission_per / 100 > 0){
					$history = $history->insert($profit_data);
					$history1 = $db->table('history')->insert($deduct_data);
			    }

				}else{
					
					// zero strategy profit 
					
					$profit_data = array(
						'uusersid' => $userid,
						'type' => 'trade_profit',
						'description' => 'Profit for order no',
						'date' => date('Y-m-d H:i:s'),
						'amount' => $profit, 
						'from_email' => '',
						'trade_process_id' => $trade_process_id
					);

					$history = $db->table('history');
                 if($profit > 0 && $profit != '') 
					$history = $history->insert($profit_data);
				}
			}
		}
		
	}
	
	// Direct commission provide

	public function directcommission($directid,$commission,$description,$usermail){

		$direct_data = array(
			'uusersid' => $directid,
			'type' => 'commissions',
			'description' => 'Direct commission'.$description,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $usermail
		);
		$db      = \Config\Database::connect();
		$history = $db->table('history');

		// $history = $history->insert($direct_data);
		return true;

	}

	// Team Reward provide
	
	public function teamreaward($userid,$commission,$description,$usermail,$trade_process_id){

		$team_rewar_data = array(
			'uusersid' => $userid,
			'type' => 'commissions',
			'description' => 'Team reward commision'.$description,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $usermail,
			'trade_process_id' => $trade_process_id
		);

		

		$db      = \Config\Database::connect();
		$history = $db->table('history');

		$history = $history->insert($team_rewar_data);

	}

	// Peer Rewar Provide

	public function peer_reward($userid,$commission,$description,$usermail,$trade_process_id){
		$peer_reward_data = array(
			'uusersid' => $userid,
			'type' => 'commissions',
			'description' => 'Peer reward commision'.$description,
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => $usermail,
			'trade_process_id' => $trade_process_id
		);

		$db      = \Config\Database::connect();
		$history = $db->table('history');

		$history = $history->insert($peer_reward_data);	
	}

	// Global Reward provide

	public function global_reward($userid,$commission){
		$currentMonth = date('F');
        $last_month = Date('F', strtotime($currentMonth . " last month"));
		$global_reward_data = array(
			'uusersid' => $userid,
			'type' => 'commissions',
			'description' => 'Global dividend commission from '.$last_month.' month',
			'date' => date('Y-m-d H:i:s'),
			'amount' => $commission, 
			'from_email' => "admin"
		);

		$db      = \Config\Database::connect();
		$history = $db->table('history');

		$history = $history->insert($global_reward_data);
	}
}