<?php
use App\model\Leadclient;
use App\model\HelpForum;
use App\User;
use App\model\Property;
use App\model\Company;
use App\model\Distributorleadmarket;
//use Session;



if(!function_exists('get_property')){
   function get_property($prop_id){
      return Property::find($prop_id);      
   }
}

if(!function_exists('user_rights')){
   function user_rights($user_role){
    if($user_role!=SUPERADMIN && $user_role!=ADMIN){
       return false;
    }else{
      return true;
    }     
   }
}

 


if(!function_exists('info_boxes')){
  function info_boxes($agent_id,$user_role){
                  
    $getmovescou      =   0;
    $getInvoicedcou   =   0;
    $getmovescouNew   =   0;
    $getrecievedcou   =   0;
    $getsoldcou       =   0;
    $getleadcou       =   0;
    $getfollowupscou  =   0;
    $getleasecou      =   0;
    $getinvoicedcou   =   0;
    $getsolddcou      =   0;

    if($user_role == ARUSER){
      
      $useraragent  =   User::where('user_role','=',AGENT)
                              ->where('assign_to_ar','=',$agent_id)
                              ->pluck('id')
                              ->toArray();
      
      $statusarry       = ['Lease Confirmed','10'];
      $getmovescouNew   = Leadclient::whereIn('curr_status',$statusarry)
                                    ->whereIn('agent_id', $useraragent)
                                    ->where(function($query){
                                      $query->select('*')
                                        ->where('lead_client.ar_contact_date_next','<=',date('Y-m-d'))
                                        ->orWhereNull('lead_client.ar_contact_date_next');
                                      })
                                      ->count();
      $statusarry       = ['Invoiced','12','Invoice 30','Invoice 60','Invoice 90','Past Due','Payment OTW','18','19','20','21','22'];
      $getInvoicedcou   = Leadclient::whereIn('curr_status',$statusarry)
                                  ->whereIn('agent_id', $useraragent)
                                  ->where(function($query){
                                    $query->select('*')
                                    ->where('lead_client.ar_contact_date_next','<=',date('Y-m-d'))
                                    ->orWhereNull('lead_client.ar_contact_date_next');
                                   })->count();
      $statusarry      = ['Pay Received','13'];
      $getrecievedcou = Leadclient::whereIn('curr_status',$statusarry)
                                    ->whereIn('agent_id', $useraragent)
                                    ->where(function($query){
                                       $query->select('*')
                                        ->where('lead_client.ar_contact_date_next','<=',date('Y-m-d'))
                                        ->orWhereNull('lead_client.ar_contact_date_next');
                                    })->count();
      $statusarry     = ['Sold','9'];
      $getsoldcou     = Leadclient::whereIn('curr_status',$statusarry)
                                  ->whereIn('agent_id', $useraragent)
                                  ->where(function($query){
                                    $query->select('*')
                                    ->where('lead_client.ar_contact_date_next','<=',date('Y-m-d'))
                                    ->orWhereNull('lead_client.ar_contact_date_next');
                                  })->count();
                                  
        $statusarry = ['Under Contract','16'];
        $getucdcou     = Leadclient::whereIn('curr_status',$statusarry)
                                  ->whereIn('agent_id', $useraragent)
                                  ->where(function($query){
                                    $query->select('*')
                                    ->where('lead_client.ar_contact_date_next','<=',date('Y-m-d'))
                                    ->orWhereNull('lead_client.ar_contact_date_next');
                                  })->count();
                                      
        $statusarry = ['Verifying Lease','17'];
        $getvldcou     = Leadclient::whereIn('curr_status',$statusarry)
                                  ->whereIn('agent_id', $useraragent)
                                  ->where(function($query){
                                    $query->select('*')
                                    ->where('lead_client.ar_contact_date_next','<=',date('Y-m-d'))
                                    ->orWhereNull('lead_client.ar_contact_date_next');
                                  })->count();
                                      
    }elseif($user_role == ADMIN){
      
        $useraragent      =   User::where('user_role','=',AGENT)
                                ->where('create_by_user','=',$agent_id)
                                ->where('status','=',1)
                                ->pluck('id')
                                ->toArray();

        $statusarry       = ['New', 'Repeat','1','2'];
        $getleadcou       = Leadclient::whereIn('curr_status',$statusarry)
                                  ->whereIn('agent_id', $useraragent)
                                  ->count();

        $statusarry       = ['New','Repeat','Prospect','Hot','Warm','1','2','3','4','5'];
        $getfollowupscou  = Leadclient::whereIn('curr_status',$statusarry)
                                    ->whereIn('agent_id', $useraragent)
                                    ->where(function($query){
                                      $query->select('*')
                                      ->where('lead_client.contact_nxt_date','<=',date('Y-m-d'))
                                      ->orWhereNull('lead_client.contact_nxt_date');
                                    })
                                    ->count();
        //For lease count
        $statusarry       = ['Pending','Lease Confirmed','10','8'];
        $getleasecou      = Leadclient::whereIn('curr_status',$statusarry)
                                        ->whereIn('agent_id', $useraragent)
                                        ->count();
       
       //For invoiced count
        $statusarry       = ['Invoiced','12','Invoice 30','Invoice 60','Invoice 90','Past Due','Payment OTW','18','19','20','21','22'];
        $getinvoicedcou   = Leadclient::whereIn('curr_status',$statusarry)
                                        ->whereIn('agent_id', $useraragent)
                                        ->where(function($query){
                                          $query->select('*')
                                          ->where('lead_client.ar_contact_date_next','<=',date('Y-m-d'))
                                          ->orWhereNull('lead_client.ar_contact_date_next');
                                        })
                                        ->count();

        $statusarry       = ['Sold','9'];
        $getsolddcou      = Leadclient::whereIn('curr_status',$statusarry)
                                        ->whereIn('agent_id', $useraragent)
                                        ->count();
                                        
        $statusarry = ['Under Contract','16'];
        $getucdcou =    Leadclient::whereIn('curr_status',$statusarry)
                                      ->where('agent_id','=',$agent_id) 
                                      ->count();
                                        
        $statusarry = ['Verifying Lease','17'];
        $getvldcou =    Leadclient::whereIn('curr_status',$statusarry)
                                      ->where('agent_id','=',$agent_id) 
                                      ->count();
    }else{
      
      $statusarry = ['New', 'Repeat','1','2'];
      $getleadcou =   Leadclient::whereIn('curr_status',$statusarry)
                                  ->where('agent_id','=',$agent_id) 
                                  ->count();
      
      $statusarry = ['New','Repeat','Prospect','Hot','Warm','1','2','3','4','5'];
      $getfollowupscou =  Leadclient::whereIn('curr_status',$statusarry)
                                  ->where('agent_id','=',$agent_id) 
                                  ->where(function($query){
                                    $query->select('*')
                                    ->where('lead_client.contact_nxt_date','<=',date('Y-m-d'))
                                    ->orWhereNull('lead_client.contact_nxt_date');
                                  })
                                  ->count();
      //For lease count
      
       
        if($user_role == ARUSER){
         $statusarry = ['Pending','Lease Confirmed','Under Contract','Verifying Lease','10','8','16','17'];   
        }else{
            $statusarry = ['Pending','Lease Confirmed','Under Contract','Verifying Lease','10','8','16','17'];
        }
      
      $getleasecou =  Leadclient::whereIn('curr_status',$statusarry)
                                      ->where('agent_id','=',$agent_id) 
                                      ->count();
     //For invoiced count
        $statusarry = ['Invoiced','12','Invoice 30','Invoice 60','Invoice 90','Past Due','Payment OTW','18','19','20','21','22'];
        $getinvoicedcou = Leadclient::whereIn('curr_status',$statusarry)
                                      ->where('agent_id','=',$agent_id) 
                                      ->count();
      
        $statusarry = ['Sold','9'];
        $getsolddcou =    Leadclient::whereIn('curr_status',$statusarry)
                                      ->where('agent_id','=',$agent_id) 
                                      ->count();
                                      
        $statusarry = ['Under Contract','16'];
        $getucdcou =    Leadclient::whereIn('curr_status',$statusarry)
                                      ->where('agent_id','=',$agent_id) 
                                      ->count();
                                      
        $statusarry = ['Verifying Lease','17'];
        $getvldcou =    Leadclient::whereIn('curr_status',$statusarry)
                                      ->where('agent_id','=',$agent_id) 
                                      ->count();
    } 

    $leadshowcou =  [
                      'lead'            =>  $getleadcou,
                      'followups'       =>  $getfollowupscou,
                      'lease'           =>  $getleasecou,
                      'Invoiced'        =>  $getinvoicedcou,
                      'getmovescou'     =>  $getmovescou,
                      'getmovescouNew'  =>  $getmovescouNew,
                      'getInvoicedcou'  =>  $getInvoicedcou,
                      'solds'           =>  $getsolddcou,
                      'getrecievedcou'  =>  $getrecievedcou,
                      'getsoldcou'      =>  $getsoldcou,
                      'getucdcou'       =>  $getucdcou,
                      'getvldcou'       =>  $getvldcou
                    ];
    return $leadshowcou;
  }
}

/* Function  to get notification_sender name */
if(!function_exists('notification_sender')){

  function notification_sender($id){
          
          $userdetail      =   User::find($id);               
          return $userdetail->name;
  }
}

/* Function  to get leads */
if(!function_exists('leads')){

  function leads($id,$from_date,$to_date){
          $statusarry =   ['New','Repeat','1','2'];
          $leads      =   sizeof(Leadclient::join('lead_status_history', 'lead_status_history.lead_id', '=', 'lead_client.id')
                    ->select('lead_client.id')     
                    ->whereIn('lead_client.agent_id',$id) 
                    ->whereIn('lead_status_history.status',$statusarry)
                    ->whereBetween('lead_status_history.date',[$from_date,$to_date]) 
                    ->distinct('lead_client.id') 
                    ->get());               
          return $leads;
  }
}  

/* function to check the sold is exists or not aand calculation */
  if(!function_exists('solds')){

    function solds($id,$from_date,$to_date){
          $statusarry = ['Sold','9'];
          $leads      = sizeof(Leadclient::join('lead_status_history', 'lead_status_history.lead_id', '=', 'lead_client.id')
                                      ->select('lead_client.id')     
                                      ->whereIn('lead_status_history.status',$statusarry)
                                      ->where('lead_client.agent_id','=',$id) 
                                      ->where('lead_status_history.date','>=',$from_date) 
                                      ->where('lead_status_history.date','<=',$to_date) 
                                      ->groupby('lead_status_history.status')
                                      ->groupby('lead_client.id')
                                      ->distinct('lead_client.id')
                                      ->get()); 
          return $leads;
    }
  }  
/* this function is for new lead testing */

  if(!function_exists('newlead')){

    function newlead($id,$from_date,$to_date){
      $leads = sizeof(Leadclient::select('lead_client.id')      
                                  ->where('lead_client.agent_id','=',$id) 
                                  ->where('lead_client.created_at','>=',$from_date) 
                                  ->where('lead_client.created_at','<=',$to_date) 
                                  ->get());
      return $leads;
    }
  }  

/* function to check the existance along with lease confirm  */
  if(!function_exists('leaseconfirm')){
    function leaseconfirm($id,$from_date,$to_date,$statusarry){
        $lease_confirmed =  sizeof(Leadclient::join('lead_status_history', 'lead_status_history.lead_id', '=', 'lead_client.id')
                  ->select('lead_client.id')     
                  ->whereIn('lead_status_history.status',$statusarry)
                  ->whereIn('lead_client.agent_id',$id) 
                  ->whereBetween('lead_status_history.date',[$from_date,$to_date]) 
                  ->groupby('lead_status_history.status')
                  ->groupby('lead_client.id')
                  ->distinct('lead_client.id')
                  ->get()); 
        return $lease_confirmed;
    }
  }

  if(!function_exists('inv_sent')){
    function inv_sent($id,$from_date,$to_date){

      $statusarry =   ['Invoiced','12'];
      $Revenue    =   sizeof(Leadclient::join('lead_status_history', 'lead_status_history.lead_id', '=', 'lead_client.id')
                                ->select('lead_client.id')     
                                ->whereIn('curr_status',$statusarry)
                                ->where('lead_client.agent_id','=',$id) 
                                ->whereBetween('lead_status_history.date',[$from_date,$to_date])
                                ->distinct('lead_client.id') 
                                ->get()); 
      return $Revenue;
    }
  }

