<?php

namespace App\Http\Controllers;

use App\model\Distributordashboard;
use App\model\Leadclient;
use App\model\Leadclientcalculation;
use App\model\Distributorleadmarket;
use App\Helper\helper;
use Auth;
use App\User;
use Session;
use DB;
use Mail;
use PDF;
use Validator;
use File;
use Carbon\Carbon;
use Illuminate\Http\Request;


class DistributordashboardController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

       public function __construct()
    {
        $this->middleware('auth');
    }

    public static function setPaidDate($id,$paid_date){

      $data     =   ['newpaid_date'=>$paid_date];
      Leadclient::where('id',$id)->update($data);
      $result   = Leadclient::find($id);
      return $result->newpaid_date;
    }
    
    public function index(Request $request)
    {  

        $items              =   $request->items ?? 25;
        $user_role          =   Auth::user()->user_role;
        $id                 =   Auth::user()->id;
        $useraragent        =   array();

        $pref               = '';

        if (!session('setAgentAdminPrefrence')){
            Session::put('setAgentAdminPrefrence', $pref);
        }else{
            $pref = session('setAgentAdminPrefrence');
        }

        $lead =0;
        if (session('leadsearchresult') != ''){
            $ser = '';

            if (strtotime(Session('leadsearchresult')) !== false){
                $date = date('Y-m-d', strtotime(Session('leadsearchresult')));
            }else{
                $date = '0000-00-00';
            }
            $leadclients    =   Leadclient::join('users', 'lead_client.agent_id','=','users.id')
                                            ->join('lead','lead.id','=','lead_client.lead_id_orig')
                                            ->select('lead_client.*','lead.unit as dunit','lead.lead_cost as lcost','users.name','users.last_name');
            /* condition if user put value in input box and don't choose aany filter type than it should work on 3 columns, fname, lname, email */
            
            if(($pref == 'myone' || $pref == '')  && Session::get('leadsearchresult') != ''){

                $leadclients    =   $leadclients->where(function ($query){
                                        $query->select('*')
                                                ->where('lead_client.fname', 'like', DB::raw("'%".Session('leadsearchresult')."%'"))
                                                ->orWhere('lead_client.lname', 'like', DB::raw("'%".Session('leadsearchresult')."%'"))
                                                ->orWhere('lead_client.email', 'like', DB::raw("'%".Session('leadsearchresult')."%'"))
                                                ->orderBy('lead_client.id', 'ASC');
                                    });
            }

            if ($pref == "curr_status"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                $query->select('*')
                                                    ->orWhere('lead_client.curr_status', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "move_date"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                $query->select('*')
                                                    ->where('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "uname"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                $query->select('*')
                                                    ->where('users.name', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                    ->orWhere('users.last_name', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "fname"){
                
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                    $query->select('*')
                                                        ->where('lead_client.fname', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                        ->orWhere('lead_client.lname', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                        ->orderBy($pref, 'ASC');
                                                    });
            }else if ($pref == "lname"){
                
                $leadclients    =   $leadclients->where(function ($query) use ($pref){
                                                    $query->select('*')
                                                        ->where('lead_client.lname', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                        ->orderBy($pref, 'ASC');
                                                    });
            }else if ($pref == "phone1"){
                
                $leadclients    =   $leadclients->where(function ($query) use ($pref){
                                                    $query->select('*')
                                                        ->where('lead_client.phone1', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                                        ->orderBy($pref, 'ASC');
                                                    });
            }else{

                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                        $query->select('*')
                                            ->orWhere('lead_client.id', session('leadsearchresult'))
                                            ->orWhere('lead_client.fname', 'LIKE', '%' . session('leadsearchresult') . '%')
                                            ->orWhere('lead_client.lname', 'LIKE', '%' . session('leadsearchresult') . '%')
                                            ->orWhere('lead_client.email', 'LIKE', '%' . session('leadsearchresult') . '%')
                                            ->orWhere('lead_client.curr_status', 'LIKE', '%' . session('leadsearchresult') . '%')
                                            ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')->orderBy($pref, 'ASC');
                                    });
            }
        }else{

            $leadclients    =   Leadclient::join('users', 'lead_client.agent_id','=','users.id')
                                            ->join('lead','lead.id','=','lead_client.lead_id_orig')
                                            ->select('lead_client.*','lead.unit as dunit','lead.lead_cost as lcost','users.name','users.last_name');
        }

        if($user_role != AGENT){

            $useraragent = User::where('user_role','=',AGENT)
                                  ->where('manage_distributor','=',1)
                                  ->where('status','=',1);
            if($user_role == SUPERADMIN){
              $useraragent       =   $useraragent->get();
            }elseif($user_role == ADMIN){
              $useraragent       =   $useraragent->where('create_by_user','=',$id)->get();
            }elseif($user_role == ARUSER){
              $useraragent        =   $useraragent->where('assign_to_ar','=',$id)->get();
            } 
            if(empty($useraragent->first())){
                echo "Sorry You Don't have not any manager ";
               //die();
            }else{
                if(Session::get('distributor') == ''){
                    
                  $first = $useraragent->first();
                  Session::put('distributor', $first->id);
                  $lead   =  $leadclients->where('lead_client.source_id',$first->id);
                }else{
                  
                  $lead   =  $leadclients->where('lead_client.source_id',Session('distributor'));
                }
            }
        }else{
            $lead       =       $leadclients->where('lead_client.source_id',$id);
        }
        
        if(!empty($useraragent->first())){

            $lead           =   $lead->sortable()->paginate($items);
        }
        
        $dist_id        =   Auth::user()->id;
           
        return view('distributorleadmarket.income',['leads'=>$lead,'usersagent'=>$useraragent])->withMembers($lead)->withItems($items);
    }


    /*
    * @function : listLeadScraper (to list all Lead Scraper of distributor.)
    * @params: request data distributor id
    * @return : json data of all income reccords
    * @modifiedby:  chintesh k.
    */ 
    public function listLeadScraper(Request $request)
    {  

        $items              =   $request->items ?? 25;
        $user_role          =   Auth::user()->user_role;
        $id                 =   Auth::user()->id;
        $useraragent        =   array();

       

        

        $leadclients    =   DB::table('lead_scraper')->join('users', 'lead_scraper.distributor_id','=','users.id')
                                            ->select('lead_scraper.*','users.name','users.last_name');
        

        $lead           =   $leadclients->paginate($items);
        $dist_id        =   Auth::user()->id;


        return view('distributorleadmarket.lead_scraper',['leads'=>$lead,'usersagent'=>$useraragent])->withMembers($lead)->withItems($items);
    }


    
/*
* @function : index (to list all income for agent user of distributor.)
* @params: request data distributor id
* @return : json data of all income reccords
* @modifiedby:  chintesh k.
*/    
  public function distributorIncome(Request $request){

    $id               = Auth::user()->id; 
    $user_role        = Auth::user()->user_role; 
    $items            = $request->items ?? 500000;
    $role_for         = "AGENT";
    $is_distributor   = false;
    
    
    // code by Randhir kumar//
    $outstanding      = $request->input('outstanding');
    $gross            = $request->input('gross');
    $totaln           = $request->input('total');
    // End here //
      

    Session::put('role_for',$role_for);
    $useraragent    = '';
    $distributors   = '';

    if($user_role == SUPERADMIN){

      $distributors     =   User::where('user_role','=',AGENT)
                              ->where('manage_distributor',1)
                              ->where('status','=',1)
                              ->orderBy('name','ASC')
                              ->get();

    }else if($user_role == ADMIN){

      $distributors     =   User::where('user_role','=',AGENT)
                              ->where('manage_distributor',1)
                              ->where('status','=',1)
                              ->where('company','=',Auth::user()->company)
                              ->orderBy('name','ASC')
                              ->get();
    }else{

      $useraragent      =   User::where('user_role','=',AGENT)
                                  ->where('status','=',1)
                                  ->where('lead_source_access_to_gent', 'LIKE', '%' . $id . '%')
                                  ->orderBy('name','ASC')
                                  ->get();

      $distributors     =   User::where('id',$id)->get();
    }



    if(session('disagentsearch') == '' && count($distributors)){
      
      $firstdistributor =  $distributors->first(); 
      if(!empty($firstdistributor)){   

        if($firstdistributor->id != ''){
          Session::put('disagentsearch', $firstdistributor->id);
        }
      }else{
        Session::put('disagentsearch',0);
      }
    }


    if(session('aragentsearch') == '' && session('disagentsearch')){
      
      $firstdistributor         =   session('disagentsearch');
      $agents_of_distri         =   User::where('user_role','=',AGENT)
                                        ->where('status','=',1)
                                        ->where('lead_source_access_to_gent', 'LIKE', '%' . $firstdistributor . '%')
                                        ->orderBy('name','ASC')
                                        ->pluck('id')
                                        ->toArray();

      $leadclients              =     Leadclient::whereIn('agent_id',$agents_of_distri)
                                            ->where('source_id',session('disagentsearch'))
                                            ->join('users', 'users.id', '=', 'lead_client.agent_id')
                                            ->leftjoin('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');
      $leadclientstotal         =     Leadclient::whereIn('agent_id',$agents_of_distri)                                         ->where('source_id', session('disagentsearch'))
                                              ->join('users', 'users.id', '=', 'lead_client.agent_id')
                                              ->leftjoin('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');
    }else{
      
      $leadclients            =   Leadclient::where('agent_id',session('aragentsearch'))
                                            ->where('source_id',session('disagentsearch'))
                                            ->join('users', 'users.id', '=', 'lead_client.agent_id')
                                            ->leftjoin('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');
      $leadclientstotal       =   Leadclient::where('agent_id', session('aragentsearch'))                                         ->where('source_id', session('disagentsearch'))
                                              ->join('users', 'users.id', '=', 'lead_client.agent_id')
                                              ->leftjoin('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');
    }

    $distributor_id         =   session('disagentsearch');
    $agent_id               =   session('aragentsearch');

    if($user_role == SUPERADMIN || $user_role == ADMIN){
      
      $useraragent   =    User::where('user_role','=',AGENT)
                              ->where('lead_source_access_to_gent', 'LIKE', '%' . $distributor_id . '%')
                              ->where('status','=',1)
                              ->orderBy('name','ASC')
                              ->get();
    }

    $search_start_date  =   ''; 
    $search_end_date    =   ''; 
    $searchform         =   $request->input('search_agent'); 
   
    if(isset($searchform)){

      //$statusarry         = ['Invoiced','Pay Received','Paid Out','Sold','Lease Confirmed','MIC'];
      $statusarry         = ['Paid Out','14'];
      
      $client_name        =  $request->input('client_name');
      $client_id          =  $request->input('client_id');
      $arr                =  explode(" ", $client_name);
      
      @$c_fname             = $arr[0];
      @$c_lname             = $arr[1];
      $data['client_name']  = $client_name;

      

      if ($client_name !='') {

        $leadclients      =   $leadclients->where('lead_client.fname',$c_fname)
                                          ->where('lead_client.lname',$c_lname);
        $leadclientstotal =   $leadclientstotal->where('lead_client.fname',$c_fname)
                                                ->where('lead_client.lname',$c_lname);
      }

      if ($client_id !='') {
        $leadclients      =  $leadclients->where('lead_client.id',$client_id);
        $leadclientstotal =  $leadclientstotal->where('lead_client.id',$client_id);
      }

      $search_start_date = setdbdate($request->input('search_start_date'));
      $search_end_date   = setdbdate($request->input('search_end_date'));

      if($search_start_date != '' && $search_end_date != ''){
       
        $leadclients =  $leadclients->whereIn('lead_status_history.status',$statusarry);
        $leadclients =  $leadclients->whereBetween('lead_status_history.date',[$search_start_date,$search_end_date]);
        

        $leadclientstotal =  $leadclientstotal->whereIn('lead_status_history.status',$statusarry);
        $leadclientstotal =  $leadclientstotal->whereBetween('lead_status_history.date',[$search_start_date,$search_end_date]);
      }
    }else{

      //$statusarry       = ['Invoiced','Pay Received','Paid Out','Sold','Lease Confirmed','MIC'];
      $statusarry         = ['Paid Out','14'];
      
      $statusarry123    = ['Invoiced','Sold','Lease Confirmed','MIC','12','9','10','11'];
      
      $statusarry123    = ['Paid Out','14'];
      $leadclients      = $leadclients->whereIn('lead_status_history.status',$statusarry);
      $leadclientstotal = $leadclientstotal->whereIn('lead_status_history.status',$statusarry123);
    }

    $leadclientPDF      =   $leadclients->whereIn('curr_status', $statusarry)
                                        ->orderby('lead_client.id','DESC')
                                        ->groupBy('lead_client.id')
                                        ->paginate($items);

    $leadclients        =   $leadclients->whereIn('curr_status', $statusarry)
                                        ->orderby('lead_client.id','DESC')
                                        ->groupBy('lead_client.id')
                                        ->paginate($items); 
    $statusarry123      =   ['Invoiced','Sold','Lease Confirmed','MIC','12','9','10','11'];

    $leadclientstotal   =   $leadclientstotal->whereIn('curr_status', $statusarry123)
                                            ->orderby('lead_client.id','ASC')
                                            ->groupBy('lead_client.id')
                                            ->get();
    $tot_net          =   0;
    $tot_invoiced     =   0;
    $tot_paid         =   0;
    $outsatnginamt    =   0;
    $sc               =   count($leadclients);
    $newres_comm      =   0;

          
    foreach ($leadclientstotal  as $keytotal => $valuetotal) {
      // Implemented By Vinod Date 12/02/2020 start
      $caculation   =   $this->getcalculation($valuetotal->id);
      if(!empty($caculation)){
        $newres_comm  =   (float) $caculation['paidamount'];
      }else{
        $newres_comm  =   0;
      }
      $outsatnginamt += $newres_comm;
    }

    foreach( $leadclients  as $keytotal => $valuetotal) {
      // Implemented By Vinod Date 12/02/2020 start
      $caculation           =   $this->getcalculation($valuetotal->id);
      $valuetotal->payment  =   number_format((float)$valuetotal->payment, 2, '.', '');
      $arr                  =   explode("~~~~",$valuetotal->status_history);
      $paid_date            =   "";
      
      $leadcalculatdata     =   Leadclientcalculation::where('leadclient_id','=',$valuetotal->id)
                                                  ->get()
                                                  ->first();
      $paid_amt             =   (float) $valuetotal->payment;
      $inc                  =   (float) $valuetotal->incentive;
              
      if(!empty($leadcalculatdata)){
        $leadcost   =   $leadcalculatdata->lead_cost;
      }else{
        $leadcost   =   0;
      }
     
      $user       =   User::find($valuetotal->agent_id);
      $invcostt   =   (float) $user->invoicing_cost;

      /*if(((float)$paid_amt-(float)$inc-(float)$leadcost-(float)$invcostt) > 0){
        $tot_net  += (float)$paid_amt-(float)$inc-(float)$leadcost-(float)$invcostt;
      }*/

      $tot_net  += (float) $leadcost;
      
      
      if($valuetotal->prop_id !=0 || $valuetotal->prop_id !=''){
      
        if (trim($valuetotal->commision)==""){
          $valuetotal->commision = 0;
        }

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

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

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

        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;
      }
      $tot_invoiced += $total;
      $tot_paid     += $paid_amt;
    }
    $total_incoe = array();
    foreach($leadclients as $leadclient){
        $leadcalculation = $this->getcalculation($leadclient->id);
        $lead_cost = lead_calculate($leadclient->id)['lead_cost'];
        array_push($total_incoe,$lead_cost);
    
    }
    
    $data['totalincome']          = array_sum($total_incoe);   //$tot_net;
    $data['outsatnginamt']        = $outsatnginamt;
    $data['url']                  = 'searchdistributorincome';
    $data['search_start_date']    = $search_start_date;
    $data['search_end_date']      = $search_end_date;
    $data['leadclients']          = $leadclients;
    $data['leadclientPDF']        = $leadclientPDF;
    $data['useraragents']         = $useraragent;
    $data['search_end_date']      = $search_end_date;
    $data['show_agent_list']      = 1;
    $data['reseturl']             = 'distributor-income';
    $data['distributor']          = $distributor_id;
    $data['distributors']         = $distributors;
    $data['is_distributor']       = session('disagentsearch') ? true : false;
    // code by randhir kumar//
    $data['outstanding']          =   $outstanding;
    $data['gross']                =   $gross;
    $data['total']                =   $totaln;

    
    if (request()->has('pdf')) {

      $pdf = PDF::loadView('distributorleadmarket.printpdf',
            ['data'=>$data])->setPaper('a4', 'landscape');
      $pdf->save(storage_path('pdf/'.date('Y-m-d').'_'.$id.'_income_pdf.pdf'));

      if($_SERVER['SERVER_NAME'] == 'development.realm.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'development.flexsin.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'realm.clientmgr.us'){

        $data['link'] = PDFPATH.'../storage/pdf/'.date('Y-m-d').'_'.$id.'_income_pdf.pdf';
      }else{
        $data['link'] = PDFPATH.'../crmrewrite/storage/pdf/'.date('Y-m-d').'_'.$id.'_income_pdf.pdf';
      }
      echo '{"status":true,"link":"'.$data['link'].'"}'; die();
    }

    return view('distributorleadmarket.distributor_income',['data'=>$data])->withMembers($leadclients)->withItems($items);
  }

  public function distributorsetsession(Request $request){
     //print_r($request->input());
     ///echo "test ".$_POST['agent_id']; exit;
        //exit;        
      $agenrt_id    = (!empty($request->input('distributor_id'))?$request->input('distributor_id'):$_POST['agent_id']);
      
      if ($agenrt_id > 0){
        //if(!empty($_POST['agent_id'])){
            Session::put('distributor', $agenrt_id);
            Session::put('disagentsearch', $agenrt_id);
        //}
        //Session::put('disagentsearch', $agenrt_id);
        
        return response()->json([
                    'status'  => true,
                    'data'    => $agenrt_id,
              ]);
      }
  }

  public function searchAgentName(Request $request){ 

      $name         =   $request->inputVal;
      $distr        =   $request->distVal;
      $leadclients  =   User::where('user_role','=',AGENT)
                            ->where('lead_source_access_to_gent','LIKE','%'.$distr.'%')
                            ->where(function($q) use($name) {
                                    $q->select('*')
                                      ->where('name', 'LIKE', '%'.$name.'%')
                                      ->orWhere('last_name', 'LIKE', '%'.$name.'%');
                                  })
                            ->orderBy('name','ASC')
                            ->get();
      if (count($leadclients)) {
        foreach ($leadclients as $keyser => $valueser) {
          echo "<p style='padding-left:5px;'>" .$valueser->name.' '.$valueser->last_name."</p>";
        }
      } else{
        echo "<p style='padding-left:5px;'>No matches found</p>";
      }
    }
  /*
  * @function: getcalculation (to get the calculation of lead clint payment)
  * @params: lead_id
  * @return: calculated data in array
  * @modifiedby: chintesh k.
  **/    
  public static function getcalculation($id){

      $total            = 0;
      $total_cost       = 0;
      $net              = 0;
      $agent_paid       = 0;

      $leadclient       =   Leadclient::find($id);
      $leadcalculatdata =   Leadclientcalculation::where('leadclient_id','=',$leadclient->id)->get()->first();
      

      $arr              =   explode("~~~~",$leadclient->status_history);

      $sold_amt           =   $leadclient->sold_amt ? (float) $leadclient->sold_amt : 0;
      $house_comm         =   $leadclient->house_comm ? (float) $leadclient->house_comm : 0;
        $house_bonus        =   $leadclient->house_bonus ? (float) $leadclient->house_bonus : 0;
      $agentleaddetail    =   User::find($leadclient->agent_id);
      /* New code added for agent paid amount */
      

      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;
            }
        }

        if ($leadclient->sold_amt > 0){
            $totalcommission = (float) $sold_amt * ((float) $house_comm / 100) + (float) $house_bonus;
        }

        if ($agent_status == 5){

            $lead               =   Distributorleadmarket::find($leadclient->lead_id_orig);
            $agent_split_hous   =   (float) $agentleaddetail->broker_cost;
            $agent_split        =   (float) $agentleaddetail->broker_cost;
            $agent_invoice_cost =   (float) $leadclient->invoicing_cost ? $leadclient->invoicing_cost : 1;
            $incentive          =   (float) $leadclient->incentive;

            if (!empty($lead)){

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

                $dis_split      = 0;
                $dis_split_unit = 0;
            }

            if ((float) $leadclient->payment != 0){

                if ($dis_split_unit == 0){
                    $dis_split              = (float) $dis_split / 100;
                    $leadclient->lead_cost  = ((float) $leadclient->payment - (float) $agent_invoice_cost) * (float) $dis_split;

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

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

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

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

            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{
            
            if ((float) $leadclient->payment != 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;
                }else{

                    $lead_cost  = $agent_split;
                    $agent_paid = (float) $leadclient->payment - (float) $agent_invoice_cost - (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;
                }
            }
        }

        $agentleaddetail    =   User::find($leadclient->agent_id);
        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;
            }else{
                $tot_trans_amt = (float) $leadclient->sold_amt;
            }

            if($tot_trans_amt <= 100000){
                $invoice_cost = $agentleaddetail->commercial_tier1;
            }else if($tot_trans_amt > 100000 && $tot_trans_amt <= 1000000){
                $invoice_cost = $agentleaddetail->commercial_tier2;
            }else{
                $invoice_cost = $agentleaddetail->commercial_tier3;
            }

            if (empty($agentleaddetail->broker_cost)){

                $agent_paid = (float) $leadclient->payment - $invoice_cost - (float) $agentleaddetail->broker_cost;
            }else{
                $agent_paid = ((float) $leadclient->payment - (float) $invoice_cost) * ((100 - (float) $agentleaddetail->broker_cost) / 100);

            }
        }

        
        $agent_paid     = (float) $agent_paid;

      /* New code added for agent paid amount */

      $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]));
              }
            }
          } 

          if((strpos($arr[$i],"Paid Out") > -1) || (strpos($arr[$i],"14") > -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]));
              }
            }
          }  
      }

      $dis=0;
      if($leadclient->status_history!=''){
          
          $getfirst=explode('~~~~',$leadclient->status_history);
          if($getfirst[0]!=''){

            $getdate  =   explode("~~",$getfirst[0]);
            //$getdate  =   explode("-",$getdate[0]); 
           
            $date1 = strtotime(date('Y-m-d'));  
            $date2 = strtotime(date('Y-m-d',strtotime($getdate[0])));  


            $diff         =   abs($date2 - $date1); 
            $statusdays   =   ceil($diff/ 86400); 
            $dis          =   $statusdays; 
          } 
      }

      if($leadclient->prop_id!=0 || $leadclient->prop_id!=''){
        
        if(trim($leadclient->commision)==""){
          $leadclient->commision=0;
        }

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

        if($leadclient->commision_unit=="1") {
           
            if ($leadclient->commision!=0 || $leadclient->commision!=0.00) {
                  
              $commision        =   (float) $leadclient->commision;
              $tot_com          =   ((float) $leadclient->rent_amount*((float) $commision/100));
              $total            =   (float) $tot_com+(float) $leadclient->bonus;
              $commision_unit   =   "%";
            }else{
              $total            = (float) $leadclient->bonus;
            }
        }else{
           
          $tot_com          =   (float) $leadclient->commision;
          $total            =   (float) $leadclient->commision+(float) $leadclient->bonus;
          $commision_unit   =   "Flat Fee";
        } 
      }else{

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

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

        if(trim($leadclient->house_bonus)==""){
          $leadclient->house_bonus=0;
        }   
            
        $total  =  ((float) $leadclient->sold_amt*((float) $leadclient->house_comm/100))+(float) $leadclient->house_bonus;
        $tot_com          =   0;
        $commision_unit   =   "Flat Fee";
      }


      $agent_invoice_cost =   (float) $leadclient->invoicing_cost;
      $paid_amt           =   (float) $leadclient->payment;
      $inc                =   (float) $leadclient->incentive;
      if(!empty($leadcalculatdata)){
        $lead_cost  = (float) $leadcalculatdata->lead_cost;
      }else{
        $lead_cost  = 0;
      }

      $user         =   User::find($leadclient->agent_id);
      $total_cost   =   (float)$agent_paid+(float)$leadclient->invoicing_cost;
      $net          =   (float)$paid_amt - (float)$inc -  (float)$lead_cost - (float)$leadclient->invoicing_cost ;

      $total        =   number_format((float)$total, 2, '.', '');
      $total_cost   =   number_format((float)$total_cost, 2, '.', '');
      $net          =   number_format((float)$net, 2, '.', '');

      if($total<0){
       $total='';
      }

      if($total_cost<0){
        $total_cost='';
      }

      if($net<0){
        $net='';
      }
    
      $data['agent_paid']   =   number_format((float) $agent_paid,2,'.','');
      $data['lead_cost']    =   number_format((float) $lead_cost,2,'.','');
      $data['paid_date']    =   $paid_rec;
      $data['paid_out']     =   $paid_out;
      $data['paidamount']   =   number_format((float) $total,2,'.','');
      $data['ledinvcast']   =   number_format((float) $total_cost,2,'.','');
      $data['netincome']    =   number_format((float) $net,2,'.','');
      $data['dis']          =   $dis;

      return $data;
  }



    /*
    *  @function_name: distributorsearch
    *  @params: Request data
    *  @return:  Json response
    *  @updatedBy: Chintesh k
    */
    public function distributorsearch(Request $request){

        $ser    =   $request->input('inputVal');
        $id     =   Auth::user()->id;
        $role   =   Auth::user()->user_role;

        if (strtotime($ser) !== false){
            $date = date('Y-m-d', strtotime($ser));
        }else{
            $date = '0000-00-00';
        }

        if ($role == AGENT){
            
            $pref = session('setAgentAdminPrefrence');

            if ($pref == 'fname'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client where lead_client.fname LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'lname'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client where lead_client.lname LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'phone1'){

                $students = \DB::select("select CONCAT('(',substr(lead_client.phone1,1,3),') ',substr(lead_client.phone1,4,3),'-',substr(lead_client.phone1,7)) As result from lead_client INNER JOIN users ON users.id =lead_client.agent_id  WHERE lead_client." . $pref . " LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'uname'){

                $students = \DB::select("select CONCAT(users.name) As result from users where name LIKE '%" . $ser . "%' ORDER BY  result ASC");

            }elseif ($pref == 'curr_status'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id where lead_client." . $pref . " LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'move_date'){

                $students = \DB::select("select CONCAT(DATE_FORMAT(move_date, '%m/%d/%Y')) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where move_date LIKE '%" . $date . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }else{
                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id where lead_client." . $pref . " LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
            }
        }elseif ($role == ARUSER){

            $pref = session('setAgentAdminPrefrence');

            if ($pref == 'fname'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client where lead_client.fname LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'lname'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client where lead_client.lname LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'uname'){

                $students = \DB::select("select CONCAT(users.name) As result from users where name LIKE '%" . $ser . "%' ORDER BY  result ASC");

            }elseif ($pref == 'phone1'){

                $students = \DB::select("select CONCAT('(',substr(lead_client.phone1,1,3),') ',substr(lead_client.phone1,4,3),'-',substr(lead_client.phone1,7)) As result from lead_client INNER JOIN users ON users.id =lead_client.agent_id  WHERE lead_client." . $pref . " LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'curr_status'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id where lead_client." . $pref . " LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'move_date'){

                $students = \DB::select("select CONCAT(DATE_FORMAT(move_date, '%m/%d/%Y')) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where move_date LIKE '%" . $date . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }else{
                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id where lead_client." . $pref . " LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
            }
        }elseif ($role == ADMIN){

            $pref = session('setAgentAdminPrefrence');

            if ($pref == 'fname'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client where lead_client.fname LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'lname'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client where lead_client.lname LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'uname'){

                $students = \DB::select("select CONCAT(users.name) As result from users where name LIKE '%" . $ser . "%' ORDER BY  result ASC");

            }elseif ($pref == 'phone1'){

                $students = \DB::select("select CONCAT('(',substr(lead_client.phone1,1,3),') ',substr(lead_client.phone1,4,3),'-',substr(lead_client.phone1,7)) As result from lead_client INNER JOIN users ON users.id =lead_client.agent_id  WHERE lead_client." . $pref . " LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'curr_status'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id where lead_client." . $pref . " LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'move_date'){

                $students = \DB::select("select CONCAT(DATE_FORMAT(move_date, '%m/%d/%Y')) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where move_date LIKE '%" . $date . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }else{
                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id where lead_client." . $pref . " LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
            }
        }else{

            $pref = session('setAgentAdminPrefrence');

            if ($pref == 'fname'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client where lead_client.fname LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'lname'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client where lead_client.lname LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'phone1'){

                $students = \DB::select("select CONCAT('(',substr(lead_client.phone1,1,3),') ',substr(lead_client.phone1,4,3),'-',substr(lead_client.phone1,7)) As result from lead_client INNER JOIN users ON users.id =lead_client.agent_id  WHERE lead_client." . $pref . " LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'uname'){

                $students = \DB::select("select CONCAT(users.name) As result from users where name LIKE '%" . $ser . "%' ORDER BY  result ASC");

            }elseif ($pref == 'curr_status'){

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id where lead_client." . $pref . " LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }elseif ($pref == 'move_date'){

                $students = \DB::select("select CONCAT(DATE_FORMAT(move_date, '%m/%d/%Y')) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where move_date LIKE '%" . $date . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");

            }else{
                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id where lead_client." . $pref . " LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
            }
        }

        if (sizeof($students) > 0){
            foreach ($students as $keyser => $valueser){
                echo '<p class="leadItems">' . $valueser->result . "</p>";
            }
        }else{
            echo "<p>No matches found</p>";
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }
    
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\model\Distributordashboard  $distributordashboard
     * @return \Illuminate\Http\Response
     */
    public function show(Distributordashboard $distributordashboard)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\model\Distributordashboard  $distributordashboard
     * @return \Illuminate\Http\Response
     */
    public function edit(Distributordashboard $distributordashboard)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\model\Distributordashboard  $distributordashboard
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Distributordashboard $distributordashboard)
    {
        //
    }

     /**
      * Remove the specified resource from storage.
      *
      * @param  int  $id
      * @return \Illuminate\Http\Response
      */
      public function destroyleadscraper($id){
          
        $istru = DB::table("lead_scraper")->delete($id);
        if($istru){
          Session::flash('message', 'delscraper');    
          Session::flash('alert-class', 'alert-success');  
        }else{

          Session::flash('message', 'delfscaper');   
          Session::flash('alert-class', 'alert-danger');
        } 
        return redirect('/lead-scraper');
      }
}
