<?php
namespace App\Libraries;
class Commission {

/**
* 
* Start 
* Create Date: 04 Oct, 2016
* This library is used for uni level or matrix commision calculation.
* Created saravanan.
* Last Updated: 11 Oct, 2016
* End
* 
*/
    private $referral_datas =  array();
    private $level_datas =  array();
    

    public function __construct() 
    {
        $CI = db_connect();
        $CI->common_model = model('CommonModel');
        $referral_setting = $CI->common_model->GetSettingall('referral');

        foreach ($referral_setting as $row) {
            $referral_data[$row->site_key] = $row->site_value;
        }
        $this->referral_datas = $referral_data;

        $level_setting = $CI->common_model->GetSettingall('level');

        foreach ($level_setting as $row) {
            $level_data[$row->site_key] = $row->site_value;
        }

        $this->level_datas = $level_data;
        
    }
    public function test($userid,$depositid,$amount)
    {
        $CI = db_connect();
        $builder = $CI->db->table('uusers');
        $builder->select('*');
        $builder->where('uusersid',$userid);
        $query = $builder->get();
        $udetails = $query->getRow();
        $username=$udetails->username;

        $this->check_level_com($userid,$amount,0,$username,1);
        
        //echo 'test';
    }

    public function test1($userid,$amount)
    {

        $CI = db_connect();
        $builder =  $CI->db->table('uusers');
        $builder->select('*');
        $builder->where('uusersid',$userid);
        $query = $builder->get();
        $udetails = $query->row();
        $username=$udetails->username;
        $this->check_level_com($userid,$amount,0,$username,2);
        
        
    }

    public function check_level_com($userid,$amount,$level,$username,$typ)
    {
        $CI = db_connect();
        $CI->common_model = model('CommonModel');
        $level = $level+1;
        $builder = $CI->db->table('uusers');
        $builder->select('*');
        $builder->where('uusersid',$userid);
        $query = $builder->get();
        $udetails = $query->getRow();
       $vue =  $CI->db->table('site_controls');
        
        $vue->select('*');
        if($typ=='2')
            $vue->where('settings_name','stacklevel');
        else
           $vue->where('settings_name','level'); 

        $vue->where('site_key','interest_type');
        $vue->from('site_controls');
        $query = $vue->get();
        $int_details = $query->row();
        $vue->select('*');
        if($typ=='2')
            $vue->where('settings_name','stacklevel');
        else
            $vue->where('settings_name','level');   

        $vue->where('site_key',"level".$level);
        $query = $vue->get();
        $comm_details = $query->getRow();
        if($comm_details)
            $comm_per=$comm_details->site_value;
        else
            $comm_per=0;

        if($int_details->site_value=='percentage')
        {
            $comm_amount=$amount*$comm_per/100;
        }
        if($int_details->site_value=='amount')
        {
            $comm_amount=$comm_per;
        }

        

        $condition = "uusersid = '".$udetails->referral_id."'";
        $lcheckmatmem = $CI->common_model->GetRow("uusers", $condition);

        if($lcheckmatmem->uusersid > 0)
        {
            if($typ=='2')
                $mode='3';
            else
                $mode='4';

             if($int_details->site_value=='coin')
             {

                $date_det=$CI->db->query("select * from admin_price order by date desc limit 1");
                $ex_det=$date_det->result();
                $token_amount=$ex_det[0]->amount;
                $token_val=floor($amount/$token_amount);
                if($token_val>0)
                {                       
                    $trans_id=strtoupper(random_string('alnum', 20));
                    $token_details = array(
                            "icocalid"  =>  '1',
                            "amount"    => '0',
                            "notokens"  => $token_val,
                            "uuserid"   => $userid,
                            "type"      =>'buy',
                            "currency"  =>'0',
                            "curr_amt"  =>'0',
                            "mode"      => $mode,
                            "transactionid" => $trans_id
                        );

                    $query_status1 = $CI->db->insert('tokens',$token_details);
                }
                    $this->check_level_com($lcheckmatmem->uusersid, $amount,$level,$username,$typ);

             }
             else
             {
                 $this->check_level_com($lcheckmatmem->uusersid, $amount,$level,$username,$typ);
                  $this->level_comm($lcheckmatmem->uusersid,$comm_amount,$level,$username,$typ);

             }

           
            
        }

    }