/* function to check the existance and apartment gross amount */

  if(!function_exists('apartment_gross')){  
    function apartment_gross($id,$from_date,$to_date){

        $total      = 0;
        $statusarry = ['Pay Received','13'];

        $incent     =  Leadclient::join('lead_status_history', 'lead_status_history.lead_id', '=', 'lead_client.id')->select('lead_client.*')
                        ->whereIn('lead_client.agent_id',$id)
                        ->whereIn('lead_status_history.status',$statusarry)
                        ->whereBetween('lead_status_history.date',[$from_date,$to_date])
                        ->distinct('lead_client.id')  
                        ->get(); 
         
        foreach($incent as $valuetotal){

          if($valuetotal->transaction_type_id==1 || $valuetotal->prop_id!=0){
                   


            if(trim($valuetotal->commision)==""){
              $valuetotal->commision=0;
            }

            if(trim($valuetotal->bonus)==""){
              $valuetotal->bonus=0;
            }

            if($valuetotal->commision_unit=="1") {
               
              if($valuetotal->commision!=0 || $valuetotal->commision!=0.00) {

                $tot_com=((float) $valuetotal->rent_amount*((float) $valuetotal->commision/100));
                $total+=(float) $tot_com + (float) $valuetotal->bonus;
              }else{
                $total+= (float) $valuetotal->bonus;
              }
            }else{
              $total+= (float) $valuetotal->commision + (float) $valuetotal->bonus;
            }
          }
        }
        return  $total;
    }
  }

  if(!function_exists('residential_gross')){
    function residential_gross($id,$from_date,$to_date){

      $total      =   0;
      $statusarry =   ['Pay Received','13'];
      $incent     =   Leadclient::join('lead_status_history', 'lead_status_history.lead_id', '=', 'lead_client.id')->select('lead_client.*')
            ->whereIn('lead_client.agent_id',$id)
            ->whereIn('lead_status_history.status',$statusarry)
            ->whereBetween('lead_status_history.date',[$from_date,$to_date])
            ->distinct('lead_client.id')  
    
            ->get(); 

      foreach($incent as $valuetotal){

        if(($valuetotal->transaction_type_id==2 || $valuetotal->transaction_type_id==3 || $valuetotal->transaction_type_id==0) && $valuetotal->prop_id==0){

          if (trim($valuetotal->sold_amt)==""){
            $valuetotal->sold_amt=0;
          }

          if (trim($valuetotal->house_comm)==""){
            $valuetotal->house_comm=0;
          }   

          if (trim($valuetotal->house_bonus)==""){
            $valuetotal->house_bonus=0;
          }   

          $total+=  ((float) $valuetotal->sold_amt*((float) $valuetotal->house_comm/100))+(float) $valuetotal->house_bonus;
        }
      }

      return $total;
    }
  }
 

  if(!function_exists('incentive')){
    function incentive($id,$from_date,$to_date,$statusarry){

      $total            =   0;
      $total_amt        =   0;
      $incent           =   Leadclient::join('lead_status_history','lead_status_history.lead_id','=','lead_client.id')
                                  ->select('lead_client.*')
                                  ->whereIn('lead_client.agent_id',$id);

      if(!empty($statusarry)){
        $incent         =   $incent->whereIn('lead_status_history.status',$statusarry);
      }
       
      $incent           =   $incent->whereBetween('lead_status_history.date',[$from_date,$to_date])
                            ->distinct('lead_client.id')
                            ->get();
      $tot_net          =   0;
      $incentive        =   0; 
      $total_gross      =   0;
      $tot_net          =   0;

      foreach($incent as $row){  
        if((int)$row->incentive>0){
          $incentive+=$row->incentive;
        }                
      }
      return number_format((float)$incentive, 2, '.', '');
    }
  } 

  if(!function_exists('paid')){
    function paid($id,$from_date,$to_date){

      $statusarry =   ['Pay Received','Paid Out','13','14'];
      $incent     =   Leadclient::join('lead_status_history', 'lead_status_history.lead_id', '=', 'lead_client.id')
          ->select('*')
          ->whereIn('lead_client.agent_id',$id)
          ->whereIn('lead_status_history.status',$statusarry)
          ->whereBetween('lead_status_history.date',[$from_date,$to_date]) 
          ->distinct('lead_client.id') 
          ->get(); 
      $payment    =   0;
      foreach($incent as $val){
        if($val->payment!=''){
          $payment+=$val->payment;
        }
      }
      return $payment;
    }
  } 

if(!function_exists('info_chart')){
  function info_chart($id,$user_role){
    $from_month   =   '01';
    $to_month     =   date('m');
    $from_year    =   date('Y');
    $to_year      =   date('Y');
    $show         =   1;
    $result       =   true;
    $ids          =   [];
    if($user_role == ADMIN){
            
      $leadclients = User::where('users.create_by_user','=',$id)->where('user_role',AGENT)->get();

      if (count($leadclients)) {
        foreach($leadclients as $value){
          $ids[] = $value->id;
        }
      } else {
         $ids[] = $id;
      }   
    }else{
      $ids[]=$id;
    }
    $incentive = array();
    for($i = 0; $i < 12; $i++){
    
      $from_date            =   date("Y-m-d", strtotime( date( 'Y-m-01' )." -$i months"));
      $incentive_from_date  =   date('d M, Y',strtotime($from_date));
      $mo                   =   date('M',strtotime($from_date));
      $to_date              =   date("Y-m-t", strtotime( date( 'Y-m-01' )." -$i months"));
      $leads                =   leads($ids,$from_date,$to_date);
             
      if($user_role == ADMIN){
        $statusarry = ['Lease Confirmed','Sold','10','9'];
      }else{
        $statusarry = ['Lease Confirmed','Sold','10','9'];
      }

      $lease_confirmed      =   leaseconfirm($ids,$from_date,$to_date,$statusarry);
      $newleads             =   newlead($ids,$from_date,$to_date);
      $statusarry           =   array();
      if($user_role == ADMIN){
        $statusarry = ['Pay Received','13'];
      }
            
      $incent               =    incentive($ids,$from_date,$to_date,$statusarry);   
        
            if($user_role==ADMIN){
              $Residential_Gross=residential_gross($ids,$from_date,$to_date);
                $Residential_Gross=number_format($Residential_Gross, 2, '.', '');
            }
            else
            {
              $Residential_Gross=paid($ids,$from_date,$to_date);
              $Residential_Gross=number_format($Residential_Gross, 2, '.', '');
            }
            
             if($user_role==ADMIN)
             {
             $Gross_Sales= apartment_gross($ids,$from_date,$to_date); 
             $Gross_Sales=number_format($Gross_Sales, 2, '.', '');
             }
             else
             {
               $Gross_Sales=residential_gross($ids,$from_date,$to_date)+apartment_gross($ids,$from_date,$to_date); 
               $Gross_Sales=number_format($Gross_Sales, 2, '.', '');
             }



            //$Residential_Gross+=$paid_arr[2];

            $Revenue= $Gross_Sales+$Residential_Gross; 
            // $Residential_Gross=number_format($Residential_Gross, 2, '.', ',');
            // $Gross_Sales= number_format($Gross_Sales, 2, '.', ',');
            // $Revenue= number_format($Revenue, 2, '.', ',');
            // number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
        //            $query = DB::getQueryLog();
        // echo '<pre>'; print_r($query); echo '</pre>'; die();      
                           
           //  }
            
             $lead[$mo]=$leads;
             $newlead[$mo]=$newleads; //new leads according to created date 
             $incentive[$mo]=$incent;
             $lease[$mo]=$lease_confirmed;
             $sales[$mo]=$Gross_Sales;
             $Resi_Gross[$mo]=$Residential_Gross;
             $rev[$mo]=number_format((float)$Revenue, 2, '.', '');
             
           }



   //  print_r($lead); exit;
     $chartdata=array(
        'incentive'=>json_encode($incentive), // Insentive Spend
        'leads'=>json_encode($lead),  // Leased
        'newleads'=>json_encode($newlead), // new leads according to created date
        'lease_confirm'=>json_encode($lease), // Lease Confirmed
        'gross_sales'=>json_encode($sales), //Total Sales
        'Resi_Gross'=>json_encode($Resi_Gross), //Total Income
        'rev'=>json_encode($rev), //Invoice Sent
        'from_month'=>$from_month,
        'to_month'=>$to_month,
        'from_year'=>$from_year,
        'to_year'=>$to_year,
        'from_date'=>date("M,d,Y", strtotime( date( 'Y-m-01' )." -0 months")),
        'to_date'=>date("M,d,Y", strtotime( date( 'Y-m-01' )." -11 months")),
        'show'=>$show
 
     );

     return $chartdata;
  }

 } 

if (!function_exists('sendmail')) {
  function sendmail(array $data,array $otherdata,$pathToFile='',$imgarr = array(),$plain='') {
      //echo $plain; exit;
        
    try {
      
        Mail::send('mail', $data, function($message) use ($otherdata,$pathToFile,$imgarr,$plain) {

          $message->to($otherdata['to'])->subject($otherdata['subject']);
          $message->from($otherdata['from'],$otherdata['from_name']);
          $message->getSwiftMessage();
          $message->getHeaders()->addTextHeader('x-mailgun-native-send', true);
          
          $message->setCharset('utf-8');
          $message->setContentType('text/html','text/plain');
             
          $message->setBody($message,'text/plain');
          $message->addPart($plain, 'text/plain');
          
          if(!empty($otherdata['cc'])){
            $message->cc($otherdata['cc']);
          }
          
          if(!empty($otherdata['bcc'])){
            $message->bcc($otherdata['bcc']);
          }
          if($pathToFile != ''){
            $message->attach($pathToFile);   
          }

          if(!empty($imgarr)){
            foreach ($imgarr as $key => $value) {
              $message->attach($value);
            }
          }
        });

 
 
        if(count(Mail::failures()) > 0 ) {
        foreach(Mail::failures() as $email_address) {
          //echo " - $email_address <br />";
          return 0;
        }
      } else {
        return true;
      }
    } catch (\Exception $e) {
      throw $e;
    }
  }
}

if (!function_exists('setdbdateincome')) {
  function setdbdateincome($dateset) {
    if($dateset==''){
      return $dateset;
    }else{
      return date("Y-m-d", strtotime($dateset));
    }
  }
}

if (!function_exists('setdbdate')) {
  function setdbdate($dateset) {
    if($dateset==''){
      return $dateset;
    }else{
      return date("Y-m-d", strtotime($dateset));
    }
  }
}
if (!function_exists('getleadcount')) {
  function getleadcount($agent_id='',$statusarry) {
    $to_date=date("Y-m-d");
    $from_date="0000-00-00";
    //echo '<pre>'; print_r($statusarry); echo '</pre>'; die();
    if($agent_id !=''){

      return $getcou = sizeof(Leadclient::whereIn('curr_status',$statusarry)
            ->where('agent_id','=',$agent_id) 
            //->where('contact_nxt_date','<=',$to_date) 
           // ->where('contact_nxt_date','>=',$from_date) 
            ->get());
    }else{

     return 0;
    }
    
  }
}

if(!function_exists('forum_count')){
 function forum_count($help_id){
  return $count=sizeof(HelpForum::where('help_id','=',$help_id)->where('status',1)->get());
 }
}


if(!function_exists('get_users')){
  function get_users(){
    return $useraragent = User::where('user_role','!=',1)
                      //->where('assign_to_ar','=',$id)
                      ->where('status','=',1)->get();
         // if(session('aragentsearch') == ''){
         //   $firstuser =  $useraragent->first();            
         //   if((isset($firstuser->id)) && $firstuser->id != '')
         //   {
         //    Session::put('aragentsearch', $firstuser->id);
         //    $email_id=$firstuser->id;
         //   }
         // } 
       }  
}


if(!function_exists('getvalue')){
 
 function getvalue($table_name,$column,$where,$id){

    $get= DB::table($table_name)
              ->select($column)
              ->where($where,'=',$id)
              ->get();

          return $get;    

 }
}

if (!function_exists('getleadcountreport')) {
  function getleadcountreport($agent_id='',$statusarry, $from_date , $to_date) {
    if($agent_id !=''){

      return $getcou = sizeof(Leadclient::join('lead_status_history', 'lead_status_history.lead_id', '=', 'lead_client.id')
            ->select('lead_client.id','lead_status_history.status')
            ->whereIn('lead_status_history.status',$statusarry)
            ->where('lead_client.agent_id','=',$agent_id) 
            ->where('lead_status_history.date','>=',$from_date) 
            ->where('lead_status_history.date','<=',$to_date) 
            ->groupby('lead_client.id') 
            ->groupby('lead_status_history.status') 
            ->get());
    }else{

     return 0;
    }
    
  }
}

if (!function_exists('getleadcountreportpaid')) {
  function getleadcountreportpaid($agent_id='',$statusarry, $from_date , $to_date) {
    if($agent_id !=''){

      $getcoupaid = Leadclient::join('lead_status_history', 'lead_status_history.lead_id', '=', 'lead_client.id')
            ->select('lead_client.id','lead_status_history.status')
            ->whereIn('lead_status_history.status',$statusarry)
            ->where('lead_client.agent_id','=',$agent_id) 
            ->where('lead_status_history.date','>=',$from_date) 
            ->where('lead_status_history.date','<=',$to_date) 
            ->groupby('lead_client.id') 
            ->groupby('lead_status_history.status') 
            ->get();
        if(sizeof($getcoupaid) > 0){
            $tot_net=0;
            $total_gross=0;
            $incentive=0;
            foreach ($getcoupaid as $keypaid => $valuepaid) {
                      
                $rent_amount =$valuepaid->rent_amount;
                $commision   =$valuepaid->commision;
                $com_unit    =$valuepaid->commision_unit;
                $bonus       =$valuepaid->bonus;
                $inc         =$valuepaid->incentive;
                $leadcost    =$valuepaid->lead_cost;
                $invcostt    =$valuepaid->agent_invcost;
                       
                if (trim($commision)==""){
                    $commision=0;
                    }
                if (trim($bonus)==""){
                    $bonus=0;
                    }
                if ($com_unit=="1") {
                   
                    if ($commision!=0 || $commision!=0.00) {
                      $tot_com=((float) $rent_amount*((float) $commision/100));
                      $total=(float) $tot_com + (float) $bonus;    
                    }else{
                      $total=$bonus;
                    }
                }else{
                   
                    $tot_com=(float) $commision;
                    $total=(float) $commision+(float) $bonus;
                    
                }
                        
                    $total_cost =(float) $leadcost+(float) $invcostt;
                    $net =(float) $total-(float) $inc-(float) $total_cost;
                    $tot_net +=(float) $net;
                  
                    $total_gross+=(float) $total;
                    $incentive+=(float) $inc;
                    $total_gross=number_format((float)$total_gross, 2, '.', '');
                    $incentive=number_format((float)$incentive, 2, '.', '');
                    
                    $tot_net=number_format((float)$tot_net, 2, '.', '');
                       
                }
                    $paidamount="$$incentive~$$total_gross~$$tot_net";
            }else{
                  $paidamount="$0.00~$0.00~$0.00";
            }
               return $paidamount;    
                    
        }else{

         return 0;
        }
    
    }
}



if (!function_exists('showdateformate')) {
  function showdateformate($dateset) {
    if($dateset==''){
      return $dateset;
    }else{

     return date("m/d/Y", strtotime($dateset));
    }
    
  }
}


if (!function_exists('showdateformatepdf')) {
  function showdateformatepdf($dateset) {
    if($dateset==''){
      return $dateset;
    }else{

     return date("m/d/Y", strtotime($dateset));
    }
    
  }
}

if (!function_exists('serformatephone')) {
  function serformatephone($phoneno) {

    //$phoneno = '+1'.$phoneno;
     $phoneno = $phoneno;

      
    if(  preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $phoneno,  $matches ) )
    {
        $result = '('.$matches[1] . ')' .$matches[2] . '-' . $matches[3];
        return  $result;
    }
    else{

     return $phoneno;
    }
    
  }
}