    private function level_comm($userid,$commission,$i,$username,$typ)
    {
        if($typ=='1')
            $desc='Lending Level-'.$i.' commission for - '.$username;
        else
            $desc='Stacking Level-'.$i.' commission for - '.$username;
        
        $CI = db_connect();
        $data = array(
            'uusersid'  =>  $userid,
            'amount'    =>  $commission,
            'type'  =>  'commissions',
            'Description'   =>  'Level-'.$i.' commission for - '.$username,
            'date'  =>  date('Y-m-d H:i:s'),
            'payment_id' => '0',
            'transactionid' =>  "COM".strtoupper(uniqid())
        );
        $userdetails = $CI->db->table('history')->insert($data);

        echo $CI->db->last_query();
        
    }

    public function Commission_calc($uusersid,$depositid) {
        // pr($this->referral_datas);
        // echo $uusersid;
        $CI = db_connect();
        /* get user details  */

        // $ucondition = "uusersid = '".$uusersid."'";
        // $udetails = $CI->common_model->GetRow('uusers', $ucondition);
        $builder = $CI->db->table('uusers_matrix');
        $CI->db->select('deposit.status, deposit.amount, uusers_matrix.*');
        $CI->db->where('deposit.status','active');
        $CI->db->join('deposit', 'deposit.uusersid = uusers_matrix.uusersid', 'inner');
        $CI->db->where('uusers_matrix.uusersid', $uusersid);
        $CI->db->where('deposit.depositid', $depositid);
        $query = $CI->db->get();
        
        if ($query->num_rows()>0) {
            $udetails = $query->row();
            $deposit_user = $CI->common_model->GetUsername("uusers","uusersid = '".$uusersid."'");
        } 

        if(isset($udetails)) {
        
            /* get downline details  */
            $dcondition = "uusersid = '".$udetails->referral_id."'";
            $ddetails = $CI->common_model->GetRow('uusers_matrix', $dcondition);


            
            if($ddetails) {

                $lcheckmatmem = $CI->common_model->userdownlinerank($ddetails->uusersid);

                if($this->referral_datas['ref_solid_comm'] == 'on' ) {
                    $dcommission = $this->referral_datas['ref_solid_comm_amnt'];
                } else {
                    $dcommission = $udetails->amount * $this->referral_datas['ref_comm_aft_deposit'] / 100 ;
                }

                if($dcommission) {
                    $dresult = $this->directcommission($ddetails->uusersid,$dcommission,$deposit_user->username);
                }
            }

            
            
            if($udetails->spillover_id != $udetails->referral_id) 
            {
                $this->checklevel($udetails->spillover_id, '1', $udetails->amount,$deposit_user->username);
                
            }
            else {

                if($udetails->spillover_id > 0)
                {
                    $condition = "uusersid = '".$udetails->spillover_id."'";
                    $lcheckmatmem = $CI->common_model->GetRow("uusers_matrix", $condition);
                    $this->checklevel($lcheckmatmem->spillover_id, '1', $udetails->amount, $deposit_user->username);
                }
            }
            
        }
        

    }

    function checklevel($uusersid, $level, $deposit, $username) {

        if($uusersid > 0 )  {
        
            $CI = db_connect();
            $level = $level + 1;
            if($level<=10) 
            {
                // $condition = "uusersid = '".$uusersid."'";
                // $lcheckmatmem = $CI->common_model->GetRow("uusers_matrix", $condition);
                $lcheckmatmem = $CI->common_model->userdownlinerank($uusersid);
                

                if($lcheckmatmem->rankid) {
                    $condition = "rankid = '".$lcheckmatmem->rankid."' AND status='1'";
                    $check_rank = $CI->common_model->GetRow("rank_controls", $condition);
                    if($check_rank) {
                        $rankcommission = explode(',',$check_rank->levelcommission);
                        $exploded = array_combine(range(1, count($rankcommission)), $rankcommission);
                        
                        if($exploded[$level]){
                            $lcommission = ($deposit * $exploded[$level]) / 100;
                        }
                        else {
                            $level_name = 'level'.$level;
                            $lcommission = ($deposit * $this->level_datas[$level_name]) / 100 ; 
                        }

                    }
                    
                } else {
                    $level_name = 'level'.$level;
                    $lcommission = $deposit * $this->level_datas[$level_name] / 100 ; 
                }

                if(isset($lcommission) && isset($lcheckmatmem->spillover_id) > 0) {
                    $this->levelcommission($uusersid, $lcommission, $level, $username);
                    $this->checklevel($lcheckmatmem->spillover_id, $level, $deposit, $username);
                }
                
            } 
            else 
            {
                return  TRUE;
            }
        } else {
            return  FALSE;
        }
    }