if (!function_exists('setemaildata')) {
  function setemaildata($agentemail , $leaddetail ,$agentdetail) {
    
     $agentemail->email_signature = str_replace("[Client Name]",$leaddetail->fname.' '.$leaddetail->lname.'',$agentemail->email_signature);

        $agentemail->email_signature = str_replace("[Client Phone]",isset($leaddetail->phone1) ? serformatephone($leaddetail->phone1) : '',$agentemail->email_signature);

        $agentemail->email_signature = str_replace("[Agent Name]",isset($agentdetail->name) ? $agentdetail->name.'' : '' ,$agentemail->email_signature);

        $agentemail->email_signature = str_replace("[Agent Phone]",isset($agentdetail->phone) ? serformatephone($agentdetail->phone) : '' ,$agentemail->email_signature);

        $agentemail->email_signature = str_replace("[Agent Cell]",isset($agentdetail->agent_cell) ? serformatephone($agentdetail->agent_cell) : '' ,$agentemail->email_signature);

        $agentemail->email_signature = str_replace("[Signature]",$agentemail->email_signature,$agentemail->email_signature);

         $agentemail->email_signature = nl2br($agentemail->email_signature );

          //for subject

        $agentemail->email_sub = str_replace("[Client Name]",$leaddetail->fname.' '.$leaddetail->lname,$agentemail->email_sub);

        $agentemail->email_sub = str_replace("[Client ID]",$leaddetail->id,$agentemail->email_sub);

        $agentemail->email_sub = str_replace("[Client Phone]",isset($leaddetail->phone1) ? serformatephone($leaddetail->phone1) : '',$agentemail->email_sub);

        //$agentemail->email_sub = str_replace("[Agent Name]",isset($agentdetail->name) ? $agentdetail->name : '' ,$agentemail->email_sub);

        $agentemail->email_sub = str_replace("[Agent Phone]",isset($agentdetail->phone) ? serformatephone($agentdetail->phone) : '' ,$agentemail->email_sub);

        $agentemail->email_sub = str_replace("[Agent Cell]",isset($agentdetail->agent_cell) ? serformatephone($agentdetail->agent_cell):'' ,$agentemail->email_sub);

        $agentemail->email_sub = str_replace("[Signature]",$agentemail->email_signature,$agentemail->email_sub);

             if($leaddetail->transaction_type_id==1 || $leaddetail->prop_id!=0)
             {

                 $commission_unit = $leaddetail->commision_unit;
              $commission      = $leaddetail->commision;
              $bonus           = $leaddetail->bonus;
              $rent_amount     = $leaddetail->rent_amount;

              if($rent_amount==''){
                $rent_amount=0;
              }

              if($bonus==''){
                $bonus=0;
              }

              if($commission==''){
                $commission=0;
              }
             

             if ($commission_unit == '1') {

                 if ($commission > 0) {

                      $tot_com = (float) $rent_amount * ((float) $commission/100);
                     $invoiced_total = (float) $tot_com + (float) $bonus;                                               
                 } else {

                     $invoiced_total = (float) $bonus;

                 }
             } else {

                 $invoiced_total = (float) $commission + (float) $bonus;

             }

           }elseif($leaddetail->transaction_type_id==2 || $leaddetail->transaction_type_id==3 || $leaddetail->transaction_type_id==0){
             
             if($leaddetail->sold_amt==''){
              $leaddetail->sold_amt=0;
             }

             if($leaddetail->house_comm==''){
               $leaddetail->house_comm=0;
             }

             if($leaddetail->house_bonus==''){
               $leaddetail->house_bonus=0;
             }
            
             if ($leaddetail->house_comm > 0) {

                      $tot_com = (float) $leaddetail->sold_amt * ((float) $leaddetail->house_comm/100);
                     $invoiced_total = (float) $tot_com+(float) $leaddetail->house_bonus;                                               
                 } else {

                     $invoiced_total = (float) $leaddetail->house_bonus;

                 }

           }else{

             $invoiced_total=0;
           }

         $agentemail->email_body = str_replace("[Invoice No]",$leaddetail->id,$agentemail->email_body);
         
         $agentemail->email_body = str_replace("[Invoice Amount]",$invoiced_total,$agentemail->email_body);

        
        $agentemail->email_body = str_replace("[Client Name]",$leaddetail->fname.' '.$leaddetail->lname,$agentemail->email_body);

         $agentemail->email_body = str_replace("[Client ID]",$leaddetail->id,$agentemail->email_body);

        $agentemail->email_body = str_replace("[Client Phone]",isset($leaddetail->phone1) ? serformatephone($leaddetail->phone1) : '',$agentemail->email_body);

        $agentemail->email_body = str_replace("[Agent Name]",isset($agentdetail->name) ? $agentdetail->name : '' ,$agentemail->email_body);

        $agentemail->email_body = str_replace("[Agent Phone]",isset($agentdetail->phone) ? serformatephone($agentdetail->phone) : '' ,$agentemail->email_body);

        $agentemail->email_body = str_replace("[Agent Cell]",isset($agentdetail->agent_cell) ? serformatephone($agentdetail->agent_cell) : '' ,$agentemail->email_body);

        $agentemail->email_body = str_replace("[Signature]",$agentemail->email_signature,$agentemail->email_body);

        $sign_img = (isset($agentdetail->profile_img) && $agentdetail->profile_img) ? '<img id="preview_img" class="img-responsive" style="height:150px" src="'.getUploadedProfileImgPath()."/".$agentdetail->id."/".$agentdetail->profile_img.'" />' : '';

        $agentemail->email_body = str_replace("[Signature Image]",$sign_img,$agentemail->email_body);

        return $agentemail;
    
  }

  // Function to set Admin area Header Company color 
  if (!function_exists('get_company_color')) {
      function get_company_color($companyId) 
      {
        return $color=Company::where('id',$companyId)->pluck('mgmt_company_color')->first();
      }
  }
  
  // code updated by Randhir  -------------------------------
  
if (!function_exists('lead_calculate')) {
    function lead_calculate($id,$invoiced_total='') 
        {
            $broker_cost=0;
            $leadclient     = Leadclient::leftJoin('property', 'property.id', 'lead_client.prop_id')
                   ->select('prop_state', 'lead_client.*')
                    ->where('lead_client.id', $id)
                    ->first();
                                        
                   // echo "<pre>";print_r($leadclient); exit;
                                        
            $agentleaddetail =  User::find($leadclient->agent_id);
                                        
            $agent_status       =   $agentleaddetail->user_role;
            
            //Transaction calculation code updated by swapnil
            // $unit               =   $agentleaddetail->unit;
            // $agent_split_hous   =   (float) $agentleaddetail->broker_cost;
            // $agent_split        =   (float) $agentleaddetail->broker_cost;
            $unit                  = transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'unit');            
            $agent_split_hous      = (float) transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'broker_cost');            
            $agent_split           =   (float) transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'broker_cost');
           // echo $agent_split; exit;
            $curr_status_cost = $leadclient->curr_status_cost ? (float) $leadclient->curr_status_cost : 0;
        
            $statusarrychk      =   ['Pay Received', 'Paid Out','13','14'];
            
             $agent_invoice_cost =0;
             
            if(in_array($leadclient->curr_status, $statusarrychk) && $leadclient->inv_date < '2021-12-01'){
                $agent_invoice_cost =   (float) $leadclient->invoicing_cost;
            }else{
                //$agent_invoice_cost =  (float) $agentleaddetail->invoicing_cost;
                
                if($leadclient->transaction_type_id == 1 || $leadclient->transaction_type_id == 2 ||$leadclient->transaction_type_id == 3 || $leadclient->transaction_type_id == 7){
                    // $agent_invoice_cost = $agent_invoice_cost+(float) $agentleaddetail->invoicing_cost;
                  $agent_invoice_cost = $agent_invoice_cost+(float) transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'invoicing_cost');
                }
            }
            
            
             
            // if(in_array($leadclient->curr_status, $statusarrychk)){
            //     $agent_invoice_cost =   (float) $leadclient->invoicing_cost;
            // }else{
            //     $agent_invoice_cost =  (float) $agentleaddetail->invoicing_cost;
            // }
            
            
           
            
            // if($leadclient->transaction_type_id == 1 || $leadclient->transaction_type_id == 2 ||$leadclient->transaction_type_id == 3){
            //     $agent_invoice_cost = $agent_invoice_cost+(float) $agentleaddetail->invoicing_cost;
            // }
            
             
            
            $incentive          =   (float) (!empty($leadclient->incentive)?$leadclient->incentive:$leadclient['incentive_lease']);
            $sold_amt           =   $leadclient->sold_amt ? (float) $leadclient->sold_amt : $leadclient->rent_amount;;
            $house_comm         =   $leadclient->house_comm ? (float) $leadclient->house_comm : $leadclient->commision;
            $house_bonus        =   $leadclient->house_bonus ? (float) $leadclient->house_bonus : 0;
    
            if ($leadclient->source_id != 0 || $leadclient->source_id != '' || $leadclient->source_id != NULL){
    
                $agentsourcedetail = User::find($leadclient->source_id);
    
                if ($agentsourcedetail->manage_distributor == 1){
                    $agent_status = 5;
                }
            }
         
            $lead = Distributorleadmarket::find($leadclient->lead_id_orig);
            
            
            $lead_cost          =   0;
            $agent_paid         =   0;
            $house_cost         =   0;
    
            //1. Total Commission = sold_amt*(house_comm/100)+house_bonus
            if ($leadclient->sold_amt > 0){
                $totalcommission = (float) $sold_amt * ((float) $house_comm / 100) + (float) $house_bonus;
            }
            
            ///---------------------------------------------------------///
            
             
            
        if ($agent_status == 5){

            if (!empty($lead)){

                $dis_split      = (float) $lead->lead_cost;
                $dis_split_unit = $lead->unit;
            }else{

                $dis_split      = 0;
               // $dis_split_unit = $agentleaddetail->unit;
               $dis_split_unit = transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'unit');
            }
            
        //echo "dis_split ".$dis_split." dis_split_unit ".$dis_split_unit; exit;
        $leadclient->payment = (!empty($leadclient->payment)?$leadclient->payment:$invoiced_total);
       
        
        $broker_cost =0;
            if ((float) $leadclient->payment != 0){
            
                if ($dis_split_unit == 0){
                    
                    if($leadclient->transaction_type_id==1 || $leadclient->transaction_type_id == 7){
                    $commision = $leadclient->commision;
                    }else{
                        $commision=$leadclient->house_comm;
                    }
                   
                    if($agent_invoice_cost){
                        $payment =   (float) ($leadclient->payment-$agent_invoice_cost);
                    }else{
                        $payment =   (float) ($leadclient->payment);
                    }
                    
                    if (!empty($lead)){
                        if(!empty($lead->lead_cost)){
                            $broker_cost = ($payment*$lead->lead_cost/100);
                        }else{
                            $broker_cost = 0;
                        }
                        
                    }else{
                      $broker_amount = transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'broker_cost');
                        if(!empty($broker_amount)){
                            $broker_cost = ($payment*$broker_amount/100);
                        }else{
                            $broker_cost = 0;
                        }
                    }
                    
                    if (!empty($lead)){
                        $broker_cost = 0;
                    }
                    
                    $dis_split              = (float) $dis_split / 100;
                    $leadclient->lead_cost  = ($payment) * (float) $dis_split;

                    $lead_cost              = ($payment) * (float) $dis_split;
                    //$lead_cost              = ($payment - (float) $agent_invoice_cost) * (float) $dis_split;

                    $leadclient->agent_paid = $payment - (float) $agent_invoice_cost - (float) $incentive - (float) $leadclient->lead_cost;

                    //$agent_paid             = $payment - (float) $agent_invoice_cost - (float) $incentive - (float) $leadclient->lead_cost-$broker_cost;
                    $agent_paid             = $payment - (float) $incentive - (float) $leadclient->lead_cost-$broker_cost;
                }else{
                    if($agent_invoice_cost){
                        $payment =   (float) ($leadclient->payment-$agent_invoice_cost);
                    }else{
                        $payment =   (float) ($leadclient->payment);
                    }
                    
                    
                    $broker_amount = transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'broker_cost');
                    // if(!empty($agentleaddetail->broker_cost)){
                    //     $broker_cost = $agentleaddetail->broker_cost;
                    // }else{
                    //     //$broker_cost = 0;
                    // }
                    if(!empty($broker_amount)){
                        $broker_cost = $broker_amount;
                    }else{
                        //$broker_cost = 0;
                    }
                    
                    if (!empty($lead)){
                        $broker_cost = 0;
                    }

                    $lead_cost                  = $dis_split;
                    $leadclient->lead_cost      = (float) $dis_split;
                    $leadclient->agent_paid     = $payment - (float) $agent_invoice_cost - (float) $incentive - (float) $leadclient->lead_cost;
                    $agent_paid                 = $payment - (float) $incentive - (float) $leadclient->lead_cost-$broker_cost;
                }  
            }
 //echo "invoiced_total ".$payment."  agent_invoice_cost - ".$agent_invoice_cost." incentive - ".$incentive." leadclient_ead_cost - ".$leadclient->lead_cost." broker_cost ".$broker_cost; exit;  
                if ((float) $leadclient->sold_amt != 0){
    
                    if ($dis_split_unit == 0){
    
                        $dis_split  = (float) $dis_split / 100;
                        $house_cost = (float) $totalcommission * (float) $dis_split;
                    }else{
                        $house_cost = (float) $dis_split;
                    }
                }
            }else{
                
                //echo 'agent_status '.$agent_status; exit;
                 $leadclient->payment = (!empty($leadclient->payment)?$leadclient->payment:$invoiced_total);
                if ((float) $leadclient->payment != 0){
                    
                    if($agent_invoice_cost){
                        $payment =   (float) ($leadclient->payment-$agent_invoice_cost);
                    }else{
                        $payment =   (float) ($leadclient->payment);
                    }
                    
                    
                    if (!empty($lead)){
                        if(!empty($lead->lead_cost)){
                            $broker_cost = ($payment*$lead->lead_cost/100);
                        }else{
                            $broker_cost = 0;
                        }
                        
                    }else{
                      $broker_amount = transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'broker_cost');

                        // if(!empty($agentleaddetail->broker_cost)){
                        //     $broker_cost = ($payment*$agentleaddetail->broker_cost/100);
                        // }else{
                        //     $broker_cost = 0;
                        // }

                      if(!empty($broker_amount)){
                            $broker_cost = ($payment*$broker_amount/100);
                        }else{
                            $broker_cost = 0;
                        }
                    }
                    
                    if (!empty($lead)){
                        $broker_cost = 0;
                    }
                    
    
                    if ($unit == 0){
                        
                        if (empty($agent_split_hous)){
                            $agent_split_hous = 0;
                        }
    
                        $agent_split    = (float) $agent_split_hous / 100;
                       // $lead_cost      = ((float) $leadclient->payment - (float) $agent_invoice_cost) * (float) $agent_split;
                        //$agent_paid     = (float) $leadclient->payment - (float) $agent_invoice_cost - (float) $incentive - (float) $lead_cost;
                        $lead_cost      = ((float) $payment ) * (float) $agent_split;
                        $agent_paid     = (float) $payment - (float) $incentive - (float) $lead_cost;
                        //echo " agent_paid - ".$agent_paid." lead_cost ".$lead_cost." payment ".$payment." incentive ".$incentive ; exit;
                    }else{
                    
                        $lead_cost  = $agent_split;
                        $agent_paid = (float) $payment - (float) $incentive - (float) $lead_cost;
                    }
                    
                    
                }
                
                if ($leadclient->sold_amt != 0){
    
                    if ($unit == 0){
                        $agent_split_hous   = (float) $agent_split_hous / 100;
                        $house_cost         = (float) $totalcommission * (float) $agent_split_hous;
                    }else{
                        $house_cost         = (float) $agent_split_hous;
                    }
                }
            }
            
          
            
            if ($leadclient->transaction_type_id == 1 || $leadclient->prop_id != 0 ){

                $commission_unit    = $leadclient->commision_unit;
                $commission         = (float) $leadclient->commision;
                $bonus              = (float) $leadclient->bonus;
                $rent_amount        = (float) $leadclient->rent_amount;
    
                if ($rent_amount == ''){
                    $rent_amount = 0;
                }
    
                if ($bonus == ''){
                    $bonus = 0;
                }
    
                if ($commission == ''){
                    $commission = 0;
                }
    
                if ($commission_unit == '1'){
    
                    if ($commission > 0){
    
                        $commission     = (float) $commission;
                        $tot_com        = (float) $rent_amount * ((float) $commission / 100);
                        $invoiced_total = (float) $tot_com + (float) $bonus;
                    }else{
                        $invoiced_total = (float) $bonus;
                    }
                }else{
                    $invoiced_total = (float) $commission + (float) $bonus;
                }
            
          
           
            }elseif ($leadclient->transaction_type_id == 2 || $leadclient->transaction_type_id == 3 || $leadclient->transaction_type_id == 0){

                if ($leadclient->sold_amt == ''){
                    $leadclient->sold_amt = 0;
                }
    
                if ($leadclient->house_comm == ''){
                    $leadclient->house_comm = 0;
                }
    
                if ($leadclient->house_bonus == ''){
                    $leadclient->house_bonus = 0;
                }

                if ($leadclient->house_comm > 0){
                    $tot_com        = (float) $leadclient->sold_amt * ((float) $leadclient->house_comm / 100);
                    $invoiced_total = (float) $tot_com + (float) $leadclient->house_bonus;
                }else{
                    $invoiced_total = (float) $leadclient->house_bonus;
                }
//echo "invoiced_total - ".$invoiced_total." house_cost - ".$house_cost." lead_cost - ".$lead_cost." agent_paid - ".$agent_paid; exit;
             }elseif ($leadclient->transaction_type_id == 5 || $leadclient->transaction_type_id == 6){

                if ($leadclient->sold_amt == ''){
                    $leadclient->sold_amt = 0;
                }
    
                if ($leadclient->house_comm == ''){
                    $leadclient->house_comm = 0;
                }
    
                if ($leadclient->house_bonus == ''){
                    $leadclient->house_bonus = 0;
                }

                if ($leadclient->house_comm > 0){
                    $tot_com        = (float) $leadclient->sold_amt * ((float) $leadclient->house_comm / 100);
                    $invoiced_total = (float) $tot_com + (float) $leadclient->house_bonus;;
                }else{
                    $invoiced_total = (float) $leadclient->house_bonus;
                }
            }elseif($leadclient->transaction_type_id == 7){
              $invoiced_total = $leadclient->invoiced_total;
            }else{
                $invoiced_total = 0;
            }
       // echo "invoiced_total ".$payment."  agent_invoice_cost - ".$agent_invoice_cost." incentive - ".$incentive." leadclient_ead_cost - ".$leadclient->lead_cost." broker_cost ".$broker_cost; exit;        
            $invoice_cost = 0;
            $broker_splite = 0;
            if ($leadclient->transaction_type_id == 5 || $leadclient->transaction_type_id == 6){

                if ($leadclient->transaction_type_id == 5){
                    //$tot_trans_amt = (float) $leadclient->sold_amt * (float) $leadclient->lease_term;
                    $tot_trans_amt = $leadclient->rent_amount;
                }else{
                    $tot_trans_amt = $leadclient->sold_amt;
                }
                
             // echo "<pre>";print_r($leadclient); exit;
             //echo "agent paid ".$tot_trans_amt; exit;
             
                if($tot_trans_amt < 100000){
                    // $invoice_cost = $agentleaddetail->commercial_tier1;
                    $invoice_cost = transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'commercial_tier1');
                }else if($tot_trans_amt >= 100000 && $tot_trans_amt < 1000000){
                    // $invoice_cost = $agentleaddetail->commercial_tier2;
                  $invoice_cost = transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'commercial_tier2');
                }else{
                    // $invoice_cost = $agentleaddetail->commercial_tier3;
                  $invoice_cost = transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'commercial_tier3');
                }
            
                if (!empty($lead)){
                    $agentleaddetail->broker_cost = 0;
                }
                // if (empty($agentleaddetail->broker_cost)){
                    
                //     if (empty($lead)){
                //         $lead_cost = 0;
                //     }
    
                //     $agent_paid = (float) $leadclient->payment - $invoice_cost - (float) $agentleaddetail->broker_cost-$lead_cost;
                    
                // }else{
                    
                //     $broker_splite = ((float) $leadclient->payment - (float) $invoice_cost) * (($agentleaddetail->broker_cost) / 100);
                //     $agent_paid = ((float) $leadclient->payment - (float) $invoice_cost) * ((100-(float) $agentleaddetail->broker_cost) / 100);
                // }
                $broker_cost_value = transaction_calculation($leadclient->transaction_type_id,$agentleaddetail,'broker_cost');
                if (empty($broker_cost_value)){
                    
                    if (empty($lead)){
                        $lead_cost = 0;
                    }
    
                    $agent_paid = (float) $leadclient->payment - $invoice_cost - (float) $broker_cost_value-$lead_cost;
                    
                }else{
                    
                    $broker_splite = ((float) $leadclient->payment - (float) $invoice_cost) * (($broker_cost_value) / 100);
                    $agent_paid = ((float) $leadclient->payment - (float) $invoice_cost) * ((100-(float) $broker_cost_value) / 100);
                }
            
            }
            
            $commision = $leadclient->house_comm;
            $rent= $leadclient->rent_amount;
            if(!empty($commision)){
                $inv_amt = (float) $rent * ((float) $commision / 100);
            }else{
               $inv_amt = '';
            }
            $invoiced_total = (!empty($invoiced_total)?$invoiced_total:$inv_amt);
    
        if (empty($lead)){
            $lead_cost=0;
        }
        //echo "broker splite ".$broker_splite; exit;
        
       // $agent_split
          
        $leadcalculatdata['invoiced_total'] = $invoiced_total;
        $leadcalculatdata['house_cost']     = (float) $house_cost;
        $leadcalculatdata['lead_cost']      = (float) $lead_cost;
        $leadcalculatdata['agent_paid']     = (float) ($agent_paid-$curr_status_cost);
        $leadcalculatdata['invoiced_fee'] = (!empty($invoiced_total)?$invoiced_total:$agent_invoice_cost);
        $leadcalculatdata['commercial_transaction'] = $invoice_cost;
        //$leadcalculatdata['broker_splite'] = (!empty($broker_splite)?$broker_splite:$broker_cost);
        if($unit==1){
            $leadcalculatdata['broker_splite'] = (!empty($broker_splite)?$broker_splite:$agent_split);
        }else{
           $leadcalculatdata['broker_splite'] = (!empty($broker_splite)?$broker_splite:$broker_cost); 
        }
         //
         
        //$leadcalculatdata['incentive'] = $incentive;
        $leadcalculatdata['incentive'] = (float) (!empty($leadclient['incentive_lease'])?$leadclient['incentive_lease'] : $leadclient->incentive);
        $leadcalculatdata['agent_invoice_cost'] = $agent_invoice_cost;
        $leadcalculatdata['transaction_coordination_lease_verify'] = $curr_status_cost;
        $leadcalculatdata['unit'] = $unit;
        
        //$leadcalculatdata['lease_verify'] = $incentive;
        
        //echo "<pre>"; print_r($leadcalculatdata); exit;
        return $leadcalculatdata; exit;
        }
    }
}

 if (! function_exists('checkDuplicateValue')) {
    function checkDuplicateValue($table,$condition)
    {
        $results= DB::select("select * from $table where $condition");
        $count = count($results);
        return $count;
       // return "select * from $table where $condition";
    }
}

if (!function_exists('convertDateFormat')) {
    function convertDateFormat($date,$format)
    {
        $Newdate = date_create($date);
        //return date('d-M-Y H:i:s',strtotime(date_format($Newdate,$format)));
        return date_format($Newdate,$format);
    }
}


if (!function_exists('count_flag')) {
    function count_flag()
    {
        $user_role          = Auth::user()->user_role;
        $user               = Auth::user()->id;
        
        //return $user; exit;
        
        if($user_role=='1' || $user_role=='2'){
            // $condition = "flag_data.is_deleted='0' and flag_data.sendto='$user' ";
            $condition = "flag_data.is_deleted='0' and flag_data.sendto='$user' and flag_data.status='1'";
        }else{
            // $condition = "flag_data.is_deleted='0' and flag_data.sendto='$user' ";
            $condition = "flag_data.is_deleted='0' and flag_data.sendto='$user' and flag_data.status='1' ";
        }
        
       // return $count=sizeof(HelpForum::where('help_id','=',$help_id)->where('status',1)->get());
    //echo "select count(*) as total_row,flag_data.*,lead_client.fname,lead_client.lname,lead_client.email,CONCAT(users.name,' ',users.last_name)as agent_name,users.email as agent_email from flag_data INNER JOIN lead_client ON flag_data.lead_id=lead_client.id INNER JOIN users ON flag_data.created_by=users.id WHERE $condition"; exit;
    $resultscount= DB::select("select count(*) as total_row,flag_data.*,lead_client.fname,lead_client.lname,lead_client.email,CONCAT(users.name,' ',users.last_name)as agent_name,users.email as agent_email from flag_data INNER JOIN lead_client ON flag_data.lead_id=lead_client.id INNER JOIN users ON flag_data.created_by=users.id WHERE $condition");
   
    return ($resultscount[0]->total_row); exit;
    
    //return (count($resultscount));
    }
}


if (!function_exists('count_property_open_status')) {
    function count_property_open_status($id)
    {
        $user_role          = (!empty(Auth::user()->user_role)?Auth::user()->user_role:'');
        
        $user               = (!empty(Auth::user()->id)?Auth::user()->id:'');
        
        $company = (!empty(Auth::user()->company)?Auth::user()->company:'');
        
       // $resultscount= DB::select("select * from lead_client WHERE prop_id ='$id' and (curr_status='Invoiced' or curr_status='12') and source_id='$user' ");
        
        
       // $resultscount= DB::select("select lead_client.*,`users`.`name`, `users`.`last_name`,users.company,lead_client.prop_id from `lead_client` inner join `users` on `users`.`id` = `lead_client`.`agent_id`  where lead_client.agent_id in(select id from users where create_by_user='$user') and lead_client.curr_status IN('Invoiced','12') and users.company='$company' and lead_client.prop_id='$id' GROUP BY lead_client.id order by lead_client.id DESC");
        $resultscount= DB::select("select lead_client.*,`users`.`name`, `users`.`last_name`,users.company,lead_client.prop_id from `lead_client` inner join `users` on `users`.`id` = `lead_client`.`agent_id`  where lead_client.curr_status IN('Invoiced','12') and users.company='$company' and lead_client.prop_id='$id' GROUP BY lead_client.id order by lead_client.id DESC");
        

        $data['count'] = (count($resultscount));
        $data['ids'] = implode(',',array_column($resultscount,'id'));
        return $data;
    }
}
    
if (!function_exists('login_user_count_flag')) {
    function login_user_count_flag()
    {
        $user_role          = Auth::user()->user_role;
        $user               = Auth::user()->id;
        
        if($user_role=='1' || $user_role=='2'){
            $condition = "flag_data.is_deleted='0' and flag_data.sendto='$user' and flag_data.status = '1' ";
        }else{
            $condition = "flag_data.is_deleted='0' and flag_data.sendto='$user' and flag_data.status = '1' ";
        }
        
       // return $count=sizeof(HelpForum::where('help_id','=',$help_id)->where('status',1)->get());
       //echo "select flag_data.*,lead_client.fname,lead_client.lname,lead_client.email,CONCAT(users.name,' ',users.last_name)as agent_name,users.email as agent_email from flag_data INNER JOIN lead_client ON flag_data.lead_id=lead_client.id INNER JOIN users ON flag_data.created_by=users.id WHERE $condition"; exit;
        $resultscount= DB::select("select flag_data.*,lead_client.fname,lead_client.lname,lead_client.email,CONCAT(users.name,' ',users.last_name)as agent_name,users.email as agent_email from flag_data INNER JOIN lead_client ON flag_data.lead_id=lead_client.id INNER JOIN users ON flag_data.created_by=users.id WHERE $condition");
        
        return (count($resultscount));
    }
}


if (!function_exists('user_security_question')) {
    function user_security_question($email)
    {
        //echo "select * from users where email='$email'"; exit;
        $user_id= DB::select("select * from users where email='$email'")[0]->id;
        
        $user_security_questions = DB::select("select *,security_question.question as questions,security_question.id as question_id from user_security_question INNER join security_question ON security_question.id=user_security_question.question where user_id='$user_id' ORDER BY RAND() LIMIT 2"); 
        
        return ($user_security_questions);
    }
}

if ( !function_exists('mysql_escape'))
{
    function mysql_escape($inp)
    { 
        if(is_array($inp)) return array_map(__METHOD__, $inp);

        if(!empty($inp) && is_string($inp)) { 
            return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp); 
        } 

        return $inp; 
    }
}



if (!function_exists('getLatLong')) {
        function getLatLong($address){
            if(!empty($address)){
                //Formatted address
                $formattedAddr = str_replace(' ','+',$address);
                $geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=true_or_false&key=AIzaSyAg9Dr0s2VU6xx3WFgDEIrR3Wby_PcpFnw');

                $output = json_decode($geocodeFromAddr);
                return $output; return false;
                $data['latitude']  = $output->results[0]->geometry->location->lat; 
                $data['longitude'] = $output->results[0]->geometry->location->lng;
                
                if(!empty($data)){
                    return $data;
                }else{
                    return false;
                }
            }else{
                return false;   
            }
        }
    }
    
    
//     $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&sensor=false';
 
// $geocode = file_get_contents($url);
// $results = json_decode($geocode, true);
 
// if ($results['status'] == 'OK') {
// $lat = $results['results'][0]['geometry']['location']['lat'];
// $long = $results['results'][0]['geometry']['location']['lng'];
// }
 
// echo " Lat:" . $lat . " ";
// echo "Lat:" . $long . " ";
// if ($results['status'] == 'OK') {
// if (count($results['results']) > 1) {
//   echo "Multiple address found";
// }
// if (count($results['results']) == 1) {
// if (isset($results['results'][0]['partial_match'])) {
// if ($results['results'][0]['partial_match']) {
// echo "This is a partially right address";
// }
// } else {
// echo "Valid address";
// }
// }
// } else {
// echo "Invalid address";
// }


if (!function_exists('income_details')) {
    function income_details($type,$id)
    {
        
        $user_role          = Auth::user()->user_role;
        $user               = Auth::user()->id;
        
        
        $data=array();
        $sql="select * from admin_income";
        $sql1="select * from agent_income";
        $sql2="select * from ar_income";
        
        if($user_role==1 && $type =='agent'){
            $sql1.=" where agent_id='$id' limit 1";
            $agent_income = DB::select($sql1);
            
            $data['agent_income'] = !empty($agent_income)?$agent_income[0]:'';
        }else{
             $data['agent_income'] ='';
        }
        
        if($user_role==1 && $type =='ar'){
            $sql2.=" where user_id='$user' and agent_id='$id' limit 1";
            $ar_income  = DB::select($sql2);
            
            $data['ar_income'] = !empty($ar_income)?$ar_income[0]:'';
        }else{
             $data['ar_income'] ='';
        }
        
        
        
        if($user_role==2 && $type =='agent'){
            $sql1.=" where agent_id='$id' limit 1";
            $agent_income = DB::select($sql1);
            
            $data['agent_income'] = !empty($agent_income)?$agent_income[0]:'';
        }else{
             $data['agent_income'] ='';
        }
        
        
        if($user_role==2 && $type =='ar'){
            $sql2.=" where user_id='$user' and agent_id='$id' limit 1";
            $ar_income  = DB::select($sql2);
            
            $data['ar_income'] = !empty($ar_income)?$ar_income[0]:'';
        }else{
             $data['ar_income'] ='';
        }
        
        if($user_role==2 && $type =='admin'){
            $sql.=" where user_id='$user' limit 1";
            $admin_income  = DB::select($sql);
            
            $data['admin_income'] = !empty($admin_income)?$admin_income[0]:'';
        }else{
             $data['admin_income'] ='';
        }
        
        
        if($user_role=='3' && $type =='agent'){
            $sql1.=" where agent_id='$id' limit 1";
            $agent_income = DB::select($sql1);
            
            $data['agent_income'] = !empty($agent_income)?$agent_income[0]:'';
        }else{
             $data['agent_income'] ='';
        }
        
        //print_r($data); exit;
        return ($data);
    }
}