    private function directcommission($userid,$commission,$username)
    {
        $CI = db_connect();
        $data = array(
            'uusersid'  =>  $userid,
            'amount'    =>  $commission,
            'type'  =>  'commissions',
            'Description'   =>  'Direct commission for reffer - '.$username,
            'date'  =>  date('Y-m-d H:i:s'),
            'payment_id' => '0',
            'transactionid' =>  "COM".strtoupper(uniqid())
        );
        $userdetails = $CI->db->insert('history', $data);
        
        // $userdetails = $this->common_model->SaveRecords($data,'history');
    }

    private function levelcommission($userid,$commission,$i,$username)
    {
        $CI = db_connect();
        $data = array(
            'uusersid'  =>  $userid,
            'amount'    =>  $commission,
            'type'  =>  'commissions',
            'Description'   =>  'Level-'.$i.' commission for - '.$username,
            'date'  =>  date('Y-m-d H:i:s'),
            'payment_id' => '0',
            'transactionid' =>  "COM".strtoupper(uniqid())
        );
        $userdetails = $CI->db->insert('history', $data);
        
    }

    public function setforcematrix($uusersid)
    {
        $CI = db_connect();
        $CI->common_model = model('CommonModel');

        $width_height = explode('X', $this->referral_datas['ref_mlm_plan']);
        $height = $width_height['0'];
        $width = $width_height['1'];

        /* get user details  */
        $ucondition = "uusersid = '".$uusersid."'";
        $udetails = $CI->common_model->GetRow('uusers', $ucondition);
        
        $direct_referral = ($udetails->referral_id) ? $udetails->referral_id : $this->referral_datas['ref_user'];
        /* get downline details  */
        $dcondition = "uusersid = '".$direct_referral."'";
        $ddetails = $CI->common_model->GetRow('uusers_matrix', $dcondition);
        
        $dmcount = $ddetails->user_count;
        $date = date('Y-m-d H:i:s');
        
        if($dmcount < $width)
        {
            $Mdata = array(
                'spillover_id'  =>  $direct_referral,
                'referral_id'   =>  $direct_referral,
                'uusersid'  =>  $uusersid,
                'cr_date' =>  $date
            );
            
            $Mresult = $CI->db->table('uusers_matrix')->insert($Mdata);
            
            if($Mresult)
            {
                $builder = $CI->table('uusers_matrix');
                $builder->set('user_count', 'user_count+1', FALSE);
                $builder->where('uusersid', $direct_referral);
                $Dresult = $builder->update();
            }
            
        }
        else
        {

            $res = $CI->common_model->GetResults("uusers_matrix", "spillover_id = '".$direct_referral."' ");
            $Downids = array($direct_referral);
            if($res != ''){
            foreach ($res as $row) {
                $Downids[] = $row->uusersid;
            }
           }
            
            $dowid = $this->GetSpillover($Downids);
            $userids = implode(",", $dowid);
            
            $query = $CI->query("SELECT * FROM uusers_matrix WHERE spillover_id  IN (".$userids.") AND user_count < '".$width."' order by uusersid asc limit 0,1 ");
            
            $query_res = $query->getRow();
            
            if($query_res) {
                $spillid = $query_res->uusersid;
                
                $Mdata = array(
                    'spillover_id'  =>  $spillid,
                    'referral_id'   =>  $direct_referral,
                    'uusersid'  =>  $uusersid,
                    'cr_date' =>  $date
                );
                
                $Mresult = $CI->db->table('uusers_matrix')->insert($Mdata);
                
                if($Mresult)
                {
                    $builder = $CI->table('uusers_matrix');
                    $builder->set('user_count', '`user_count` + 1', FALSE);
                    $builder->where('uusersid', $spillid);
                    $spcondition = "uusersid='".$spillid."'";
                    $Mresult = $builder->update();
                    return TRUE;
                }
            }

        }

    }

    private function GetSpillover($Downids)
    {
        $CI =db_connect();
        $array = $Downids;
        foreach ($Downids as $downid) {
            $builder = $CI->table('uusers_matrix');
            $builder->where('spillover_id', $downid);
            $spil_qry = $builder->get();
            
            foreach ($spil_qry->getResult() as $spil) {
                array_push($array,$spil->uusersid);
            }
            
        }
        return array_unique($array);
    }

    
    private function trackuser() {

        $CI->db =db_connect();
        $data = array(
            'ip' => $_SERVER['REMOTE_ADDR'],
            'path' => $path,
            'date' => date('Y-m-d H:i:s')
        );
        $CI->db->table('trackip')->insert($data);
        
    }


       
}

?>