if (!function_exists('admin_agent_income')) {
  function admin_agent_income(){

    $id               =   Auth::user()->id; 
    $user_role        =   Auth::user()->user_role;
    
    $role_for         =   "ADMIN";
    $items            =   $request->items ?? 25;
    
    $sort           = isset($request->sort) ? $request->sort : 'id';
    $direction      = isset($request->direction) ? $request->direction : 'DESC';

    $leadclients      = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                    ->join('lead_status_history','lead_status_history.lead_id','lead_client.id')
                                    ->select('lead_client.*', 'users.name', 'users.last_name','lead_status_history.date as paid_date');

   
    $useraragent              =   '';
    $data['show_agent_list']  =    0;

    if($user_role == SUPERADMIN){
      
      $useraragent = User::where('user_role','=',ADMIN)
                    ->where('status','=',1)
                    ->orderBy('name','ASC')
                    ->get();
      $data['show_agent_list'] = 1;
    }elseif($user_role == ADMIN){
  
      $useraragent = User::where('user_role','=',ADMIN)
                            ->where('id','=',$id)
                            ->where('status','=',1)
                            ->orderBy('name','ASC')
                            ->get();
      Session::put('aragentsearch', $id);               
    }else{

      $useraragent = User::where('id','=',$id)
                          ->where('status','=',1)
                          ->orderBy('name','ASC')
                          ->get();
    }
      
    $firstuser =  $useraragent->first(); 

    if(session('aragentsearch') == ''){

      $firstuser =  $useraragent->first(); 
      if(!empty($firstuser)){   

        if($firstuser->id != ''){
          Session::put('aragentsearch', $firstuser->id);
        }
      }else{
        Session::put('aragentsearch',0);
      }
    }
         
    //
    $agent_id           =   session('aragentsearch');
    $arUser             =   User::select('id')->where('create_by_user','=',$agent_id)->get();
    
    $leadclients        =   $leadclients->whereIN('agent_id',$arUser);
   
    $search_start_date  =   '';
    $search_end_date    =   '';
    $client_name        =   '';
    $client_id          =   '';
   // $searchform         =   $request->input('search_agent'); 

  
       $statusarry         = ['Sold','Invoiced','Pay Received','MIC','Paid Out','9','11','12','13','14'];
       $leadclients = $leadclients->whereIn('lead_client.curr_status',$statusarry);
     

    
    $statusarry         = ['Sold','Invoiced','Pay Received','MIC','Paid Out','9','11','12','13','14'];
    
    
     $leadclientsall    =  $leadclients->where('curr_status','!=','Write Off')
                                ->groupBy('lead_client.id')
                                ->get(); 
                         //echo "<pre>"; print_r(count($leadclientsall)); exit; 
                                  

                                      
                                      
         
   


    //echo "<pre>";print_r($leadclientsall); exit;
    // $tot_net       = 0;
    // $tot_invoiced  = 0;
    // $tot_paid      = 0;
    // $outsatnginamt = 0;
   
    // Session::put('role_for',$role_for);
    
   
    // $data['leadclients']        = $leadclients;
    
        $sum =0;
    foreach($leadclientsall as $leadclientall){
        $value = lead_calculate($leadclientall->id)['agent_paid'];
        $sum+= $value;
       
    }
    return number_format($sum,2);
    //echo "<pre>"; print_r(($sum)); exit;
    
  }
}


if (!function_exists('number_format_short')) {
   function number_format_short( $n, $precision = 1 ) {
       echo $n; exit;
	if ($n < 900) {
		// 0 - 900
		$n_format = number_format($n, $precision);
		$suffix = '';
	} else if ($n < 900000) {
		// 0.9k-850k
		$n_format = number_format($n / 1000, $precision);
		$suffix = 'K';
	} else if ($n < 900000000) {
		// 0.9m-850m
		$n_format = number_format($n / 1000000, $precision);
		$suffix = 'M';
	} else if ($n < 900000000000) {
		// 0.9b-850b
		$n_format = number_format($n / 1000000000, $precision);
		$suffix = 'B';
	} else {
		// 0.9t+
		$n_format = number_format($n / 1000000000000, $precision);
		$suffix = 'T';
	}

  // Remove unecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1"
  // Intentionally does not affect partials, eg "1.50" -> "1.50"
	if ( $precision > 0 ) {
		$dotzero = '.' . str_repeat( '0', $precision );
		$n_format = str_replace( $dotzero, '', $n_format );
	}

	return $n_format . $suffix;
}

}


if (!function_exists('count_security_question')) {
    function count_security_question()
    {
        $user_role          = Auth::user()->user_role;
        $user               = Auth::user()->id;
      
        $condition = "user_id='$user' and answer!=''";
        
        $resultscount= DB::select("select count(*) as total_row from user_security_question WHERE $condition");
        return ($resultscount[0]->total_row); exit;
    }
}

if (!function_exists('array_sort_by_column')) {
    function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
        $sort_col = array();
        $i=0;
        foreach ($arr as $key => $row) {
            $sort_col[$key] = $row[$col];
            $i++;
        }
    
        array_multisort($sort_col, $dir, $arr);
    }
}


if (!function_exists('security_questions')) {
    function security_questions()
    {
       $id           =   Auth::user()->id;
       $user_security_questions = DB::select("select *,security_question.question as questions from user_security_question INNER join security_question ON security_question.id=user_security_question.question where user_id='$id' ORDER BY RAND()");
        
        $limit =5;
        $condtion = '';
        if(count($user_security_questions)>0){
            
            $user_security_question = (json_decode(json_encode($user_security_questions), true)); 
            $idd = implode(',',array_column($user_security_question,'id'));
           
            $limit = $limit-count($user_security_question);
            $condtion = "where id NOT IN($idd)";
        }
        $security_questions = DB::select("select * from security_question ".$condtion." ORDER BY RAND() LIMIT $limit");
                
            $data['questions']     =  $security_questions;
            $data['user_questions'] =  $user_security_questions;
            
        return ($data); exit;
    
    }
}


if (!function_exists('lead_sort')) {
    function lead_sort(&$arr, $col, $dir = SORT_ASC) {
        $sort_col = array();
        $i=0;
        foreach ($arr as $key => $row) {
            $sort_col[$key] = $row[$col];
            $i++;
        }
    
        array_multisort($sort_col, $dir, $arr);
    }
}


if (!function_exists('deduction')) {
    function deduction($lead_calculate,$id){
        $str = '';
        $total = array();
        
        $lead_calculate = $lead_calculate;
        
         if($lead_calculate['agent_invoice_cost']){
            
            $str.="<tr><td>Invoice Fee</td><td>$".number_format($lead_calculate['agent_invoice_cost'],2).'</td></tr>';
            
            array_push($total,$lead_calculate['agent_invoice_cost']);
        }
        
        if($lead_calculate['commercial_transaction']){
            $str.="<tr><td>Commercial Transaction Fee (Tiered) </td><td>$".number_format($lead_calculate['commercial_transaction'],2).'</td></tr>';
            array_push($total,$lead_calculate['commercial_transaction']);
        }
        
        if($lead_calculate['broker_splite']){
            $str.="<tr><td>Broker Cost </td><td>$".number_format($lead_calculate['broker_splite'],2).'</td></tr>';
            array_push($total,$lead_calculate['broker_splite']);
        }
        
        if($lead_calculate['lead_cost']){
            $str.="<tr><td>Lead Cost </td><td>$".number_format($lead_calculate['lead_cost'],2).'</td></tr>';
            array_push($total,$lead_calculate['lead_cost']);
        }
        
        if($lead_calculate['incentive']){
            
            $str.="<tr><td>Incentive</td><td>$".number_format($lead_calculate['incentive'],2).'</td></tr>';
             
            array_push($total,$lead_calculate['incentive']);
        }
       
        
        if($lead_calculate['transaction_coordination_lease_verify']){
            
            $str.="<tr><td>Optional Fee </td><td>$".number_format($lead_calculate['transaction_coordination_lease_verify'],2).'</td></tr>';
           
            array_push($total,$lead_calculate['transaction_coordination_lease_verify']);
        }
        
        
        $str.="<tr><th>Total Deductions </th><td>$".number_format(array_sum($total),2)."</td></tr>";
        
        $data['string'] = "<a  href='javascript:void(0);' data-toggle='modal' data-target='#showdeduct' onclick='view_deduct($id)'; style='cursor: pointer;text-decoration: none;' title='View Deductios' str='$str' class='ded_$id'>$". number_format(array_sum($total),2)."</a>";
        
        $data['total'] = (array_sum($total));
        
        return $data;
    }
}


if (!function_exists('aroradmin')) {
    function aroradmin($lead_calculate,$reseturl,$id){
        if($reseturl=='adminincome' || $reseturl=='arincome'){
               
            $lead_calculation = $lead_calculate;
                    
             
            $totals=array();
            $str='';
            //$payable_amount= $leadcalculatdata['invoiced_total'];
                
             if($lead_calculation['transaction_coordination_lease_verify']){
            
                array_push($totals,$lead_calculation['transaction_coordination_lease_verify']);
                $str.="<tr><td>Optional Fee</td><td>$".number_format($lead_calculation['transaction_coordination_lease_verify'],2).'</td></tr>';
            }
                
             if($lead_calculation['agent_invoice_cost']){
            
                array_push($totals,$lead_calculation['agent_invoice_cost']);
                $str.="<tr><td>Invoiced fee</td><td>$".number_format($lead_calculation['agent_invoice_cost'],2).'</td></tr>';
            }
                
            if($lead_calculation['commercial_transaction']){
            
                array_push($totals,$lead_calculation['commercial_transaction']);
                $str.="<tr><td>Commercial transaction</td><td>$".number_format($lead_calculation['commercial_transaction'],2).'</td></tr>';
            }
                
            if($lead_calculation['broker_splite']){
            
                array_push($totals,$lead_calculation['broker_splite']);
                $str.="<tr><td>Broker splite</td><td>$".number_format($lead_calculation['broker_splite'],2).'</td></tr>';
            }
                
            $str.="<tr><th>Total Deductions </th><td>$".number_format(array_sum($totals),2).'</td></tr>';
            
            $data['string'] = '<a  href="javascript:void(0);" data-toggle="modal" data-target="#showdeduct" onclick="view_deduct1('.$id.')"; style="cursor: pointer;text-decoration: none;" title="View Deductios" str="'.$str.'" class="ded1_'.$id.'">$'.number_format(array_sum($totals),2).'</a>';
            
            $data['total'] = (array_sum($totals));
            
            return $data;
        }  
                 
    }
}

if (!function_exists('get_income_calculation')) {
    function get_income_calculation($leads){
        
        $id             = Auth::user()->id;
        $user_role      = Auth::user()->user_role;
        
        $result = array();
        
        $outstanding = 0;
        $gross_revenue = 0;
        $deductions = 0;
        $agent_income = array();
        $company_incomes = array();
        $rescommission=0;
        
        
        foreach($leads as $lead){
            
            
            $lead_calculate = lead_calculate($lead['id']);
            
           // echo "<pre>"; print_r($lead_calculate); exit;
            
            $deduction = deduction($lead_calculate,$lead['id']);
            
            $reseturl ='adminincome';
            
            $company_income = aroradmin($lead_calculate,$reseturl,$lead['id']);
           
            if($lead['curr_status']=='Lease Confirmed' || $lead['curr_status']=='Invoiced' || $lead['curr_status']=='Sold' || $lead['curr_status']=='9' || $lead['curr_status']=='10' || $lead['curr_status']=='12'){
                
                //$outstanding += ($lead['invoiced_total']-$lead['payment']); 
               
                if($lead['payment']==0){
                  // $outstanding += ($lead['invoiced_total']); 
                  // edited on 30th may
                  $outstanding += ($lead['invoiced_total'] != null) ? $lead['invoiced_total'] : ((is_numeric($lead_calculate['invoiced_total']) != null) ? $lead_calculate['invoiced_total']:0);   
                    
                }
                // 30th May changes
                // $rescommission += $lead['invoiced_total'];
                $rescommission += ($lead['invoiced_total'] != null) ? $lead['invoiced_total'] : ((is_numeric($lead_calculate['invoiced_total']) != null) ? $lead_calculate['invoiced_total']:0); 
                    $deductions += $deduction['total'];
            }
            
            //$rescommission += $lead['invoiced_total'];
            
            if(($lead['curr_status']=='Pay Received' || $lead['curr_status']=='Paid Out' || $lead['curr_status']=='13' || $lead['curr_status']=='14')){
               
                $gross_revenue+= $lead['payment'];   
                //if($lead['deducation'] >=1)  {
                
                if(!empty($lead['transaction_type_id']))  {
                    array_push($company_incomes,$company_income['total']);
                }
                
                //}
                
                //if($lead['agent_paid']!=0){
                    $agent_incomes = ($lead_calculate['agent_paid']);
                    
                    if(!empty($agent_incomes)){
                        array_push($agent_income,$agent_incomes);
                    }
                //}
                // 30th May changes
                // $rescommission += $lead['invoiced_total'];
                  $rescommission += ($lead['invoiced_total'] != null) ? $lead['invoiced_total'] : ((is_numeric($lead_calculate['invoiced_total']) != null) ? $lead_calculate['invoiced_total']:0); 
                    $deductions += $deduction['total'];
            }
            $deductions += $deduction['total'];
        }
        
        $data['rescommission'] = '$'.number_format($rescommission,2);
        $data['outstanding'] = '$'.number_format($outstanding,2);
        $data['gross_revenue'] =  '$'.number_format($gross_revenue,2);
        $data['deduction'] = '$'.number_format($deductions,2);
        $data['agent_income'] = '$'.number_format(array_sum($agent_income),2);
        $data['company_income'] = '$'.number_format(array_sum($company_incomes),2);
       // $data['id'] = implode(',',array_column($leads,'id'));
       
        if($user_role==2){
           
            DB::select("update admin_income set outsatnginamt='".$outstanding."',gross_pay='".$gross_revenue."',total_income='".$data['agent_income']."' ,comp_income='".$data['company_income']."' ,agent_income='".$data['agent_income']."' where user_id='$id'");
        }
      
     
        $data['id'] ='';
        
        return $data;     
    }
}

if (!function_exists('get_income_calculation_admin')) {
    function get_income_calculation_admin($leads,$type,$income_url=''){
        
        $id             = Auth::user()->id;
        $user_role      = Auth::user()->user_role;
        //echo $type; exit;
        
        $result = array();
        
        $outstanding = 0;
        $gross_revenue = 0;
        $deductions = 0;
        $agent_income = array();
        $company_incomes = array();
        $rescommission = 0;
        
        
        
        
        //echo "<pre>"; print_r($type); exit;
        foreach($leads as $lead){
            
            
            $lead_calculate = lead_calculate($lead['id']);
            
            $deduction = deduction($lead_calculate,$lead['id']);
            
            $reseturl ='adminincome';
            
            $company_income = aroradmin($lead_calculate,$reseturl,$lead['id']);
           
            if($type=='outstand'){
                   if($lead['curr_status']=='Lease Confirmed' || $lead['curr_status']=='Invoiced' || $lead['curr_status']=='Sold' || $lead['curr_status']=='9' || $lead['curr_status']=='10' || $lead['curr_status']=='12'){
                
                //$outstanding += ($lead['invoiced_total']-$lead['payment']); 
               
                    if($lead['payment']==0){
                        $outstanding += ($lead['invoiced_total']);   
                        
                    }
                    
                    $rescommission += $lead['invoiced_total'];
                }
                    
                    
                    $agent_incomes = ($lead_calculate['agent_paid']);
                    
                    if(!empty($agent_incomes)){
                        array_push($agent_income,$agent_incomes);
                    }
                   
                   $gross_revenue+= $lead['payment'];   
                    array_push($company_incomes,$company_income['total']);
                    
                    
                    //$rescommission += $lead['invoiced_total'];
                    
                    $deductions += $deduction['total'];
                    
            }else if($type=='gross'){
                
                if($lead['curr_status']=='Lease Confirmed' || $lead['curr_status']=='Invoiced' || $lead['curr_status']=='Sold' || $lead['curr_status']=='9' || $lead['curr_status']=='10' || $lead['curr_status']=='12'){
                
                //$outstanding += ($lead['invoiced_total']-$lead['payment']); 
               
                    if($lead['payment']==0){
                        $outstanding += ($lead['invoiced_total']);   
                        
                    }
                    
                    $rescommission += $lead['invoiced_total'];
                }
                
                
                if(($lead['curr_status']=='Pay Received' || $lead['curr_status']=='Paid Out' || $lead['curr_status']=='13' || $lead['curr_status']=='14')){
               
               // if($lead['deducation'] >=1)  {
                    $gross_revenue+= $lead['payment'];   
                    array_push($company_incomes,$company_income['total']);
               // }
                
                if($lead['agent_paid']!=0){
                    $agent_incomes = ($lead_calculate['agent_paid']);
                    
                    if(!empty($agent_incomes)){
                        array_push($agent_income,$agent_incomes);
                    }
                }
                $rescommission += $lead['invoiced_total'];
            }
            $deductions += $deduction['total'];
            
                
            }else if($type=='company'){
                
                
                if(!empty($income_url) && $income_url='adminincome'){
                    
                    //if($lead['curr_status']=='Lease Confirmed' || $lead['curr_status']=='Invoiced' || $lead['curr_status']=='Sold' || $lead['curr_status']=='9' || $lead['curr_status']=='10' || $lead['curr_status']=='12'){
                
                        //if($lead['payment']==0){
                         //   $outstanding += ($lead['invoiced_total']);   
                            
                       // }
                    //}
                
                    
                    
                   if(($lead['curr_status']=='Pay Received' || $lead['curr_status']=='Paid Out' || $lead['curr_status']=='13' || $lead['curr_status']=='14')){
                    
                        if($lead['payment']==0){
                            $outstanding += ($lead['invoiced_total']);   
                        }
                    
                    
                        $gross_revenue+= $lead['payment'];
                        
                       array_push($company_incomes,$company_income['total']);
                   
                   $agent_status = 0;
                if($lead['source_id']!=0 || $lead['source_id']!='' || $lead['source_id']!=NULL){

                    $agentsourcedetail    = User::find($lead['source_id']);
    
                    if($agentsourcedetail->manage_distributor==1){
                      $agent_status     = 5; 
                      
                    }
                }

                //$lead     =   Distributorleadmarket::find($leadclient->lead_id_orig);
              
              
                   
                    //   if($agent_status==5){
                    //       $agent_incomes = ($lead_calculate['lead_cost']);
                           
                    //   }else{
                    //       $agent_incomes = ($lead_calculate['agent_paid']);
                    //   }
                    
                       $agent_incomes = ($lead_calculate['agent_paid']);
                        
                        if(!empty($agent_incomes)){
                            array_push($agent_income,$agent_incomes);
                        }
                    
                        $rescommission += $lead['invoiced_total'];
                        
                         $deductions += $deduction['total'];
                    }
                }else{
                    
                  if(($lead['curr_status']=='Pay Received' || $lead['curr_status']=='Paid Out' || $lead['curr_status']=='13' || $lead['curr_status']=='14')){
                    
                        if($lead['payment']==0){
                            $outstanding += ($lead['invoiced_total']);   
                        }
                    
                    
                        $gross_revenue+= $lead['payment'];
                        
                       array_push($company_incomes,$company_income['total']);
                   
                    
                        $agent_incomes = ($lead_calculate['agent_paid']);
                        
                        if(!empty($agent_incomes)){
                            array_push($agent_income,$agent_incomes);
                        }
                    
                        $rescommission += $lead['invoiced_total'];
                        
                         $deductions += $deduction['total'];
                    }  
                }
        
        
                
                
                
            }else if($type=='all'){
                
                
                if(!empty($income_url) && $income_url='adminincome'){
                    
                    
                    
                    $lead_calculate = lead_calculate($lead['id']);
                    $reseturl ='adminincome';
                    $company_income = aroradmin($lead_calculate,$reseturl,$lead['id']);
                    
                    if($lead['curr_status']=='Lease Confirmed' || $lead['curr_status']=='Invoiced' || $lead['curr_status']=='Sold' || $lead['curr_status']=='9' || $lead['curr_status']=='10' || $lead['curr_status']=='12'){
                
               
                        if($lead['payment']==0){
                            // edited on 26th may 
                            $outstanding += ($lead['invoiced_total'] != null) ? $lead['invoiced_total'] : ((is_numeric($lead_calculate['invoiced_total']) != null) ? $lead_calculate['invoiced_total']:0);  
                        }
                    }
                   
                   
                    if(($lead['curr_status']=='Pay Received' || $lead['curr_status']=='Paid Out' || $lead['curr_status']=='13' || $lead['curr_status']=='14')){
               
                        $gross_revenue+= $lead['payment'];  
                    }
                    
                    if(($lead['curr_status']=='Pay Received' || $lead['curr_status']=='Paid Out' || $lead['curr_status']=='13' || $lead['curr_status']=='14')){
               
                        if(!empty($lead['transaction_type_id']))  {
                            array_push($company_incomes,$company_income['total']);
                        }
                    }
                    
                    if(($lead['curr_status']=='Pay Received' || $lead['curr_status']=='Paid Out' || $lead['curr_status']=='13' || $lead['curr_status']=='14')){
                    
                        $agent_incomes = ($lead_calculate['agent_paid']);
                    
                        if(!empty($agent_incomes)){
                            array_push($agent_income,$agent_incomes);
                        }
                    }
                    
                    
                    // edited on 26th may 
                    // $rescommission += $lead['invoiced_total']; 
                    $rescommission += ($lead['invoiced_total'] != null) ? $lead['invoiced_total'] : ((is_numeric($lead_calculate['invoiced_total']) != null) ? $lead_calculate['invoiced_total']:0); 
                    $deductions += $deduction['total'];
                
                }
            }else{
                
                
                
                if($lead['curr_status']=='Lease Confirmed' || $lead['curr_status']=='Invoiced' || $lead['curr_status']=='Sold' || $lead['curr_status']=='9' || $lead['curr_status']=='10' || $lead['curr_status']=='12'){
                
                //$outstanding += ($lead['invoiced_total']-$lead['payment']); 
               
                    if($lead['payment']==0){
                        // edited on 26th may 
                        // $outstanding += ($lead['invoiced_total']); 
                        $outstanding += ($lead['invoiced_total'] != null) ? $lead['invoiced_total'] : ((is_numeric($lead_calculate['invoiced_total']) != null) ? $lead_calculate['invoiced_total']:0);   
                        
                    }
                    
                    //$rescommission += $lead['invoiced_total'];
                }
                
                
                if(($lead['curr_status']=='Pay Received' || $lead['curr_status']=='Paid Out' || $lead['curr_status']=='13' || $lead['curr_status']=='14')){
                    $gross_revenue+= $lead['payment'];   
                     // $rescommission += $lead['invoiced_total'];  
                    // edited on 26th may 
                    $rescommission += ($lead['invoiced_total'] != null) ? $lead['invoiced_total'] : ((is_numeric($lead_calculate['invoiced_total'])) ? $lead_calculate['invoiced_total']:0); 
                   //if($lead['deducation'] >=1)  {
                       
                        //array_push($company_incomes,$company_income['total']);
                   //}
                     array_push($company_incomes,$company_income['total']);
                    //if($lead['incentive']!=0){
                        $agent_incomes = ($lead_calculate['agent_paid']);
                        
                        if(!empty($agent_incomes)){
                            array_push($agent_income,$agent_incomes);
                        }
                   // }
                   
                    //$rescommission += $lead['invoiced_total'];
                }
                $deductions += $deduction['total'];
                
                
            }
            
           
            
            
            //$rescommission += $lead['invoiced_total'];
            
            
        }
        
        
        $data['rescommission'] = '$'.number_format($rescommission,2);
        $data['outstanding'] = '$'.number_format($outstanding,2);
        $data['gross_revenue'] =  '$'.number_format($gross_revenue,2);
        $data['deduction'] = '$'.number_format($deductions,2);
        $data['agent_income'] = '$'.number_format(array_sum($agent_income),2);
        $data['company_income'] = '$'.number_format(array_sum($company_incomes),2);

        
        
       // $data['id'] = implode(',',array_column($leads,'id'));
       
        if($user_role==2){
           
            //DB::select("update admin_income set outsatnginamt='".$outstanding."',gross_pay='".$gross_revenue."',total_income='".$data['agent_income']."' ,comp_income='".$data['company_income']."' ,agent_income='".$data['agent_income']."' where user_id='$id'");
        }
      
     
        $data['id'] ='';
        
        return $data;     
    }
}
if (!function_exists('get_status_name')) {
    function get_status_name($id)
    {
        //echo $id;
        if(is_numeric($id)){
            $rest = DB::select("select * from lead_status where id='$id'")[0];
            return ($rest->status_name); exit;
        }else{
          return ($id); exit;  
        }
        
    }
}

if (!function_exists('get_status_id')) {
    function get_status_id($id)
    {
        //$rest = DB::select("select * from lead_status where status_name='$id'")[0];        
        $rest = DB::select("select * from lead_status where status_name='$id' or new_status_name='$id'")[0];

        return ($rest->id); exit;
    }
}


if (!function_exists('set_status_name')) {
    function set_status_name($id)
    {
        //echo $id;
        if(is_numeric($id)){
            $rest = DB::select("select * from lead_status where id='$id'")[0];
            return ($rest->new_status_name); exit;
        }else{
            
            if (strpos($id, "~~") !== false) {
            $ids = explode('~~',$id)[1];
            
            $rest = DB::select("select * from lead_status where status_name='$ids'")[0];
            return explode('~~',$id)[0].'~~'.($rest->new_status_name); 
    
            exit;
            }else{
                $id =$id;
                
                if(!empty($id)){
                     $rest = DB::select("select * from lead_status where status_name='$id'")[0];
                    return ($rest->new_status_name); exit;
                }
               
            }
        }
    }
}

if (!function_exists('generate_income_pdf')) {
    function generate_income_pdf($leads,$url,$income_url=''){
        
        
        $income_detail = get_income_calculation_admin(json_decode(json_encode($leads), true),$url,$income_url);
        //echo "<pre>"; print_r($income_detail); exit;
        $response['url']                =   'searchagentincome';
        $response['search_start_date']  =   '';
        $response['search_end_date']    =   '';
        $response['show_agent_list']    =   1;
        $response['reseturl']           =   $url;
        $response['income_detail']      =   $income_detail;
        $response['leadclients']        =   $leads;
        
        $response['rescommission']      =  $income_detail['rescommission'];
        $response['outsatnginamt']      =  $income_detail['outstanding'];
        $response['gross_revenue']      =  $income_detail['gross_revenue'];
        $response['deduction']          =  $income_detail['deduction'];
        $response['outstanding']        =  $income_detail['outstanding'];
        $response['agent_income']       =  $income_detail['agent_income'];
        $response['company_income']     =  $income_detail['company_income'];
        
        $path='/adminincome';
          
        if($path == '/adminincome' || $path =='adminincome_new'){
            $title= $usserpage = 'Admin Income';
        }elseif($path == '/arincome'){
            $title= $usserpage = "AR Income";
        }else{
            $title= $usserpage = "Agent Income";
        }
         
        $response['title']  =   $title;
        
        return $response; exit;
    }
}


if (!function_exists('payout_payreceived_date')) {
    function payout_payreceived_date($status_history){
        
        $arr              =   explode("~~~~",$status_history);
       // return $arr; exit;
        
        $paid_rec = "";
        $paid_out = "";

        for ($i=0;$i<count($arr);$i++) {
         
            if((strpos($arr[$i],"Pay Received") > -1)) {
                $date       =   explode("~~",$arr[$i]);
                if($date[0]){
                  $newdate    =  explode("-",$date[0]);
                  if (str_contains($date[0], '-')) { 
                    $newdate    =  explode("-",$date[0]);
                  }else{
                    $newdate    =  explode("/",$date[0]);
                  }
                  if(!empty($newdate[1]) && !empty($newdate[2]) && !empty($newdate[0])){
    
                    $paid_rec  =   date('m/d/Y',strtotime($newdate[1].'-'.$newdate[0].'-'.$newdate[2]));
                  }
                }
                break;
            }
        }
            
         for ($i=0;$i<count($arr);$i++) {   
            if((strpos($arr[$i],"Paid Out") > -1) ) {
                $date       =   explode("~~",$arr[$i]);
    
                if($date[0]){
                  $newdate    =  explode("-",$date[0]);
                  if (str_contains($date[0], '-')) { 
                    $newdate    =  explode("-",$date[0]);
                  }else{
                    $newdate    =  explode("/",$date[0]);
                  }
                  if(!empty($newdate[1]) && !empty($newdate[2]) && !empty($newdate[0])){
    
                    $paid_out   =  date('m/d/Y',strtotime($newdate[1].'-'.$newdate[0].'-'.$newdate[2]));
                  }
                }
                break;
            }
        }
      
        $data['paid_rec'] = $paid_rec;
        $data['paid_out'] = $paid_out;
        return $data;
    }
} 

 function aroradmin($lead_calculate,$reseturl,$id){
        if($reseturl=='adminincome' || $reseturl=='arincome'){
               
                   
            $lead_calculation = $lead_calculate;
                    
                  
            $totals=array();
            $str='';
            //$payable_amount= $leadcalculatdata['invoiced_total'];
                
             if($lead_calculation['transaction_coordination_lease_verify']){
            
                array_push($totals,$lead_calculation['transaction_coordination_lease_verify']);
                $str.="<tr><td>Optional Fee</td><td>$".number_format($lead_calculation['transaction_coordination_lease_verify'],2).'</td></tr>';
            }
                
             if($lead_calculation['agent_invoice_cost']){
            
                array_push($totals,$lead_calculation['agent_invoice_cost']);
                $str.="<tr><td>Invoiced fee</td><td>$".number_format($lead_calculation['agent_invoice_cost'],2).'</td></tr>';
            }
                
            if($lead_calculation['commercial_transaction']){
            
                array_push($totals,$lead_calculation['commercial_transaction']);
                $str.="<tr><td>Commercial transaction</td><td>$".number_format($lead_calculation['commercial_transaction'],2).'</td></tr>';
            }
                
            if($lead_calculation['broker_splite']){
            
                array_push($totals,$lead_calculation['broker_splite']);
                $str.="<tr><td>Broker splite</td><td>$".number_format($lead_calculation['broker_splite'],2).'</td></tr>';
            }
                
            $str.="<tr><th>Total Deductions </th><td>$".number_format(array_sum($totals),2).'</td></tr>';
            
            $data['string'] = '<a  href="javascript:void(0);" data-toggle="modal" data-target="#showdeduct" onclick="view_deduct1('.$id.')"; style="cursor: pointer;text-decoration: none;" title="View Deductios" str="'.$str.'" class="ded1_'.$id.'">$'.number_format(array_sum($totals),2).'</a>';
            
            $data['total'] = (array_sum($totals));
            
            return $data;
        }  
                 
    }

    if (!function_exists('upload_file')) {
    function upload_image($file_name,$custom_path='')
       {
           $image = $file_name;
           $image_name = uniqid().time().'.'.$image->getClientOriginalExtension();
           if(empty($custom_path)){
               $path = 'upload/images/w9_files/';
           }else{
               $path = $custom_path;
           }
           $destinationPath = public_path($path);
           if (!file_exists($destinationPath)) {
               mkdir($destinationPath, 0777, true);
           }
           $image->move($destinationPath, $image_name);
            $imagePath = $path.$image_name;

           return $imagePath;
       }
    }

    if(! function_exists('bucket_upload')) {
      function bucket_upload($file_name,$custom_path = '',$name="",$type=0) {

        if(empty($custom_path)){
          $path = 'upload/images/w9_files/';
        }else{
          $path = $custom_path;
        }

        // Check if the folder exists, create it if not
        if (!Storage::disk('s3')->exists($custom_path)) {
            Storage::disk('s3')->makeDirectory($custom_path);
        }


        //Updated s3 bucket file upload
        if(empty($name)) {
          $imageName = time().'.'.$file_name->getClientOriginalExtension();
        } else {
          $imageName = $name;
        }
        
        $filePath  = $path . $imageName;
        try{
          
          // Upload the file to Amazon S3
           if($type == 1)
           {
             Storage::disk('s3')->put($filePath,$file_name);
           } else {
              Storage::disk('s3')->put($filePath, file_get_contents($file_name));
           } 

          // Retrieve the public URL of the uploaded file
          $imagePath = Storage::disk('s3')->url($filePath);

          return $imageName;

        } catch(Exception $e) {
          return redirect()->back()->withError($e->getMessage());
        }
            
        // return $filePath;
      }
    }

    if(! function_exists('bucket_show')) {
      function bucket_show($path) {

        return Storage::disk('s3')->url($path);
      }
    }

    if(! function_exists('bucket_delete')) {
      function bucket_delete($path) {

        return Storage::disk('s3')->delete($path);
      }
    }

    if(! function_exists('bucket_exist')) {
      function bucket_exist($path) {
        return Storage::disk('s3')->exists($path);
      }
    }

    if (!function_exists('transaction_calculation')) {
    function transaction_calculation($transaction_type_id,$agent,$type)
       {
        $result = '';
        if($type == 'invoicing_cost'){
          if($transaction_type_id == 1) {
            $result =  (float) $agent->al_invoicing_cost;
          } else if($transaction_type_id == 2){
            $result =  (float) $agent->rl_invoicing_cost;
          } else if($transaction_type_id == 3){
            $result = (float) $agent->rs_invoicing_cost;
          } else if($transaction_type_id == 5){
            $result = (float) $agent->cl_invoicing_cost;
          } else if($transaction_type_id == 6){
            $result = (float) $agent->cs_invoicing_cost;
          } else {
            $result = (float) $agent->invoicing_cost;
          }
        } else if ($type == 'unit') {
          if($transaction_type_id == 1) {
            $result =  (float) $agent->al_unit;
          } else if($transaction_type_id == 2){
            $result =  (float) $agent->rl_unit;
          } else if($transaction_type_id == 3){
            $result = (float) $agent->rs_unit;
          } else if($transaction_type_id == 5){
            $result = (float) $agent->cl_unit;
          } else if($transaction_type_id == 6){
            $result = (float) $agent->cs_unit;
          } else {
            $result = (float) $agent->unit;
          }
        } else if($type == 'broker_cost') {
          if($transaction_type_id == 1) {
            $result =  (float) $agent->al_broker_cost;
          } else if($transaction_type_id == 2){
            $result =  (float) $agent->rl_broker_cost;
          } else if($transaction_type_id == 3){
            $result = (float) $agent->rs_broker_cost;
          } else if($transaction_type_id == 5){
            $result = (float) $agent->cl_broker_cost;
          } else if($transaction_type_id == 6){
            $result = (float) $agent->cs_broker_cost;
          } else {
            $result = (float) $agent->broker_cost;
          }
        } else if($type == 'commercial_tier1') {
          if($transaction_type_id == 5){
            $result = (float) $agent->cl_commercial_tier1;
          } else if($transaction_type_id == 6) {
            $result = (float) $agent->cs_commercial_tier1;
          } else {
            $result = 0;
          }
        } else if($type == 'commercial_tier2') {
          if($transaction_type_id == 5){
            $result = (float) $agent->cl_commercial_tier2;
          } else if($transaction_type_id == 6) {
            $result = (float) $agent->cs_commercial_tier2;
          } else {
            $result = 0;
          }
        } else if($type == 'commercial_tier3') {
          if($transaction_type_id == 5){
            $result = (float) $agent->cl_commercial_tier3;
          } else if($transaction_type_id == 6) {
            $result = (float) $agent->cs_commercial_tier3;
          } else {
            $result = 0;
          }
        }
        return $result;
       }
    } 
 