<?php
namespace App\Http\Controllers;
use App\model\Leadclient;
use App\model\Property;
use App\Helper\helper;
use GuzzleHttp\Client;
use App\Helper\faxage;
use Illuminate\Http\Request;

use Session;
use DB;
use Mail;
use App\User;
use App\model\Agentemail;
use App\model\EmailLog;
use App\model\Distributorleadmarket;
use Auth;
use PDF;
use App\model\Company;
use App\model\CollectionDetails;
use App\model\VendorDetails;
use App\model\Leadclientcalculation;
use App\model\Leasstatus_history;
use App\modal\Flag_data;

use Validator;
use File;
use DateTime;

class LeadclientController extends Controller
{
    //private $faxage_api_url = "https://www.faxage.com/httpsfax.php";

    private $faxage_api_url = "https://api.faxage.com/httpsfax.php";
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    function migrate_email_list(){
        $new_admins = DB::table('admin')->where('old_id', '>', 0)
            ->get();
        foreach ($new_admins as $new_admin){
            DB::table('email_list')->where('old_id', '>', 0)
                ->where('agent_id', '=', $new_admin->old_id)
                ->update(['agent_id' => $new_admin->id]);
        }
    }

    function update_mgmt_co(){

        $companies = Company::where('mgmt_id', '!=', 0)->get();
        foreach ($companies as $company){
            Property::where('prop_mgmt_co', $company->mgmt_id)
                        ->update(['prop_mgmt_co' => $company->id]);
        }
    }

    function migrate_prop_id(){
        $leads = Property::where('prop_id', '>', 0)->get();
        foreach ($leads as $lead){
            Leadclient::where('lc_id', '>', 0)
                        ->where('prop_id', '=', $lead->prop_id)
                        ->update(['prop_id' => $lead->id]);
        }
    }

    function migrate_lead_status_history(){

        $leadstatuss = Leadclient::where('lc_id', '!=', 0)->get();
        foreach ($leadstatuss as $leadstatus){
            $leadclient = Leasstatus_history::where('lead_id', '=', $leadstatus->lc_id)
                                            ->update(['lead_id' => $leadstatus->id]);
        }
    }

    function update_lead_id_origin(){

        $leads      = Distributorleadmarket::where('lead_id', '!=', 0)
                                            ->where('id', '>=', 1)
                                            ->where('id', '<=', 5000)
                                            ->get();
    }

    function update_lead_status_history(){

        $leadclients = Leadclient::where('lc_id', '!=', 0)->get();
        foreach ($leadclients as $leadclient){

            $email_hist             = explode('~~~~', $leadclient->email_hist);
            $status_history         = explode('~~~~', $leadclient->status_history);
            $notes_history          = explode('~~~~', $leadclient->notes_history);
            $ar_notes_history       = explode('~~~~', $leadclient->ar_notes_history);

            $email_hist             = str_replace("/", '-', $leadclient->email_hist);
            $status_history         = str_replace("/", '-', $leadclient->status_history);
            $notes_history          = str_replace("/", '-', $leadclient->notes_history);
            $ar_notes_history       = str_replace("/", '-', $leadclient->ar_notes_history);

            Leadclient::where('id', $leadclient->id)
                ->update(['email_hist' => $email_hist, 'status_history' => $status_history, 'notes_history' => $notes_history, 'ar_notes_history' => $ar_notes_history]);
        }
    }
    /*
    *  @function_name:   index
    *  @params: Request data
    *  @return:  Json response
    *  @updatedBy: Chintesh k
    */    
    public function index(Request $request)
    {
      

        $id                 = Auth::user()->id;
        $user_role          = Auth::user()->user_role;
        $items              = $request->items??25;
        $role_for           = 'AGENT';
        Session::put('role_for', $role_for);
        $useraragent        = array();
        $statusarry         = ['New', 'Repeat', 'Prospect', 'Hot', 'Warm', 'Pending', 'Lease Confirmed', 'Invoiced','1','2','3','4','5','8','10','12','7'];
        //$statusarry         = ['New', 'Repeat', 'Prospect', 'Hot', 'Warm', 'Cold', 'WOT', 'Pending','Sold', 'Lease Confirmed', 'MIC', 'Invoiced', 'Pay Received', 'Paid Out', 'Write Off', 'Under Contract','Verifying Lease'];
        $agent_id           = $id;
        $email_id           = $id;
        $pref               = '';

        if (!session('setAgentAdminPrefrence')){
            Session::put('setAgentAdminPrefrence', $pref);
        }else{
            $pref = session('setAgentAdminPrefrence');
        }
        
        
        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', 'users.id', '=', 'lead_client.agent_id')
                                        ->leftJoin('property', 'property.id', '=', 'lead_client.prop_id')
                                        ->select('lead_client.*', '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'))
                             ->orWhere('lead_client.curr_status', 'LIKE', get_status_id(session('leadsearchresult')))
                                ->orderBy($pref, 'ASC');
                           });
            }else if ($pref == "contact_nxt_date"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                $query->select('*')
                                                    ->orWhere('lead_client.curr_status', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                    ->orWhere('lead_client.contact_nxt_date', 'LIKE', '%' . $date . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "move_date"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                $query->select('*')
                                                    ->orWhere('lead_client.curr_status', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                    ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "fname"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                    $query->select('*')
                                                        ->orWhere('lead_client.fname', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                        ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                        ->orderBy($pref, 'ASC');
                                                    });
            }else if ($pref == "lname"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                    $query->select('*')
                                                        ->orWhere('lead_client.lname', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                        ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                        ->orderBy($pref, 'ASC');
                                                    });
            }else if ($pref == "email"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                $query->select('*')
                                                    ->orWhere('lead_client.email', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                    ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                    ->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('property.prop_phone', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                            ->orWhere('lead_client.title_phone', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                            ->orWhere('lead_client.phone1', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                            ->orWhere('lead_client.contact_nxt_date', 'LIKE', '%' . $date . '%')->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                            ->orderBy($pref, 'ASC');
                                    });
            }
        }else{

            $leadclients        =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name')
                                        //->whereIn('curr_status', $statusarry)
                                        ->where(function ($query){
                                            $query->select('*')
                                                ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                               ->orWhereNull('lead_client.contact_nxt_date');
                                        });
                                        
                                        //echo "Hello"; exit;
        }

        if ($user_role == SUPERADMIN){

            $users = User::select('id')->where('user_role', AGENT);
            //$leadclients = $leadclients->whereIn('agent_id', $users);
             $leadclients = $leadclients->whereIn('agent_id', $users)->whereIn('curr_status', $statusarry);
        }elseif ($user_role == ADMIN){

            $users = User::select('id')->where('create_by_user', $id)->where('user_role', AGENT);
           // $leadclients = $leadclients->whereIn('agent_id', $users);
           
           
            $leadclients = $leadclients->whereIn('agent_id', $users)->whereIn('curr_status', $statusarry);
            
            
            
           
        }elseif ($user_role == ARUSER){

            $users = User::select('id')->where('assign_to_ar', $id)->where('user_role', AGENT);
            //$leadclients = $leadclients->whereIn('agent_id', $users);
             $leadclients = $leadclients->whereIn('agent_id', $users)->whereIn('curr_status', $statusarry);
        }else{
            //echo $id; exit;
            
            
            $leadclients = $leadclients->where('agent_id', '=', $id);
           
        }
        
        $sort       = isset($request->sort) ? $request->sort : 'curr_status';
        $direction  = isset($request->direction) ? $request->direction : 'ASC';
    
    
        //if($sort=="contact_nxt_date"){
          
          
            //if($request == 'ARUSER'){
            //  $leadclients  =   $leadclients->orderby( 'lead_client.ar_contact_date_next',$direction);
          
           // }
          
            //if($request == 'AGENT'){
            //   $leadclients  =   $leadclients->orderby( 'lead_client.contact_nxt_date',$direction);
            //}
          
          
        //}else{
            $leadclients  =   $leadclients->orderby('lead_client.'.$sort ,$direction);
       // }
        

   // DB::enableQueryLog();
    $leadclients = $leadclients->paginate($items);
    //dd(DB::getQueryLog());exit;            
                                    
    //   if (Auth::User()->user_role == "3"){
    //         $current_status =  DB::table('lead_status')
    //                             ->select('id', 'status_name')
    //                             ->where('status', '=', 1)->whereNotIn('id', [16,17])->orderBy('position', 'ASC')
    //                             ->get();
                                
    //     }else{
    //         $current_status =  DB::table('lead_status')
    //                             ->select('id', 'status_name')
    //                             ->where('status', '=', 1)->orderBy('position', 'ASC')
    //                             ->get(); 
    //     }
    
        
        if (Auth::User()->user_role == "3" && empty(Auth::User()->manage_manager)){
            $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1)
           // ->whereNotIn('id', [11,12,13,14,15])
            ->orderBy('position', 'ASC')
            ->get(); 
        }else if (Auth::User()->user_role == "3" && Auth::User()->manage_manager==1){
             $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1) 
            ->orderBy('position', 'ASC')
            ->get();
        } else{
            $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1) 
          
            ->orderBy('position', 'ASC')
            ->get();
        }
         //  echo"<pre>"; print_r($leadclients);  exit;                                 
        return view('leadclient.index', [
            'current_status'        =>  $current_status, 
            'manager'               =>  0, 
            'edit_table'            =>  1, 
            'agent_id'              =>  $agent_id, 
            'AgentAdminPrefrence'   =>  $pref, 
            'agentemailcreate'      =>  Agentemail::where('agent_id', '=', $email_id)
                                                ->where('status', '=', 1)
                                                ->orderBy('email_name', 'ASC')
                                                ->get(),
            'user_role'             =>  $user_role, 
            'arlead'                =>  0, 
            'usersagent'            =>  $useraragent, 
            'role_for'              =>  $role_for, 
            'show_table'            =>  1
        ], compact('leadclients'))->withMembers($leadclients)->withItems($items);
    }


    /*
    *  @function_name:   indexboxtype
    *  @params: Request data
    *  @return:  Json response
    *  @updatedBy: Chintesh k
    */    
    public function indexboxtype($boxtype, Request $request)
    {
         //print_r($boxtype); exit;
        $id                 = Auth::user()->id;
        $user_role          = Auth::user()->user_role;
        $items              = $request->items??25;
        $role_for           = 'AGENT';
        $useraragent        = array();
        $agent_id           = $id;
        $email_id           = $id;
        $pref               = '';
        Session::put('role_for', $role_for);

        if ($boxtype == 'LEADS'){
            $statusarry = ['New', 'Repeat','1'];
        }elseif ($boxtype == 'PENDING'){
            //$statusarry = ['Pending', 'MIC', 'Lease Confirmed','Under Contract','Verifying Lease','7','10','11','16','17'];
            $statusarry = ['Pending','Lease Confirmed','Under Contract','Verifying Lease','10','8','16','17'];
        }elseif ($boxtype == 'SOLDS'){
            $statusarry = ['Sold','9'];
        }elseif ($boxtype == 'FOLLOW'){
            $statusarry = ['New','Repeat','Prospect','Hot','Warm','1','2','3','4','5'];
        }elseif ($boxtype == 'INVOICES'){
            $statusarry = ['Invoiced','12'];
        }elseif ($boxtype == 'PAY-RECIEVED'){
            $statusarry = ['Pay Received','13'];
        }elseif ($boxtype == 'MOVE-INS'){
            $statusarry = ['Lease Confirmed','10'];
        }elseif ($boxtype == 'CONTRACT'){
            $statusarry = ['Under Contract','16'];
        }elseif ($boxtype == 'VERIFYLEASE'){
            $statusarry = ['Verifying Lease','17'];
        }else{
            $statusarry = ['New', 'Repeat', 'Prospect', 'Hot', 'Warm', 'Pending', 'Lease Confirmed', 'Invoiced','1','2','3','4','5','7','10','12'];
        }

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

        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', 'users.id', '=', 'lead_client.agent_id')
                                        ->leftJoin('property', 'property.id', '=', 'lead_client.prop_id')
                                        ->select('lead_client.*', '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('*')
                                                ->orWhere('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'))
                                    ->orWhere('lead_client.curr_status', 'LIKE', get_status_id(session('leadsearchresult')))
                                        ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "contact_nxt_date"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                $query->select('*')
                                                    ->where('lead_client.contact_nxt_date', 'LIKE', '%' . $date . '%')
                                                    ->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 == "fname"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                    $query->select('*')
                                                        ->orWhere('lead_client.fname', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                        ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                        ->orderBy($pref, 'ASC');
                                                    });
            }else if ($pref == "lname"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                    $query->select('*')
                                                        ->orWhere('lead_client.lname', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                        ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                        ->orderBy($pref, 'ASC');
                                                    });
            }else if ($pref == "email"){
                $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                $query->select('*')
                                                    ->orWhere('lead_client.email', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                    ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                    ->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('property.prop_phone', 'LIKE', '%' . session('leadsearchresult') . '%')
                                            ->orWhere('lead_client.title_phone', 'LIKE', '%' . session('leadsearchresult') . '%')
                                            ->orWhere('lead_client.phone1', 'LIKE', '%' . session('leadsearchresult') . '%')
                                            ->orWhere('lead_client.title_officer', 'LIKE', '%' . Session('leadsearchresult') . '%')
                                            ->orWhere('lead_client.contact_nxt_date', 'LIKE', '%' . $date . '%')->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')->orderBy($pref, 'ASC');
                                    });
            }
        }else{

            if($boxtype == 'FOLLOW'){

                $leadclients        =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name')
                                        ->whereIn('curr_status', $statusarry)
                                        ->where(function ($query){
                                            $query->select('*')
                                               ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                                ->orwhereNull('lead_client.contact_nxt_date');
                                        });
            }else if($boxtype == 'PENDING'){
                $leadclients        =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name')
                                        ->whereIn('curr_status', $statusarry);
            }else if($boxtype == 'INVOICES'){
                $leadclients        =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name')
                                        ->whereIn('curr_status', $statusarry);
            }else if($boxtype == 'SOLDS'){
                $leadclients        =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name')
                                        ->whereIn('curr_status', $statusarry);
            }else{
                $leadclients        =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name')
                                        ->whereIn('curr_status', $statusarry)
                                        ->where(function ($query){
                                            $query->select('*')
                                                ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                                ->orWhereNull('lead_client.contact_nxt_date');
                                        });
            }
        }

        if ($user_role == SUPERADMIN)
        {
            $users = User::select('id')->where('user_role', AGENT);
            $leadclients = $leadclients->whereIn('agent_id', $users);
        }elseif ($user_role == ADMIN){
            $users = User::select('id')->where('create_by_user', $id)->where('user_role', AGENT);
            $leadclients = $leadclients->whereIn('agent_id', $users);
        }elseif ($user_role == ARUSER){
            $users = User::select('id')->where('assign_to_ar', $id)->where('user_role', AGENT);
            $leadclients = $leadclients->whereIn('agent_id', $users);
        }else{

            $leadclients = $leadclients->where('agent_id', '=', $id);
        }

     //DB::enableQueryLog();

        $leadclients = $leadclients->orderBy('curr_status', 'ASC')
                                    ->sortable()
                                    ->paginate($items);
  //dd(DB::getQueryLog()); exit;
        return view('leadclient.index', [
            'current_status'        =>  DB::table('lead_status')
                                            ->select('id', 'status_name','new_status_name')
                                            ->where('status', '=', 1)->orderBy('position', 'ASC')
                                            ->get() , 
            'manager'               =>  0, 
            'edit_table'            =>  1, 
            'agent_id'              =>  $agent_id, 
            'AgentAdminPrefrence'   =>  $pref, 
            'agentemailcreate'      =>  Agentemail::where('agent_id', '=', $email_id)
                                                ->where('status', '=', 1)
                                                ->orderBy('email_name', 'ASC')
                                                ->get() , 
            'user_role'             =>  $user_role, 
            'arlead'                =>  0, 
            'usersagent'            =>  $useraragent, 
            'role_for'              =>  $role_for, 
            'show_table'            =>  1
        ], compact('leadclients'))->withMembers($leadclients)->withItems($items);
    }
    

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function setAgentAdminPrefrence(Request $request)
    {
        $pref = $request->input('pref');
        Session::put('setAgentAdminPrefrence', $pref);
        echo 'success';
    }
    /*
    *  @function_name:   leadsearch
    *  @params: Request data
    *  @return:  Json response
    *  @updatedBy: Chintesh k
    */
    
   
    public function leadsearch(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){
            // echo $role; exit;
            $pref = session('setAgentAdminPrefrence');

            if ($pref == 'contact_nxt_date'){

                $students = \DB::select("select CONCAT(DATE_FORMAT(contact_nxt_date, '%m/%d/%Y')) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where contact_nxt_date LIKE '%" . $date . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
            }elseif ($pref == "phone1"){
    
                //$students = \DB::select("select CONCAT('(',substr(lead_client.phone1,0,3),') ',substr(lead_client.phone1,3,3),'-',substr(lead_client.phone1,6)) 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");
        
                $students = \DB::select("select lead_client.phone1 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 == '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");
            }elseif($pref == 'curr_status'){
                $students = \DB::select("SELECT CONCAT(lead_status.new_status_name) AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id  INNER JOIN lead_status on lead_client.curr_status = lead_status.id where lead_status.new_status_name LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
                if(sizeof($students) == 0)
                {
                    $students = \DB::select("SELECT CONCAT(lead_status.status_name) AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id  INNER JOIN lead_status on lead_client.curr_status = lead_status.id where lead_status.status_name LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
                }
            }else{
                if($pref=='prop_phone'){
                   $pref='phone1';
                }else{
                    $pref=$pref;
                }
                
                
                $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 == 'id'){

                $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 . "%' AND users.assign_to_ar=" . $id . " GROUP BY lead_client." .$pref. " ORDER BY lead_client." .$pref. " ASC");

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

                $students = \DB::select("select CONCAT(property." . $pref . ") As result from property INNER JOIN lead_client ON lead_client.prop_id =property.id INNER JOIN users ON users.id=lead_client.agent_id WHERE property." . $pref . " LIKE '" . $ser . "%' UNION select CONCAT(house_add) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where house_add LIKE '" . $ser . "%' ORDER BY  result ASC");

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

                $students = \DB::select("select lead_client.phone1 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 == 'prop_phone'){

                $students = \DB::select("select  DISTINCT CONCAT('(',substr(property." . $pref . ",0,3),') ',substr(property." . $pref . ",3,3),'-',substr(property." . $pref . ",6)) As result from property INNER JOIN lead_client ON lead_client.prop_id =property.id INNER JOIN users ON users.id=lead_client.agent_id WHERE property." . $pref . " LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' UNION ALL select  DISTINCT CONCAT('(',substr(lead_client.title_phone,0,3),') ',substr(lead_client.title_phone,3,3),'-',substr(lead_client.title_phone,6)) As result from lead_client  WHERE lead_client.title_phone LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' UNION ALL select  DISTINCT CONCAT('(',substr(lead_client.phone1,0,3),') ',substr(lead_client.phone1,3,3),'-',substr(lead_client.phone1,6)) As result from lead_client  WHERE lead_client.phone1 LIKE '%" . preg_replace("/[^0-9.]/", "", $ser)."%'");

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

                $students = \DB::select("select CONCAT(property.prop_manager) As result from property INNER JOIN lead_client ON lead_client.prop_id =property.id INNER JOIN users ON users.id=lead_client.agent_id WHERE property.prop_manager LIKE '" . $ser . "%' AND users.assign_to_ar=" . $id . " UNION select CONCAT(title_officer) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where title_officer LIKE '" . $ser . "%' AND users.assign_to_ar=" . $id . " ORDER BY result ASC");

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

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

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

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

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

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

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

                $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 . "%' AND users.assign_to_ar=" . $id . " GROUP BY lead_client." .$pref. " ORDER BY lead_client." .$pref. " ASC");

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

                $students = \DB::select("select CONCAT(DATE_FORMAT(start_date, '%m/%d/%Y')) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where start_date LIKE '%" . $date . "%' UNION select CONCAT(DATE_FORMAT(close_date, '%m/%d/%Y')) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where close_date LIKE '%" . $date . "%'  ORDER BY result ASC");
            }elseif($pref == 'curr_status'){
                $students = \DB::select("SELECT CONCAT(lead_status.new_status_name) AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id  INNER JOIN lead_status on lead_client.curr_status = lead_status.id where lead_status.new_status_name LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
                if(sizeof($students) == 0)
                {
                    $students = \DB::select("SELECT CONCAT(lead_status.status_name) AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id  INNER JOIN lead_status on lead_client.curr_status = lead_status.id where lead_status.status_name LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
                }
            }else{
                if($pref=='prop_phone'){
                   $pref='phone1';
                }else{
                    $pref=$pref;
                }
                
                
                $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 . "%' AND users.assign_to_ar=" . $id . " GROUP BY lead_client." .$pref. " ORDER BY lead_client." .$pref. " ASC");
            }
        }elseif ($role == ADMIN){
    
            $pref = session('setAgentAdminPrefrence');
            
          

            if ($pref == 'id'){

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

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

                $students = \DB::select("select CONCAT(property." . $pref . ") As result from property INNER JOIN lead_client ON lead_client.prop_id =property.id INNER JOIN users ON users.id=lead_client.agent_id WHERE property." . $pref . " LIKE '" . $ser . "%' UNION select CONCAT(house_add) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where house_add LIKE '" . $ser . "%' ORDER BY  result ASC");

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

                $students = \DB::select("select  DISTINCT CONCAT('(',substr(property." . $pref . ",0,3),') ',substr(property." . $pref . ",3,3),'-',substr(property." . $pref . ",6)) As result from property INNER JOIN lead_client ON lead_client.prop_id =property.id INNER JOIN users ON users.id=lead_client.agent_id WHERE property." . $pref . " LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' UNION ALL select  DISTINCT CONCAT('(',substr(lead_client.title_phone,0,3),') ',substr(lead_client.title_phone,3,3),'-',substr(lead_client.title_phone,6)) As result from lead_client  WHERE lead_client.title_phone LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' UNION ALL select  DISTINCT CONCAT('(',substr(lead_client.phone1,0,3),') ',substr(lead_client.phone1,3,3),'-',substr(lead_client.phone1,6)) As result from lead_client  WHERE lead_client.phone1 LIKE '%" . preg_replace("/[^0-9.]/", "", $ser)."%'");

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

                $students = \DB::select("select lead_client.phone1 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 == 'contact_nxt_date'){

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

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

                $students = \DB::select("select CONCAT(DATE_FORMAT(ar_contact_date_next, '%m/%d/%Y')) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where ar_contact_date_next LIKE '%" . $date . "%' 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");

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

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

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

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

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

                $students = \DB::select("select CONCAT(property.prop_manager) As result from property  WHERE property.prop_manager LIKE '%" . $ser . "%' UNION select CONCAT(title_officer) As result from lead_client  where title_officer LIKE '%" . $ser . "%' ORDER BY result ASC");
            }elseif($pref == 'curr_status'){
                $students = \DB::select("SELECT CONCAT(lead_status.new_status_name) AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id  INNER JOIN lead_status on lead_client.curr_status = lead_status.id where lead_status.new_status_name LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
                if(sizeof($students) == 0)
                {
                    $students = \DB::select("SELECT CONCAT(lead_status.status_name) AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id  INNER JOIN lead_status on lead_client.curr_status = lead_status.id where lead_status.status_name LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
                }
            }else{
                if($pref=='prop_phone'){
                   $pref='phone1';
                }else{
                    $pref=$pref;
                }
                  //echo $pref; exit;
                $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 == 'id'){

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

                $students = \DB::select("select CONCAT(property." . $pref . ") As result from property INNER JOIN lead_client ON lead_client.prop_id =property.id INNER JOIN users ON users.id=lead_client.agent_id WHERE property." . $pref . " LIKE '" . $ser . "%' UNION select CONCAT(house_add) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where house_add LIKE '" . $ser . "%' ORDER BY  result ASC");

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

                $students = \DB::select("select  lead_client.phone1 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 == "title_phone"){

                $students = \DB::select("select  DISTINCT CONCAT('(',substr(lead_client.title_phone,0,3),') ',substr(lead_client.title_phone,3,3),'-',substr(lead_client.title_phone,6)) 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 == 'prop_phone'){

                /* match title_phone, prop_phone, phone1 */
                $students = \DB::select("select  DISTINCT CONCAT('(',substr(property." . $pref . ",0,3),') ',substr(property." . $pref . ",3,3),'-',substr(property." . $pref . ",6)) As result from property INNER JOIN lead_client ON lead_client.prop_id =property.id INNER JOIN users ON users.id=lead_client.agent_id WHERE property." . $pref . " LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' UNION ALL select  DISTINCT CONCAT('(',substr(lead_client.title_phone,0,3),') ',substr(lead_client.title_phone,3,3),'-',substr(lead_client.title_phone,6)) As result from lead_client  WHERE lead_client.title_phone LIKE '%" . preg_replace("/[^0-9.]/", "", $ser) . "%' UNION ALL select  DISTINCT CONCAT('(',substr(lead_client.phone1,0,3),') ',substr(lead_client.phone1,3,3),'-',substr(lead_client.phone1,6)) As result from lead_client  WHERE lead_client.phone1 LIKE '%" . preg_replace("/[^0-9.]/", "", $ser)."%'");

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

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

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

                $students = \DB::select("select CONCAT(DATE_FORMAT(ar_contact_date_next, '%m/%d/%Y')) As result from lead_client INNER JOIN users ON users.id=lead_client.agent_id where ar_contact_date_next LIKE '%" . $date . "%' 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");

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

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

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

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

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

                $students = \DB::select("SELECT CONCAT(lead_client." . $pref . ") AS result from lead_client where lead_client." . $pref . " LIKE '" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
            }elseif($pref == 'curr_status'){
                $students = \DB::select("SELECT CONCAT(lead_status.new_status_name) AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id  INNER JOIN lead_status on lead_client.curr_status = lead_status.id where lead_status.new_status_name LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
                if(sizeof($students) == 0)
                {
                    $students = \DB::select("SELECT CONCAT(lead_status.status_name) AS result from lead_client INNER JOIN users ON users.id = lead_client.agent_id  INNER JOIN lead_status on lead_client.curr_status = lead_status.id where lead_status.status_name LIKE '%" . $ser . "%' GROUP BY lead_client." . $pref . " ORDER BY lead_client." . $pref . " ASC");
                }
            }else{
                
                if($pref=='prop_phone'){
                   $pref='phone1';
                }else{
                    $pref=$pref;
                }
                $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){
            $i=1;
            foreach ($students as $keyser => $valueser){
                
                if($i==1){
                    $class="leadItems selecteder";
                }else{
                    $class="leadItems";
                }
                echo '<p class="'.$class.'">' . $valueser->result . "</p>";
                $i++;
            }
        }else{
            echo "<p>No matches found</p>";
        }
    }
    

    /*
    *  @function_name:   aragentsearch
    *  @params: Request data
    *  @return:  Json response
    *  @updatedBy: Chintesh k
    */
    public function aragentsearch(Request $request)
    {
        $id     =   Auth::user()->id;
        $ser    =   $request->input('inputVal');

        $students = \DB::select("SELECT CONCAT(name) As result from users WHERE name LIKE '" . $ser . "%' UNION select CONCAT (last_name) AS result from users where last_name LIKE '" . $ser . "%' UNION SELECT CONCAT(email) As result from users WHERE email LIKE '" . $ser . "%' AND assign_to_ar=" . $id . " ORDER BY result ASC");

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

    public function setleadresult(Request $request){

        $agenrt_id = $request->input('arnameemail');
        Session::put('leadsearchresult', $agenrt_id);
        echo 'success';
    }

    public function unsetleadresult(Request $request)
    {
        $agenrt_id = $request->input('arnameemail');

        Session::forget('agentsearchresult');
        Session::forget('leadsearchresult');
        echo 'success';
    }

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

        $id                 =   Auth::user()->id;
        $manager            =   Auth::user()->manage_manager;
        $user_role          =   Auth::user()->user_role;
        $manager_agent      =   Auth::user()->agents_to_manager;
        $agents             =   explode(',', $manager_agent);
        $items              =   $request->items??25;
        $role_for           =   '';

        Session::put('role_for', $role_for);

        $statusarry         =   ['New','Repeat', 'Prospect', 'Hot', 'Warm', 'Pending','Paid Out','1','2','3','4','5','7','14'];
        
        if ($user_role == SUPERADMIN || ($user_role == AGENT || $manager == 1)){

            $role_for = 'AGENT';

            if (!empty($agents) && $agents[0] != 0){
                $useraragent    =   User::where('user_role', '=', AGENT)
                                        ->whereIn('id', $agents)
                                        ->where('status', '=', 1)
                                        ->get();

                if (session('aragentsearch') == ''){
                    $firstuser = $useraragent->first();
                    if ((isset($firstuser->id)) && $firstuser->id != ''){
                        Session::put('aragentsearch', $firstuser->id);
                    }
                }

                $pref = '';

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

                if (session('leadsearchresult') != ''){
                    
                    if (strtotime(Session('leadsearchresult')) !== false){
                        $date = date('Y-m-d', strtotime(Session('leadsearchresult')));
                    }else{
                        $date = '0000-00-00';
                    }
                    $leadclients    =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                                ->leftJoin('property', 'property.id', '=', 'lead_client.prop_id')
                                                ->select('lead_client.*', '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('*')
                                                ->orWhere('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'))
                                        ->orWhere('lead_client.curr_status', 'LIKE', get_status_id(session('leadsearchresult')))
                                        ->orderBy($pref, 'ASC');
                                                        });

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

                    }else if ($pref == "email"){
                        $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                $query->select('*')
                                                    ->orWhere('lead_client.email', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                    ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                    ->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('property.prop_phone', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                ->orWhere('lead_client.title_phone', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                ->orWhere('lead_client.phone1', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                ->orWhere('lead_client.title_officer', 'LIKE', '%' . Session('leadsearchresult') . '%')
                                ->orWhere('lead_client.contact_nxt_date', 'LIKE', '%' . $date . '%')->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')->orderBy($pref, 'ASC');
                            });
                    }
                }else{

                    $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                                ->select('lead_client.*', 'users.name', 'users.last_name')
                                                ->whereIn('curr_status', $statusarry)
                                                ->where(function ($query){
                                                    $query->select('*')
                                                        ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                                        ->orWhereNull('lead_client.contact_nxt_date');
                                                });

                }

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

                    $agent_id       =   session('aragentsearch');
                    $id             =   $agent_id;
                    $email_id       =   $agent_id;
                    $leadclients    =   $leadclients->where('agent_id', '=', session('aragentsearch'))
                        ->where(function ($query){
                            $query->select('*')
                                ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                ->orWhereNull('lead_client.contact_nxt_date');
                            })
                        ->sortable()
                        ->paginate($items);
                    $agent_id = session('aragentsearch');
                }else{

                    $agent_id       = 0;
                    $email_id       = 0;
                    $leadclients    = $leadclients->where('users.assign_to_ar', '=', $id)
                        ->where(function ($query){
                            $query->select('*')
                                ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                ->orWhereNull('lead_client.contact_nxt_date');
                            })
                        ->sortable()
                        ->paginate($items);
                }

                return view('manager.index', [
                    'current_status'    =>  DB::table('lead_status')
                                                ->select('id', 'status_name','new_status_name')
                                                ->where('status', '=', 1)->orderBy('position', 'ASC')
                                                ->get() , 
                    'edit_table'        =>  1, 
                    'manager'           =>  $manager, 
                    'agentemailcreate'  =>  Agentemail::where('agent_id', '=', Auth::user()->id)
                                                        ->where('status', '=', 1)
                                                        ->orderBy('email_name', 'ASC')
                                                        ->get() , 
                    'user_role'         =>  $user_role, 
                    'arlead'            =>  0, 
                    'agent_id'          =>  $agent_id, 
                    'usersagent'        =>  $useraragent, 
                    'role_for'          =>  $role_for
                ], compact('leadclients'))->withMembers($leadclients)->withItems($items);
            }else{
                return redirect('/');
            }
        }else{
            return redirect('/');
        }
    }


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

        $id                 = Auth::user()->id;
        $manager            = Auth::user()->manage_manager;
        $user_role          = Auth::user()->user_role;
        $manager_agent      = Auth::user()->agents_to_manager;
        $agents             = explode(',', $manager_agent);
        $items              = $request->items??25;
        $role_for           = '';

        Session::put('role_for', $role_for);

        if ($boxtype == 'LEADS'){
            $statusarry = ['New', 'Repeat','1','2'];
        }elseif ($boxtype == 'PENDING'){
            $statusarry = ['Pending', 'MIC', 'Lease Confirmed','7','10','11'];
        }elseif ($boxtype == 'SOLDS'){
            $statusarry = ['Sold','9'];
        }elseif ($boxtype == 'FOLLOW'){
            $statusarry = ['New','Repeat','Prospect','Hot','Warm','1','2','3','4','5'];
        }elseif ($boxtype == 'INVOICES'){
            $statusarry = ['Invoiced','12'];
        }elseif ($boxtype == 'PAY-RECIEVED'){
            $statusarry = ['Pay Received','13'];
        }elseif ($boxtype == 'MOVE-INS'){
            $statusarry = ['Lease Confirmed','10'];
        }else{
            $statusarry = ['New', 'Repeat', 'Prospect', 'Hot', 'Warm', 'Pending','Paid Out', 'Lease Confirmed', 'Invoiced','1','2','3','4','5','7','10','12','14'];
        }
        
        if ($user_role == SUPERADMIN || ($user_role == AGENT || $manager == 1)){

            $role_for = 'AGENT';

            if (!empty($agents) && $agents[0] != 0){
                $useraragent    =   User::where('user_role', '=', AGENT)
                                        ->whereIn('id', $agents)
                                        ->where('status', '=', 1)
                                        ->get();

                if (session('aragentsearch') == ''){
                    $firstuser = $useraragent->first();
                    if ((isset($firstuser->id)) && $firstuser->id != ''){
                        Session::put('aragentsearch', $firstuser->id);
                    }
                }

                $pref                   = '';

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

                if (session('leadsearchresult') != ''){
                    
                    if (strtotime(Session('leadsearchresult')) !== false){
                        $date = date('Y-m-d', strtotime(Session('leadsearchresult')));
                    }else{
                        $date = '0000-00-00';
                    }
                    $leadclients    =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                                ->leftJoin('property', 'property.id', '=', 'lead_client.prop_id')
                                                ->select('lead_client.*', '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('*')
                                                                ->orWhere('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'))
                                        ->orWhere('lead_client.curr_status', 'LIKE', get_status_id(session('leadsearchresult')))
                                                            ->orderBy($pref, 'ASC');
                                                        });

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

                    }else if ($pref == "email"){
                        $leadclients    =   $leadclients->where(function ($query) use ($date, $pref){
                                                        $query->select('*')
                                                            ->orWhere('lead_client.email', 'LIKE', '%' . session('leadsearchresult') . '%')
                                                            ->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')
                                                            ->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('property.prop_phone', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                ->orWhere('lead_client.title_phone', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                ->orWhere('lead_client.phone1', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('leadsearchresult')) . '%')
                                ->orWhere('lead_client.title_officer', 'LIKE', '%' . Session('leadsearchresult') . '%')
                                ->orWhere('lead_client.contact_nxt_date', 'LIKE', '%' . $date . '%')->orWhere('lead_client.move_date', 'LIKE', '%' . $date . '%')->orderBy($pref, 'ASC');
                            });
                    }
                }else{

                    if($boxtype == 'FOLLOW'){

                        $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                                ->select('lead_client.*', 'users.name', 'users.last_name')
                                                ->whereIn('curr_status', $statusarry)
                                                ->where(function ($query){
                                                    $query->select('*')
                                                        ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                                        ->orWhereNull('lead_client.contact_nxt_date');
                                                });
                    }else if($boxtype == 'PENDING'){
                        $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                                ->select('lead_client.*', 'users.name', 'users.last_name')
                                                ->whereIn('curr_status', $statusarry);
                    }else if($boxtype == 'INVOICES'){
                        $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                                ->select('lead_client.*', 'users.name', 'users.last_name')
                                                ->whereIn('curr_status', $statusarry);
                    }else if($boxtype == 'SOLDS'){
                        $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                                ->select('lead_client.*', 'users.name', 'users.last_name')
                                                ->whereIn('curr_status', $statusarry);
                    }else{
                        $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                                ->select('lead_client.*', 'users.name', 'users.last_name')
                                                ->whereIn('curr_status', $statusarry)
                                                ->where(function ($query){
                                                    $query->select('*')
                                                        ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                                        ->orWhereNull('lead_client.contact_nxt_date');
                                                });
                    }
                }

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

                    $agent_id       =   session('aragentsearch');
                    $id             =   $agent_id;
                    $email_id       =   $agent_id;
                    $leadclients    =   $leadclients->where('agent_id', '=', session('aragentsearch'))
                        ->where(function ($query){
                            $query->select('*')
                                ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                ->orWhereNull('lead_client.contact_nxt_date');
                            })
                        ->sortable()
                        ->paginate($items);
                    $agent_id = session('aragentsearch');
                }else{

                    $agent_id       = 0;
                    $email_id       = 0;
                    $leadclients    = $leadclients->where('users.assign_to_ar', '=', $id)
                        ->where(function ($query){
                            $query->select('*')
                                ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                ->orWhereNull('lead_client.contact_nxt_date');
                            })
                        ->sortable()
                        ->paginate($items);
                }

                /*if (session('aragentsearch') != ''){

                    $agent_id       =   session('aragentsearch');
                    $id             =   $agent_id;
                    $email_id       =   $agent_id;
                    $leadclients    =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                        ->select('lead_client.*', 'users.name', 'users.last_name')
                        ->where('agent_id', '=', session('aragentsearch'))
                        ->where(function ($query){
                            $query->select('*')
                                ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                ->orWhereNull('lead_client.contact_nxt_date');
                            })
                        ->sortable()
                        ->paginate($items);
                    $agent_id = session('aragentsearch');
                }else{

                    $agent_id = 0;
                    $email_id = 0;
                    $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')->select('lead_client.*', 'users.name', 'users.last_name')
                        ->where('users.assign_to_ar', '=', $id)
                        ->where(function ($query){
                            $query->select('*')
                                ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                ->orWhereNull('lead_client.contact_nxt_date');
                            })
                        ->sortable()
                        ->paginate($items);
                }*/

                return view('manager.index', [
                    'current_status'    =>  DB::table('lead_status')
                                                ->select('id', 'status_name','new_status_name')
                                                ->where('status', '=', 1)->orderBy('position', 'ASC')
                                                ->get() , 
                    'edit_table'        =>  1, 
                    'manager'           =>  $manager, 
                    'agentemailcreate'  =>  Agentemail::where('agent_id', '=', Auth::user()->id)
                                                        ->where('status', '=', 1)
                                                        ->orderBy('email_name', 'ASC')
                                                        ->get() , 
                    'user_role'         =>  $user_role, 
                    'arlead'            =>  0, 
                    'agent_id'          =>  $agent_id, 
                    'usersagent'        =>  $useraragent, 
                    'role_for'          =>  $role_for
                ], compact('leadclients'))->withMembers($leadclients)->withItems($items);
            }else{
                return redirect('/');
            }
        }else{
            return redirect('/');
        }
    }


    public function leadclientresult($status, $id, Request $request)
    {

        $user           = User::find($id);
        $user_role      = $user->user_role;
        $role_for       = '';
        $items          = $request1->items ?? 25;
        $sort           = isset($request1->sort) ? $request1->sort : 'curr_status';
        $direction      = isset($request1->direction) ? $request1->direction : 'ASC';

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

        if ($status == 'LEADS'){
            $statusarry = ['New', 'Repeat','1','2'];
        }elseif ($status == 'PENDING'){
            $statusarry = ['Pending', 'MIC', 'Lease Confirmed','7','10','11'];
        }elseif ($status == 'SOLDS'){
            $statusarry = ['Sold','9'];
        }elseif ($status == 'FOLLOW'){
            $statusarry = ['New','Repeat','Prospect','Hot','Warm','Pending','1','2','3','4','5','7'];
        }elseif ($status == 'INVOICES'){
            $statusarry = ['Invoiced','12'];
        }elseif ($status == 'PAY-RECIEVED'){
            $statusarry = ['Pay Received','13'];
        }elseif ($status == 'MOVE-INS'){
            $statusarry = ['Lease Confirmed','10'];
        }else{
            $statusarry = ['New','Repeat','Prospect','Hot','Warm','Pending','Lease Confirmed','Invoiced','1','2','3','4','5','7','10','12'];
        }

        $leadclients    =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                ->leftJoin('property','property.id','=','lead_client.prop_id');

        if ($user_role == SUPERADMIN){
            
            $useragentlist      =   array();
            $arlead             =   0;
            $useraragent        =   $useragentlist    =   User::where('user_role','=',$user_role)
                                                              ->orderBy('name','ASC')
                                                              ->get();

            if (session('aragentsearch') == ''){
                $firstuser = $useraragent->first();
                if ((isset($firstuser->id)) && $firstuser->id != ''){
                    Session::put('aragentsearch', $firstuser->id);
                }
            }

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

                $agent_id       = session('aragentsearch');
                $leadclients    = $leadclients->select('lead_client.*', 'users.name', 'users.last_name')
                                            ->where('agent_id', '=', session('aragentsearch'))
                                            ->whereIn('curr_status', $statusarry);
            }else{

                $agent_id       = 0;
                $leadclients    = $leadclients->select('lead_client.*', 'users.name', 'users.last_name')
                                                ->where('users.assign_to_ar', '=', $id)
                                                ->whereIn('curr_status', $statusarry);
            }
        }elseif ($user_role == ARUSER){
            
            $arlead             =   1;
            if(Auth::user()->user_role == SUPERADMIN){
                $useragentlist  =   User::where('user_role','=',$user_role)
                                                              ->orderBy('name','ASC')
                                                              ->get();
            }else{

                $useragentlist      =   User::where('user_role','=',ARUSER)
                                              ->where('users.create_by_user','=',Auth::user()->id)
                                              ->orderBy('name','ASC')
                                              ->get();
            }
            # code...
            //Agent Dashboard Fror A/R USERS Manage Condition
            $role_for       =  'AGENT';
            $useraragent    =   User::where('user_role', '=', AGENT)
                                    ->where('assign_to_ar', '=', session('aragentsearch'));

            if (session('aragentsearch') == ''){
                $firstuser = $useraragent->first();
                if ((isset($firstuser->id)) && $firstuser->id != ''){
                    Session::put('aragentsearch', $firstuser->id);
                }
            }

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

                $alluseraragent =   $useraragent->pluck('id')->toArray();
                $leadclients    =   $leadclients->select('lead_client.*', 'users.name', 'users.last_name')
                                            ->whereIn('curr_status',$statusarry)
                                            ->whereIn('agent_id', $alluseraragent);

                $agent_id       =   session('aragentsearch');
                $id             =   $agent_id;
                if ($status == 'INVOICES' || $status == 'PAY-RECIEVED' || $status == 'SOLDS' || $status == 'MOVE-INS'){

                    
                    $leadclients    =   $leadclients->where(function($query){
                                              $query->select('*')
                                              ->where('lead_client.ar_contact_date_next','<=',date('Y-m-d'))
                                              ->orWhereNull('lead_client.ar_contact_date_next');
                                        });
                }
            }
        }elseif ($user_role == ADMIN){
           
            $role_for           =   'ADMIN';
            $useragentlist      =   User::where('user_role','=',2)
                                          ->orderBy('name','ASC')
                                          ->get();

            $useraragent        =   User::where('user_role','=',AGENT)
                                            ->where('create_by_user','=',$id)
                                            ->where('status','=',1)
                                            ->pluck('id')
                                            ->toArray();
            $agent_id           =   $id;
            $arlead             =   0;
            
            $leadclients        =   $leadclients->select('lead_client.*', 'users.name', 'users.last_name')
                                            ->whereIn('agent_id', $useraragent)
                                            ->whereIn('curr_status', $statusarry);
            
            if ($status == 'FOLLOW'){
                
                $leadclients    =   $leadclients->where(function ($query){
                                        $query->select('*')
                                            ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                            ->orWhereNull('lead_client.contact_nxt_date');
                                    });
            }
        }else{
            
            $role_for       =   'AGENT';
            $useraragent    =   array();
            $useragentlist  =   User::where('user_role','=',$user_role)
                                                              ->orderBy('name','ASC')
                                                              ->get();
            $agent_id       =   $id;
            $arlead         =   0;
            
            $leadclients    =   $leadclients->select('lead_client.*', 'users.name', 'users.last_name')
                                            ->where('agent_id', '=', $id)
                                            ->whereIn('curr_status', $statusarry);
            
            if ($status == 'FOLLOW'){

                $leadclients    =   $leadclients->where(function ($query){
                                        $query->select('*')
                                            ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                            ->orWhereNull('lead_client.contact_nxt_date');
                                    });
            }

            //$leadclients        = $leadclients->sortable()->paginate($items);
        }

        if(Session::get('leadsearchresult') != ''){

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

            /* 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) use ($date, $pref){
                                          $query->select('*')
                                          ->orWhere('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', 'DESC');
                                });
            }

            if($pref == 'close_date' && $pref != ''){
                 
               $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                          $query->select('*')
                                            ->orWhere('lead_client.id', 'LIKE', 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.house_add', 'LIKE', '%'.Session('leadsearchresult').'%')
                                            ->orWhere('lead_client.title_phone', 'LIKE', '%'. preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                            ->orWhere('lead_client.title_officer', 'LIKE', '%'.Session('leadsearchresult').'%')
                                            ->orWhere('lead_client.phone1', 'LIKE', '%'.preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                            ->orWhere('property.prop_name', 'LIKE', Session('leadsearchresult'))
                                            ->orWhere('lead_client.contact_nxt_date','LIKE',$date)
                                            ->orWhere('lead_client.start_date','LIKE',$date)
                                            ->orWhere('lead_client.close_date','LIKE','%'.$date.'%')
                                            ->orWhere('lead_client.ar_contact_date_next','LIKE', $date)
                                            ->orWhere('lead_client.move_date','LIKE',$date)
                                            ->orderBy($pref, 'ASC');
                                });
            }else if($pref == 'prop_name'&&$pref!=''){
                 
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                                $query->select('*')
                                                ->orWhere('lead_client.house_add', 'LIKE', '%'.Session('leadsearchresult').'%')
                                                ->orWhere('property.prop_name', 'LIKE', '%'.Session('leadsearchresult').'%')
                                                ->orderBy($pref, 'ASC');
                                });
            }else if($pref == 'start_date'&&$pref!=''){
                 
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                            $query->select('*')
                                            ->orWhere('lead_client.start_date','LIKE','%'.$date.'%')
                                            ->orWhere('lead_client.close_date','LIKE','%'.$date.'%')
                                            ->orWhere('lead_client.ar_contact_date_next','LIKE', $date)
                                            ->orWhere('lead_client.move_date','LIKE',$date)
                                            ->orderBy($pref, 'ASC');
                                });
            }else if($pref == 'move_date'&&$pref!=''){
              
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                            $query->select('*')
                                            ->orWhere('lead_client.move_date','LIKE','%'.$date.'%')
                                            ->orderBy($pref, 'ASC');
                                });
            }else if($pref == 'contact_nxt_date'&&$pref!=''){
                  
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                                $query->select('*')
                                                ->orWhere('lead_client.id', 'LIKE', 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.house_add', 'LIKE', '%'.Session('leadsearchresult').'%')
                                                ->orWhere('lead_client.title_phone', 'LIKE', '%'.preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                                ->orWhere('lead_client.title_officer', 'LIKE', '%'.Session('leadsearchresult').'%')
                                                ->orWhere('lead_client.phone1', 'LIKE', '%'.preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                                ->orWhere('property.prop_name', 'LIKE', Session('leadsearchresult'))
                                                ->orWhere('lead_client.contact_nxt_date','LIKE','%'.$date.'%')
                                                ->orWhere('lead_client.start_date','LIKE',$date)
                                                ->orWhere('lead_client.close_date','LIKE',$date)
                                                ->orWhere('lead_client.ar_contact_date_next','LIKE', $date)
                                                ->orWhere('lead_client.move_date','LIKE',$date)
                                                ->orderBy($pref, 'ASC');
                                }); 
            }elseif($pref == 'id'&&$pref!=''){
              
                    $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                                $query->select('*')
                                                ->orWhere('lead_client.id', 'LIKE',Session('leadsearchresult'))
                                                ->orderBy($pref, 'ASC');
                                              });
            }elseif($pref == 'curr_status'&&$pref!=''){
                  
              $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                            $query->select('*')
                                            ->orWhere('lead_client.curr_status', 'LIKE',Session('leadsearchresult'))
                                            ->orderBy($pref, 'ASC');
                                });
            }elseif($pref == 'fname'&&$pref!=''){
                  
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                          $query->select('*')
                                          ->orWhere('lead_client.fname', 'LIKE',Session('leadsearchresult'))
                                          ->orderBy($pref, 'ASC');
                                });
            }elseif($pref == 'lname' && $pref != ''){
                  
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                            $query->select('*')
                                            ->orWhere('lead_client.lname', 'LIKE',Session('leadsearchresult'))
                                            ->orderBy($pref, 'ASC');
                                });
            }elseif($pref == 'email'&&$pref!=''){
                  
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                            $query->select('*')
                                            ->orWhere('lead_client.email', 'LIKE',Session('leadsearchresult'))
                                            ->orderBy($pref, 'ASC');
                                });
            }elseif($pref == 'prop_phone'&&$pref!=''){
                  
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                          $query->select('*')
                                          ->orWhere('lead_client.phone1', 'LIKE', preg_replace("/[^0-9.]/", "", Session('leadsearchresult')))
                                          ->orWhere('property.prop_phone', 'LIKE', preg_replace("/[^0-9.]/", "", Session('leadsearchresult')))
                                          ->orderBy($pref, 'ASC');
                                });
            }elseif($pref == 'title_officer'&&$pref!=''){
                   
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                          $query->select('*')
                                          ->orWhere('lead_client.id', '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.house_add', 'LIKE', '%'.Session('leadsearchresult').'%')
                                          ->orWhere('lead_client.title_phone', 'LIKE', '%'. preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                          ->orWhere('lead_client.title_officer', 'LIKE', '%'.Session('leadsearchresult').'%')
                                          ->orWhere('property.prop_manager',  Session('leadsearchresult'))
                                          ->orWhere('property.prop_phone', 'LIKE', '%'.preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                          ->orWhere('property.prop_name', 'LIKE', Session('leadsearchresult'))
                                          ->orWhere('lead_client.contact_nxt_date','LIKE',$date)
                                          ->orWhere('lead_client.start_date','LIKE',$date)
                                          ->orWhere('lead_client.close_date','LIKE',$date)
                                          ->orWhere('lead_client.ar_contact_date_next','LIKE', $date)
                                          ->orWhere('lead_client.move_date','LIKE','%'.$date.'%')
                                          ->orderBy($pref, 'ASC');
                                });
            }elseif($pref == 'ar_contact_date_next'&&$pref!=''){
                   
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                                $query->select('*')
                                                ->orWhere('lead_client.id', '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.house_add', 'LIKE', '%'.Session('leadsearchresult').'%')
                                                ->orWhere('lead_client.title_phone', 'LIKE', '%'.preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                                ->orWhere('lead_client.title_officer', 'LIKE', '%'.Session('leadsearchresult').'%')
                                                ->orWhere('property.prop_phone', 'LIKE', '%'.preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                                ->orWhere('property.prop_name', 'LIKE', Session('leadsearchresult'))
                                                ->orWhere('lead_client.contact_nxt_date','LIKE',$date)
                                                ->orWhere('lead_client.start_date','LIKE',$date)
                                                ->orWhere('lead_client.close_date','LIKE',$date)
                                                ->orWhere('lead_client.ar_contact_date_next','LIKE', '%'.$date.'%')
                                                ->orWhere('lead_client.move_date','LIKE',$date)
                                                ->orderBy($pref, 'ASC');
                                });
            }else{
                  
                $leadclients  =   $leadclients->where(function($query) use ($date, $pref){
                                                $query->select('*')
                                                ->orWhere('lead_client.id', 'LIKE', 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.house_add', 'LIKE', '%'.Session('leadsearchresult').'%')
                                                ->orWhere('lead_client.title_phone', 'LIKE', '%'.preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                                ->orWhere('lead_client.title_officer', 'LIKE', '%'.Session('leadsearchresult').'%')
                                                ->orWhere('property.prop_phone', 'LIKE', '%'.preg_replace("/[^0-9.]/", "", Session('leadsearchresult')).'%')
                                                ->orWhere('property.prop_name', 'LIKE', '%'.Session('leadsearchresult'.'%'))
                                                ->orWhere('lead_client.contact_nxt_date','LIKE','%'.$date.'%')
                                                ->orWhere('lead_client.start_date','LIKE','%'.$date.'%')
                                                ->orWhere('lead_client.close_date','LIKE','%'.$date.'%')
                                                ->orWhere('lead_client.ar_contact_date_next','LIKE','%'.$date.'%')
                                                ->orWhere('lead_client.move_date','LIKE','%'.$date.'%')
                                                ->orderBy($pref, 'ASC');
                                });
            }

            if($sort=="house_add"){
                $leadclients  =   $leadclients->orderby( 'lead_client.house_add',$direction);
            }else{
                $leadclients  =   $leadclients->orderby('lead_client.'.$sort ,$direction);
            }
        }
        $leadclients            =   $leadclients->sortable()->paginate($items);

        return view('leadclient.index', [
            'current_status'    =>  DB::table('lead_status')->select('id', 'status_name','new_status_name')
                                        ->where('status', '=', 1)->orderBy('position', 'ASC')
                                        ->get() , 
            'edit_table'        =>  1, 
            'manager'           =>  0, 
            'agent_id'          =>  $id, 
            'agentemailcreate'  =>  Agentemail::where('agent_id', '=', Auth::user()->id)
                                                ->where('status', '=', 1)
                                                ->orderBy('email_name', 'ASC')
                                                ->get() , 
            'user_role'         =>  $user_role, 
            'arlead'            =>  $arlead, 
            'usersagent'        =>  $useragentlist, 
            'role_for'          =>  $role_for
        ], compact('leadclients'))->withMembers($leadclients)->withItems($items);
    }

    public function create()
    {

        $company    = Auth::user()->company;
        $id         = Auth::user()->id;
        $agent_id   = $id;

        if (Auth::user()->user_role == AGENT)
        {
            Session::put('agent_id', Auth::user()->id);

            if (Auth::user()->manage_manager == 1){

                $agents = Auth::user()->agents_to_manager;
                $agents = explode(',', $agents);
                if (empty($agents)){
                    $agents = array(0);
                }

                $useragent  =   User::where('user_role', '=', 3)
                                        ->where('id', '=', $id)
                                        ->where('status', '=', 1)
                                        ->orWhere(function ($query) use ($agents){
                                            $query->select('*')
                                                    ->whereIn('id', $agents);
                                        })
                                        ->orderBy('name', 'ASC')
                                        ->get();        
            }else{
                $useragent  =   User::where('user_role', '=', 3)
                                        ->where('id', '=', $id)
                                        ->where('status', '=', 1)
                                        ->orderBy('name', 'ASC')
                                        ->get();
            }
        }elseif (Auth::user()->user_role == ARUSER){

            $useragent  =   User::where('user_role', '=', 3)
                                ->where('assign_to_ar', Auth::user()->id)
                                ->where('status', '=', 1)
                                ->orderBy('name', 'ASC')
                                ->get();
        }elseif (Auth::user()->user_role == ADMIN){

            $useragent  =   User::where('user_role', '=', 3)
                                ->where('users.create_by_user', Auth::user()->id)
                                ->where('status', '=', 1)
                                ->orWhere([['company','=',Auth::user()->company],['user_role','=',3]])
                                ->orderBy('name', 'ASC')
                                ->get();
        }else{
            $useragent  =   User::where('user_role', '=', 3)
                                ->orderBy('name', 'ASC')
                                ->get();
        }

        $state = DB::table('state')->select('id', 'state_name', 'state_value')->get();
        
        // add property 
        
        $agent_id   =   Auth::user()->id;
        $user_role  =   Auth::user()->user_role;
        
        if($user_role  ==  SUPERADMIN){
        
            $companyid      =   0;
            $company_name   =   '';
        }else{
        
            $companyid          =   Auth::user()->company;
            $company_name       =   Company::find($companyid);
            if(!empty($company_name)){
                $company_name     =   $company_name->mgmt_name;
            }else{
                $company_name     =   '';
            }
        }
    
        $mgmt_company  =  Company::where('company_type',2)->OrderBy('mgmt_name','ASC')->get();
        $real_company =  Company::where('company_type',1)->OrderBy('mgmt_name','ASC')->get();
        
        //echo "<pre>";print_r($useragent); exit;
          
        return view('leadclient.createlead', [
            'agentemailcreate'  =>  Agentemail::where('agent_id', '=', Auth::user()
            ->id)
                                            ->where('status', '=', 1)
                                            ->orderBy('email_name', 'ASC')
                                            ->get() , 
            'propertys'         =>  Property::leftJoin('company', 'company.id', '=', 'property.prop_mgmt_co')
                                            ->select('property.*', 'company.mgmt_name')
                                            ->orderBy('property.prop_name', 'ASC')
                                            ->get() , 
            'states'            =>  $state, 
            'current_status'    =>  DB::table('lead_status')
                                        ->select('id', 'status_name','cost','new_status_name')
                                        ->where('status', '=', 1)->whereNotIn('id', [16,17])->orderBy('position', 'ASC')
                                        ->get() ,
            'usersagent'        =>  $useragent, 
            'agent_id'          =>  $id, 
            'show_table'        =>  1,
            'mgmt_company'  =>  $mgmt_company,
            'real_company'  =>  $real_company,
            'company_id'    =>  $companyid,
            'company_name'  =>  $company_name
        ]);

    }

    public function getproperty()
    {
        $_POST;
        $id         =   $_POST['id'];
        $propertys  =   Property::find($id);
        $collection =   CollectionDetails::where('company_id', Auth::user()->company)
                                        ->where('property_id', $id)
                                        ->OrderBy('id', 'desc')
                                        ->first();

        if (!empty($propertys)){
            if (!empty($collection)){
                $propertys->prop_notes = $collection->collection_details;
            }else{
                $propertys->prop_notes = '';
            }

            echo json_encode($propertys);
        }
    }

    public function agentsetsession(Request $request)
    {
        $agenrt_id = $request->input('agent_id');

        if ($agenrt_id > 0){
            Session::put('aragentsearch', $agenrt_id);
        }else{
            Session::forget('aragentsearch');
        }

    }

    public function getemailform(){

        $email_id       =   $_POST['email_id'];
        $leaddetail     =   $_POST['lead_id'];
        $agentemail     =   Agentemail::find($email_id);
        $leaddetail     =   Leadclient::find($leaddetail);
        $agentdetail    =   User::find(Auth::user()->id);
        
        $agentemail     =   setemaildata($agentemail, $leaddetail, $agentdetail);
        
        return view('leadclient.sendemail', ['agentemail' => $agentemail, 'leaddetail' => $leaddetail]);
    }

    public function getinvoiceemailform()
    {
        $email_id           = $_POST['email_id'];
        $leaddetail         = $_POST['lead_id'];
        $agentemail         = Agentemail::find($email_id);
        $leaddetail         = Leadclient::find($leaddetail);
        $agentdetail        = User::find($leaddetail->agent_id);
        $agentdetail        = User::find($agentdetail->assign_to_ar);
        $agentemail         = setemaildata($agentemail, $leaddetail, $agentdetail);
        
        return view('leadclient.sendemail', ['agentemail' => $agentemail, 'leaddetail' => $leaddetail]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store()
    {
        $input              = request()->all();
        $leadclient         = new Leadclient();
        $agent_id           = $input['agent_id'];
        $input['source_id'] = $agent_id;
        
        unset($input['user_role']);
        unset($input['w9files']);
        

        foreach ($input as $key => $value)
        {
            if ($key != '_token' && $key != 'send_email' && $key != 'prop_add' && $key != 'prop_city' && $key != 'prop_state' && $key != 'prop_zip' && $key != 'prop_email' && $key != 'prop_phone' && $key != 'prop_fax' && $key != 'lease_email' && $key != 'lead_source' && $key != 'house_cost' && $key != 'lease_email_house' && $key != 'inv_num' && $key != 'days_status' && $key != 'mgmt_name' && $key != 'property_phone' && $key != 'prop_manager' && $key != 'invoiced_total' && $key != 'paid_date' && $key != 'agent_paid' && $key != 'prop_notes' && $key != 'inv_email' && $key != 'apt_prop_id' && $key != 'apt_start_date' && $key != 'apt_lease_term' && $key != 'apt_rent_amount' && $key != 'apt_commision' && $key != 'apt_commision_unit' && $key != 'apt_bonus' && $key != 'apt_incentive' && $key != 'apt_reg_po' && $key != 'apt_lease_email' && $key != 'paid_date' && $key != 'ctitle_officer' && $key != 'ctitle_phone' && $key !='ctitle_fax' && $key != 'ctitle_email' && $key != 'rsmls' && $key != 'rshouse_add' && $key != 'rshouse_state' && $key != 'rshouse_city' && $key != 'rshouse_zip' && $key != 'rsclose_date' && $key != 'rsb_or_s' && $key != 'rssold_amt' && $key != 'rshouse_comm' && $key != 'rshouse_bonus' && $key != 'rstitle' && $key !='rstitle_add' && $key != 'rstitle_city' && $key != 'rstitle_state' && $key != 'rstitle_zip' && $key != 'rstitle_officer' && $key != 'rstitle_phone' && $key != 'rstitle_fax' && $key != 'rstitle_email' && $key != 'cs_cprop_type' && $key != 'rsap_method' && $key !='cl_prop_type' && $key != 'clrent_amount' && $key !='cltitle_add' && $key != 'cltitle_city' && $key != 'cltitle_state' && $key != 'cltitle_zip' && $key != 'cltitle_phone' && $key != 'cltitle_fax' && $key != 'clbroker_name' && $key != 'clbroker_phone' && $key !='clbroker_email' && $key != 'clbroker_fax' && $key !='cshouse_add' && $key != 'cshouse_state' && $key != 'cshouse_city' && $key !='cshouse_zip' && $key != 'csclose_date' && $key != 'csb_or_s' && $key != 'cssold_amt' && $key != 'cshouse_comm' && $key !='cshouse_bonus' && $key != 'cstitle' && $key !='cstitle_add' && $key != 'cstitle_city' && $key != 'cstitle_state' && $key != 'cstitle_zip' && $key != 'cstitle_phone' && $key != 'cstitle_fax' && $key != 'cstitle_email' && $key != 'cstitle_officer' && $key != 'csap_method' && $key != 'rslease_email_house' && $key !='cslease_email_house' && $key != 'clhouse_add' && $key != 'clcommision_unit' && $key != 'clhouse_city' && $key != 'clhouse_state' && $key != 'clhouse_fax' && $key != 'clhouse_zip' && $key != 'clclose_date' && $key != 'clb_or_s' && $key != 'cllease_term' && $key != 'clsold_amt' && $key != 'clhouse_comm' && $key != 'clhouse_bonus' && $key != 'cltitle')
            {
                $leadclient->$key = $value;
            }

            $leadclient->lead_id_orig = 0;                  
            
            if ($key == 'contact_nxt_date')
            {
                $leadclient->$key = setdbdate($value);
            }
            if ($key == 'move_date')
            {
                $leadclient->$key = setdbdate($value);
            }
            if ($key == 'ar_contact_date_next')
            {
                $leadclient->$key = setdbdate($value);
            }
            if ($key == 'rebateform_date')
            {
                $leadclient->$key = setdbdate($value);
            }
            if ($key == 'rebatesent_date')
            {
                $leadclient->$key = setdbdate($value);
            }
        }

        if ($input['curr_status'] != ''){
            $leadclient->status_history = date('m-d-Y') . '~~' . get_status_name($input['curr_status']);
            $leadclient->curr_status_cost  = (!empty($input['curr_status_cost'])?$input['curr_status_cost']:'');
        }
        $agentdetail_invcost            = User::find($agent_id); 
        $leadclient->assigned_date      = date("Y-m-d H:i:s");
        $leadclient->create_by_user     = Auth::user()->id;
        $leadclient->update_by_user     = 0;
        $leadclient->invoicing_cost     = (!empty($agentdetail_invcost->invoicing_cost) ? $agentdetail_invcost->invoicing_cost : 1);

        /* Apartment Lease data */
        if ($input['transaction_type_id'] == 1){  // Apartment Lease

            $leadclient->transaction_type_id   = $input['transaction_type_id'];
            $leadclient->prop_id               = $input['apt_prop_id'];
            $leadclient->bonus                 = $input['apt_bonus'];
            $leadclient->incentive             = $input['apt_incentive'];
            $leadclient->reg_po                = $input['apt_reg_po'];
            $leadclient->commision_unit        = $input['apt_commision_unit'];
            $leadclient->commision             = $input['apt_commision'];
            $leadclient->rent_amount           = $input['apt_rent_amount'];
            $leadclient->apt_unit              = $input['apt_unit'];
            $leadclient->lease_term            = $input['apt_lease_term'];
            $leadclient->start_date            = $input['apt_start_date'] ? setdbdate($input['apt_start_date']) : NULL;
        }

        if ($input['transaction_type_id'] == 2){  // Residential Lease

            $leadclient->transaction_type_id           = $input['transaction_type_id'];
            $leadclient->mls                           = $input['mls'];
            $leadclient->house_add                     = $input['house_add'];
            $leadclient->house_state                   = $input['house_state'];
            $leadclient->house_city                    = $input['house_city'];
            $leadclient->house_zip                     = $input['house_zip'];
            $leadclient->close_date                    = $input['close_date'] ? setdbdate($input['close_date']) : NULL;
            $leadclient->b_or_s                        = $input['b_or_s'];
            $leadclient->sold_amt                      = $input['sold_amt'];
            $leadclient->house_comm                    = $input['house_comm'];
            $leadclient->house_bonus                   = $input['house_bonus'];
            $leadclient->title                         = $input['title'];
            $leadclient->title_add                     = $input['title_add'];
            $leadclient->title_city                    = $input['title_city'];
            $leadclient->title_state                   = $input['title_state'];
            $leadclient->title_zip                     = $input['title_zip'];
            $leadclient->incentive                     = $input['incentive'];
            $leadclient->title_officer                 = $input['title_officer'];
            $leadclient->title_phone                   = $input['title_phone'];
            $leadclient->title_fax                     = $input['title_fax'];
            $leadclient->title_email                   = $input['title_email'];
        }

        if ($input['transaction_type_id'] == 3){  // Residential Sale

            $leadclient->transaction_type_id    = $input['transaction_type_id'];
            $leadclient->mls                    = $input['rsmls'];
            $leadclient->house_add              = $input['rshouse_add'];
            $leadclient->house_state            = $input['rshouse_state'];
            $leadclient->house_city             = $input['rshouse_city'];
            $leadclient->house_zip              = $input['rshouse_zip'];
            $leadclient->close_date             = $input['rsclose_date'] ? setdbdate($input['rsclose_date']) : NULL;
            $leadclient->b_or_s                 = $input['rsb_or_s'];
            $leadclient->sold_amt               = $input['rssold_amt'];
            $leadclient->house_comm             = $input['rshouse_comm'];
            $leadclient->house_bonus            = $input['rshouse_bonus'];
            $leadclient->title                  = $input['rstitle'];
            $leadclient->title_add              = $input['rstitle_add'];
            $leadclient->title_city             = $input['rstitle_city'];
            $leadclient->title_state            = $input['rstitle_state'];
            $leadclient->title_zip              = $input['rstitle_zip'];
            $leadclient->title_officer          = $input['rstitle_officer'];
            $leadclient->title_phone            = $input['rstitle_phone'];
            $leadclient->title_fax              = $input['rstitle_fax'];
            $leadclient->title_email            = $input['rstitle_email'];
            $leadclient->ap_method              = $input['rsap_method'];
            $leadclient->incentive              = $input['incentive_lease'];
            
        }

        if ($input['transaction_type_id'] == 5){  // Commercial Lease

            $leadclient->transaction_type_id     = $input['transaction_type_id'];
            $leadclient->prop_type               = $input['cl_prop_type'];
            $leadclient->house_add               = $input['clhouse_add'];
            $leadclient->commision_unit          = $input['clcommision_unit'];
            $leadclient->house_state             = $input['clhouse_state'];
            $leadclient->house_city              = $input['clhouse_city'];
            $leadclient->house_zip               = $input['clhouse_zip'];
            $leadclient->close_date              = $input['clclose_date'] ? setdbdate($input['clclose_date']) : NULL;
            $leadclient->b_or_s                  = $input['clb_or_s'];
            $leadclient->rent_amount             = $input['clrent_amount'];
            $leadclient->lease_term              = $input['cllease_term'];
            $leadclient->house_comm              = $input['clhouse_comm'];
            $leadclient->title                   = $input['cltitle'];
            $leadclient->title_add               = $input['cltitle_add'];
            $leadclient->title_city              = $input['cltitle_city'];
            $leadclient->title_state             = $input['cltitle_state'];
            $leadclient->title_zip               = $input['cltitle_zip'];
            $leadclient->title_phone             = $input['cltitle_phone'];
            $leadclient->title_fax               = (!empty($input['cltitle_fax'] )?$input['cltitle_fax'] : NULL);
            $leadclient->broker_name             = $input['clbroker_name'];
            $leadclient->broker_phone            = $input['clbroker_phone'];
            $leadclient->broker_email            = $input['clbroker_email'];
            $leadclient->broker_fax              = $input['clbroker_fax'];
            //echo "<pre>";print_r($leadclient); exit;
        }

        if ($input['transaction_type_id'] == 6){  // Commercial Sales

            $leadclient->transaction_type_id    = $input['transaction_type_id'];
            $leadclient->prop_type              = $input['cs_cprop_type'];
            $leadclient->house_add              = $input['cshouse_add'];
            $leadclient->house_state            = $input['cshouse_state'];
            $leadclient->house_city             = $input['cshouse_city'];
            $leadclient->house_zip              = $input['cshouse_zip'];
            $leadclient->close_date             = $input['csclose_date'] ? setdbdate($input['csclose_date']) : NULL;
            $leadclient->b_or_s                 = $input['csb_or_s'];
            $leadclient->sold_amt               = $input['cssold_amt'];
            $leadclient->house_comm             = $input['cshouse_comm'];
            $leadclient->house_bonus            = $input['cshouse_bonus'];
            $leadclient->title                  = $input['cstitle'];
            $leadclient->title_add              = $input['cstitle_add'];
            $leadclient->title_city             = $input['cstitle_city'];
            $leadclient->title_state            = $input['cstitle_state'];
            $leadclient->title_zip              = $input['cstitle_zip'];
            $leadclient->title_phone            = $input['cstitle_phone'];
            $leadclient->title_fax              = $input['cstitle_fax'];
            $leadclient->title_email            = $input['cstitle_email'];
            $leadclient->title_officer          = $input['cstitle_officer'];
            $leadclient->ap_method              = $input['csap_method'];   
        }

        if ($input['transaction_type_id'] == 4 || $input['transaction_type_id'] == 0){  // Reset

            $leadclient->transaction_type_id   = $input['transaction_type_id'];
            $leadclient->mls                           = "";
            $leadclient->prop_id                       = "";
            $leadclient->bonus                         = 0;
            $leadclient->reg_po                        = "";
            $leadclient->start_date                    = NULL;
            $leadclient->close_date                    = NULL;
            $leadclient->prop_type                     = "";
            $leadclient->house_add                     = "";
            $leadclient->house_state                   = "";
            $leadclient->house_city                    = "";
            $leadclient->house_zip                     = "";
            $leadclient->b_or_s                        = "";
            $leadclient->apt_unit                      = "";
            $leadclient->sold_amt                      = 0;
            $leadclient->house_comm                    = 0;
            $leadclient->house_bonus                   = 0;
            $leadclient->commision_unit                = "";
            $leadclient->commision                     = "";
            $leadclient->rent_amount                   = 0;
            $leadclient->title                         = "";
            $leadclient->title_add                     = "";
            $leadclient->title_city                    = "";
            $leadclient->title_state                   = "";
            $leadclient->title_zip                     = "";
            $leadclient->title_phone                   = "";
            $leadclient->title_fax                     = "";
            $leadclient->title_email                   = "";
            $leadclient->title_officer                 = "";
            $leadclient->incentive                     = 0;
            $leadclient->ap_method                     = "";
            $leadclient->broker_name                   = "";
            $leadclient->broker_phone                  = "";
            $leadclient->broker_email                  = "";
            $leadclient->broker_fax                    = "";   
        }

        if ($leadclient->save()){

            $leadclientcalculation                  = new Leadclientcalculation();
            $leadclientcalculation->leadclient_id   = $leadclient->id;

            $lead_status_history                    = new Leasstatus_history();
            $lead_status_history->lead_id           = $leadclient->id;
            $lead_status_history->status            = get_status_name($input['curr_status']);
            $lead_status_history->curr_status_cost  = (!empty($input['curr_status_cost'])?$input['curr_status_cost']:'111');
            $lead_status_history->date              = date('Y-m-d');
            $lead_status_history->time              = date('Y-m-d h:i:s');

            if ($leadclientcalculation->save() && $lead_status_history->save()){
                
                if ($input['curr_status'] == 'Paid Out' || $input['curr_status'] == '14' ){
                    $this->create_duplicate_lead($leadclient->id);
                }
                Session::flash('message', 'add');
                Session::flash('alert-class', 'alert-success');
            }
        }else{

            Session::flash('message', 'failadd');
            Session::flash('alert-class', 'alert-danger');
        }

        return redirect('/editclientlead/' . $leadclient->id . '/1');
    }


    function create_duplicate_lead($id){

        $input              = request()->all();
        $leadclient         = new Leadclient();

        $lead_agent         = Leadclient::find($id);
        $notes_history      = date('m-d-Y') . '- Previous Record  ID <a href="' . url('editclientlead/' . $id . '/1') . '">#' . $id . '</a> ';
        if ($lead_agent->prop_id != 0 && $lead_agent->prop_id != ''){

            $prop           = Property::find($lead_agent->prop_id);
            $notes_history .= 'Property Name ' . $prop->prop_name;

        }else{
            $notes_history .= 'Lease date ' . $lead_agent->close_date;
        }

        $notts                          = explode('~~~~', $lead_agent->notes_history);
        $notts                          = implode('<br/>', $notts);
        $input['notes_history']         = rtrim($notes_history . '~~~~' . 'All Previous Notes' . '~~~~' . $notts, '~~~~');
        $input['curr_status']           = 'Repeat';
        $input['duplicate_id']          = $id;
        $agent_id                       = $lead_agent['agent_id'];
        $input['agent_id']              = $lead_agent['agent_id'];
        $input['source_id']             = $agent_id;
        $input['contact_nxt_date']      = '1970-01-01';
        $input['prop_id']               = 0;

        foreach ($input as $key => $value)
        {

            if ($key == 'fname' || $key == 'lname' || $key == 'lname' || $key == 'phone1' || $key == 'phone2' || $key == 'email' || $key == 'contact_notes' || $key == 'curr_status' || $key == 'contact_nxt_date' || $key == 'source_id' || $key == 'agent_id' || $key == 'duplicate_id' || $key == 'notes_history' || $key == 'prop_id')
            {
                $leadclient->$key = $value;
            }

            
            $leadclient->lead_id_orig = 0;
            
            if ($key == 'move_date')
            {
                $leadclient->$key = date("Y-m-d", strtotime($input['move_date']));
            }
            if ($key == 'start_date')
            {
                $leadclient->$key = date("Y-m-d", strtotime($input['start_date']));
            }
            if ($key == 'close_date')
            {
                $leadclient->$key = date("Y-m-d", strtotime($input['close_date'][0]));
            }
            if ($key == 'ar_contact_date_next')
            {
                $leadclient->$key = date("Y-m-d", strtotime($input['ar_contact_date_next']));
            }
            
            if ($key == 'rebateform_date')
            {
                $leadclient->$key = date("Y-m-d", strtotime($input['rebateform_date']));
            }

            if ($key == 'rebatesent_date')
            {
                $leadclient->$key = date("Y-m-d", strtotime($input['rebatesent_date']));
            }
        }

        if ($input['curr_status'] != '')
        {
            $leadclient->status_history = date('m-d-Y') . '~~' . get_status_name($input['curr_status']);
           $leadclient->curr_status_cost  = (!empty($input['curr_status_cost'])?$input['curr_status_cost']:'');

        }

        $leadclient->assigned_date  = date("Y-m-d H:i:s");
        $leadclient->create_by_user = Auth::user()->id;
        $leadclient->update_by_user = 0;

        if ($leadclient->save()){

            $leadclientcalculation                  = new Leadclientcalculation();
            $leadclientcalculation->leadclient_id   = $leadclient->id;
            $lead_status_history                    = new Leasstatus_history();
            $lead_status_history->lead_id           = $leadclient->id;
            $lead_status_history->status            = get_status_name($input['curr_status']);
            $lead_status_history->curr_status_cost  = (!empty($input['curr_status_cost'])?$input['curr_status_cost']:'');
            $lead_status_history->date              = date('Y-m-d');
            $lead_status_history->time              = date('Y-m-d h:i:s');

            if ($leadclientcalculation->save() && $lead_status_history->save()){
                return true;
            }
        }else{
            return false;
        }

    }

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

    public function updatedata()
    {
    
       // print_r($_POST); exit;
        $id             =   $_POST['lead_id'];
        $leadclient     =   Leadclient::find($id);
        $role_for       =   $_POST['role'];
        $agentemail     =   array();
       
      
        if ($_POST['notes_history'] != ''){
            
            if ($role_for != 'AGENT'){
                
                if (!empty($leadclient->notes_history))
                {

                    $agentemail['ar_notes_history'] = date('m-d-Y') . '-' . $_POST['notes_history'] . '~~~~' . $leadclient->ar_notes_history;
                }else{

                    $agentemail['ar_notes_history'] = date('m-d-Y') . '-' . $_POST['notes_history'];
                }
            }else{

                if ($leadclient->notes_history != '')
                {

                    $agentemail['notes_history'] = date('m-d-Y') . '-' . $_POST['notes_history'] . '~~~~' . $leadclient->ar_notes_history;
                }
                else
                {

                    $agentemail['notes_history'] = date('m-d-Y') . '-' . $_POST['notes_history'];
                }
            }
        }
        
        
    
        if (!empty($_POST['curr_status'])){

            if (!empty($leadclient->status_history)){
                $agentemail['status_history'] = date('m-d-Y') . '~~' .get_status_name($_POST['curr_status']) . '~~~~' . $leadclient->status_history;
            }else{

                $agentemail['status_history'] = date('m-d-Y') . '~~' . $_POST['curr_status'];
            }

            $agentemail['curr_status'] = $_POST['curr_status'];
            $agentemail['curr_status_cost']  = (!empty($_POST['curr_status_cost'])?$_POST['curr_status_cost']:'');
            
            $lead_status_history            = new Leasstatus_history();
            $lead_status_history->lead_id   = (!empty($leadclient->id)?$leadclient->id:'');
            $lead_status_history->status    = ($_POST['curr_status']);
            $lead_status_history->curr_status_cost  = (!empty($_POST['curr_status_cost'])?$_POST['curr_status_cost']:'');
            $lead_status_history->date      = date('Y-m-d');
            $lead_status_history->time      = date('Y-m-d h:i:s');
            
            
            $lead_status_history->save();
        }

        if ($_POST['contact_nxt_date'] != ''){
            if ($role_for == 'AGENT'){
                $agentemail['contact_nxt_date'] = setdbdate($_POST['contact_nxt_date']);
            }else{
                $agentemail['ar_contact_date_next'] = setdbdate($_POST['contact_nxt_date']);
            }
        }
        //DB::enableQueryLog();
  

        $updateLeadclient = Leadclient::where('id', $id)->update($agentemail);
        
        // dd(DB::getQueryLog()); exit;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\model\Leadclient  $leadclient
     * @return \Illuminate\Http\Response
     */

    function migratecalculation(){

        $agent_id       =   Auth::user()->id;
        $user_role      =   Auth::user()->user_role;
        $leadclients    =   Leadclient::all();

        foreach ($leadclients as $leadclient){

            $check = User::find($leadclient->agent_id);

            $agentleaddetail = User::find($leadclient->agent_id);
            if (!empty($agentleaddetail)){

                $assignar = User::find($agentleaddetail->assign_to_ar);

                if (empty($assignar))
                {
                    $assignar = new User;
                }
                
                $state                  =   DB::table('state')
                                                ->select('id', 'state_name', 'state_value')
                                                ->get();

                $agent_status           =   $agentleaddetail->user_role;
                $unit                   =   $agentleaddetail->unit;
                $agent_split_hous       =   $agentleaddetail->broker_cost;
                $agent_split            =   $agentleaddetail->broker_cost;
                $agent_invoice_cost     =   $leadclient->invoicing_cost;
                $incentive              =   (!empty($leadclient->incentive)?$leadclient->incentive:$leadclient['incentive_lease']);//$leadclient->incentive;
                $sold_amt               =   $leadclient->sold_amt;
                $house_comm             =   $leadclient->house_comm;
                $house_bonus            =   $leadclient->house_bonus;

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

                /*======== Remi ===========*/
                //calculat lead cost and agent paid amount
                $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 = $sold_amt * ((float) $house_comm / 100) + (float) $house_bonus;
                }

                if ($agent_status == 5){

                    if (!empty($lead)){
                        $dis_split      = $lead->lead_cost;
                        $dis_split_unit = $lead->unit;
                    }else{
                        $dis_split      = 0;
                        $dis_split_unit = 0;
                    }

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

                        if ($unit == 0){
                            
                            $agent_split = (int)$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 = (float) $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        = (int) $totalcommission * (int) $agent_split_hous;
                        }else{
                            $house_cost        = (float) $agent_split_hous;
                        }
                    }
                }
                
                

                //end calculat lead cost and agent paid amount
                /*======== End Remi=========*/

                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){

                            $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;
                    }
                }else{

                    $invoiced_total = 0;
                }

                /*======== Remi ===========*/
                //calculate invoice amount
                
                $leadcalculatdata['invoiced_total']     = (float) $invoiced_total;
                $leadcalculatdata['house_cost']         = (float) $house_cost;
                $leadcalculatdata['lead_cost']          = (float) $lead_cost;
                $leadcalculatdata['agent_paid']         = (float) $agent_paid;

                $leadcal                                = Leadclientcalculation::where('leadclient_id', $leadclient->id)
                                                                ->first();
                if (!empty($leadcal)){
                    $updateLeadclient = Leadclientcalculation::where('leadclient_id', $leadclient->id)
                                                                ->update($leadcalculatdata);
                }else{

                    $leadcalculatdata['leadclient_id']  = $leadclient->id;
                    $updateLeadclient                   = Leadclientcalculation::insert($leadcalculatdata);
                }
            }
        }
    }

    function migrateProperty()
    {
        $property = Property::all();

        foreach ($property as $prop)
        {
            $first = DB::table('vendor_details')->where(['company_id' => 1, 'property_id' => $prop
                ->id])
                ->first();

            if (empty($first))
            {
                DB::table('vendor_details')->insert(['company_id' => 1, 'property_id' => $prop->id, 'vendor_id' => $prop->vendor_id, 'created_at' => date('Y-m-d h:i:s') , 'updated_at' => date('Y-m-d h:i:s') ]);
            }

            $second = DB::table('collection_details')->where(['company_id' => 1, 'property_id' => $prop
                ->id])
                ->first();

            if (empty($second))
            {
                DB::table('collection_details')->insert(['company_id' => 1, 'property_id' => $prop->id, 'collection_details' => $prop->prop_notes, 'lead_id' => 0, 'created_at' => date('Y-m-d h:i:s') , 'updated_at' => date('Y-m-d h:i:s') ]);
            }
        }

    }

    public function edit($id, $id1)
    {
        
        $agent_id       = Auth::user()->id;
        $user_role      = Auth::user()->user_role;
        
        $leadclient     = Leadclient::leftJoin('property', 'property.id', 'lead_client.prop_id')
                                        ->select('prop_state', 'lead_client.*')
                                        ->where('lead_client.id', $id)
                                        ->first();
        
        $new_record_id  = Leadclient::where('duplicate_id', '=', $leadclient->id)
                                        ->first();

        if (!empty($new_record_id)){
            $leadclient->new_record_id = $new_record_id->id;
        }else{
            $leadclient->new_record_id = 0;
        }

        /* Disable Button(PDF,CDA) if state missing. */
        $disablebtn = false;
        if($leadclient->transaction_type_id == 2 || $leadclient->transaction_type_id == 3 || $leadclient->transaction_type_id == 5 || $leadclient->transaction_type_id == 6){

            if($leadclient->house_state == '' || $leadclient->title_state == ''){
                $disablebtn = true;
            }
        }
        /* Disable Button(PDF,CDA) if state missing. */
        
        if ($user_role == SUPERADMIN){
            
            $property   = Property::leftJoin('company', 'company.id', '=', 'property.prop_mgmt_co')
                                    ->select('property.*', 'company.mgmt_name')
                                    ->orderBy('property.prop_name', 'ASC')
                                    ->get();
        }else{
            $company    = Auth::user()->company;
        }
        


        $property       = Property::leftJoin('company', 'company.id', '=', 'property.prop_mgmt_co')
                                        ->select('property.*', 'company.mgmt_name')
                                        ->orderBy('property.prop_name', 'ASC')
                                        ->get();
        
        //echo"<pre>"; print_r($property); exit;
        // for rights validation
        $check          =   User::find($leadclient->agent_id);
        $email_log      =   DB::table('email_log')
                                ->Where('lead_id', $id)
                                ->Where('mail_for', '=', 'Lease Verification')
                                ->get();

        $invoice_log    =   DB::table('email_log')
                                ->Where('lead_id', $id)
                                ->Where('mail_for', '=', 'Invoice')
                                ->get();

        if ($leadclient->prop_id == 0 && $leadclient->prop_id == ''){

            $propertylead   = new Property;
            $companylead    = new Company;
        }else{

            $propertylead   = Property::find($leadclient->prop_id);
            $companylead    = Company::find($propertylead->prop_mgmt_co);

            if (!isset($companylead->mgmt_name)){
                $companylead = new Company;
                $companylead->mgmt_name = $propertylead->prop_mgmt_co;
            }
        }

        $agentleaddetail    =   User::find($leadclient->agent_id);

        $agentemailcreate   =   Agentemail::where('agent_id', '=', Auth::user()->id)
                                            ->where('status', '=', 1)
                                            ->orderBy('email_name', 'ASC')
                                            ->get();
        $assignar           =   User::find($agentleaddetail->assign_to_ar);

        if (empty($assignar)){
            $assignar       = new User;
        }
        
        $state              = DB::table('state')
                                    ->select('id', 'state_name', 'state_value')
                                    ->get();

        $agent_status       =   $agentleaddetail->user_role;
        $unit               =   $agentleaddetail->unit;
        $agent_split_hous   =   (float) $agentleaddetail->broker_cost;
        $agent_split        =   (float) $agentleaddetail->broker_cost;
        
        $curr_status_cost = $leadclient->curr_status_cost ? (float) $leadclient->curr_status_cost : 0;
        
        $statusarrychk      =   ['Pay Received', 'Paid Out','14','13'];
        $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){
                $agent_invoice_cost = $agent_invoice_cost+(float) $agentleaddetail->invoicing_cost;
            }
        }
        
       
       // echo  $agent_invoice_cost; exit;
        
        // 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);

        /*======== Remi ===========*/
        //calculat lead cost and agent paid amount
        $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;
        }
        $broker_cost =0;
        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;
            }
       
         //echo "<pre>"; print_r($dis_split_unit); exit;
            if ((float) $leadclient->payment != 0){

                if ($dis_split_unit == 0){
                    
                    if($leadclient->transaction_type_id==1){
                    $commision = $leadclient->commision;
                    }else{
                        $commision=$leadclient->house_comm;
                    }
                    
                    if($agent_invoice_cost){
                        $payment =   (float) ($leadclient->payment-$agent_invoice_cost);
                    }else{
                        $payment =   (float) ($leadclient->payment);
                    }
                    
                   // $payment =   (float) ($leadclient->payment);
                    
                    if (!empty($lead)){
                        if(!empty($lead->lead_cost)){
                            $broker_cost = ($payment*$lead->lead_cost/100);
                        }else{
                            $broker_cost = 0;
                        }
                        
                    }else{
                    
                        if(!empty($agentleaddetail->broker_cost)){
                            $broker_cost = ($payment*$agentleaddetail->broker_cost/100);
                        }else{
                            $broker_cost = 0;
                        }
                    }
                    
                    
    
                    if (!empty($lead)){
                        $broker_cost = 0;
                    }
              // echo " Broker cost ".$broker_cost; exit; 
                    
                    
                    $dis_split              = (float) $dis_split / 100;
                    //$leadclient->lead_cost  = ($payment - (float) $agent_invoice_cost) * (float) $dis_split;

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

                    $lead_cost              = (($payment) * (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;
                    
                    
                     //echo " agent paid ".$agent_paid." payment ".$payment." incentive ".$incentive.' agent_invoice_cost '.$agent_invoice_cost.' LEAD COST '.$leadclient->lead_cost." broker_cost ".$broker_cost; exit;
                }else{
                   // $payment =   (float) $leadclient->payment;
                    
                    if($agent_invoice_cost){
                        $payment =   (float) ($leadclient->payment-$agent_invoice_cost);
                    }else{
                        $payment =   (float) ($leadclient->payment);
                    }
                    
                    
                    if(!empty($agentleaddetail->broker_cost)){
                        $broker_cost = $agentleaddetail->broker_cost;
                    }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) $agent_invoice_cost - (float) $incentive - (float) $leadclient->lead_cost-$broker_cost;
                    
                    $agent_paid                 = $payment - (float) $incentive - (float) $leadclient->lead_cost-$broker_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($agent_invoice_cost){
                        $payment =   (float) ($leadclient->payment-$agent_invoice_cost);
                    }else{
                        $payment =   (float) ($leadclient->payment);
                    }
                    
                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;
                }else{

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

        //end calculated lead cost and agent paid amount
        /*======== End Remi=========*/

        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;
            }
        }else{
            $invoiced_total = 0;
        }
        
        
        
        /*======== Remi ===========*/
        //calculate invoice amount
            $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;
            }else if($tot_trans_amt >= 100000 && $tot_trans_amt < 1000000){
                $invoice_cost = $agentleaddetail->commercial_tier2;
            }else{
                $invoice_cost = $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{
                
                $agent_paid = ((float) $leadclient->payment - (float) $invoice_cost) * ((100-(float) $agentleaddetail->broker_cost) / 100);
            }
          //echo "Received amount  tier ".$invoice_cost. " broker_cost ".$broker_cost." agent_pad ".$agent_paid." commision ".$commision." lead_cost ".$lead_cost; exit; 
            
        }
           
        $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);
        
    
     //echo "invoiced_total  house_cost - ".$house_cost." lead_cost - ".$lead_cost." agent_paid - ".$agent_paid." broker cost ".$broker_cost." invoice_cost ".$agent_invoice_cost; exit; 
   
        $leadcalculatdata['invoiced_total'] = $invoiced_total;
        $leadcalculatdata['house_cost']     = (float) $house_cost;
        $leadcalculatdata['lead_cost']      = (float) $lead_cost;
        $leadcalculatdata['agent_paid']     = (float) $agent_paid;
        
       
//echo "<pre>";print_r($leadcalculatdata); exit;
        //end calculate invoice amount
        /*======== End Remi=========*/

        //get other open invoice
        if ($leadclient->prop_id != 0 && $leadclient->prop_id != ''){
            //DB::enableQueryLog();
  
            
             //$otherproperty = Leadclient::where('prop_id', '=', $leadclient->prop_id)
                                    //    ->where('(curr_status', '=', 'Invoiced')
                                      //   ->orWhere('curr_status', '=', '12)')
                                     //   ->get();
                                        
                                        
           
            $otherproperty =  DB::select("select * from `lead_client` where `prop_id` = '$leadclient->prop_id' and (`curr_status` = 'Invoiced' OR `curr_status` = '12')"); 
            //print_r($otherproperty); exit;
                                        
                  // dd(DB::getQueryLog()); exit;                     
        }else{
            $otherproperty = array();
        }
 
        $other_inv = '';
        if (!empty($otherproperty)){

            $other_inv = '';
            foreach ($otherproperty as $keyotherinvoice => $valueotherinvoice){

                $notes_arr = explode("~~~~", $valueotherinvoice->status_history);

                if ($valueotherinvoice->curr_status == 'Invoiced' || $valueotherinvoice->curr_status == '12'){

                    $dates = explode("~~~", $notes_arr[0]);
                    $getdate    = explode("~~", $dates[0]);
                    if (str_contains($getdate[0], '-')) { 
                        $newdate    =  explode("-",$getdate[0]);
                    }else{
                        $newdate    =  explode("/",$getdate[0]);
                    }
                    $date1 = strtotime(date('Y-m-d'));  
                    $date2 = strtotime(date('Y-m-d'));

                    if(!empty($newdate[1]) && !empty($newdate[2]) && !empty($newdate[0])){

                        $date2 = strtotime(date('Y-m-d',strtotime($newdate[0].'/'.$newdate[1].'/'.$newdate[2])));  
                    }
                }

                $str = abs($date1 - $date2);
                
                if ($str > 0){
                    $days = ceil($str / (60 * 60 * 24));

                    if ($user_role == ARUSER || $user_role == ADMIN){

                        $other_inv .= '<a href="' . url('/editclientlead/' . $valueotherinvoice->id . '/0') . '" target="_blank">' . $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . '-' . $days . ' days </a><BR>';
                    }else{

                        $other_inv .= $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . '-' . $days . ' days <BR>';
                    }
                }else{
                    if ($user_role == ARUSER || $user_role == ADMIN){

                        $other_inv .= '<a href="' . url('/editclientlead/' . $valueotherinvoice->id . '/0') . '" target="_blank">' . $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . "- 1 day</a><BR>";
                    }else{

                        $other_inv .= $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . "- 1 day<BR>";
                    }
                }
            }
        }

        $user_role          =   Auth::user()->user_role;
        $agent              =   User::where('id', '=', $leadclient->agent_id) ->first();
        $source             =   User::where('id', '=', $leadclient->source_id)->first();
        
       // echo "<pre>";print_r($leadclient); exit;
        
        if (!empty($source)){
          $source_name      = $source->name . ' ' . $source->last_name;
        }else{
            $source_name    = $agent->name . ' ' . $agent->last_name;
        }

        if ($user_role == ARUSER || $user_role == SUPERADMIN || $user_role == ADMIN){
            $role = 1;
        }else{
            $role = 0;
        }

        $leadcal = Leadclientcalculation::where('leadclient_id', $leadclient->id)->first();
        if (!empty($leadcal)){
          $updateLeadclient = Leadclientcalculation::where('leadclient_id', $leadclient->id)
                                                    ->update($leadcalculatdata);
        }else{
            $leadcalculatdata['leadclient_id'] = $leadclient->id;
            $updateLeadclient = Leadclientcalculation::insert($leadcalculatdata);
        }

        //end calculate house cost
        if ($agent_id > 0){
            if ($id1 == 1){
                $agent_id = $leadclient->agent_id;
            }
        }

        $leadcalculatdata['paid_date'] = '';
        if ($leadclient->status_history != ''){

            $getfirst   = explode('~~~~', $leadclient->status_history);
            $getdate    = explode("~~", $getfirst[0]);
            if (str_contains($getdate[0], '-')) { 
                $newdate    =  explode("-",$getdate[0]);
            }else{
                $newdate    =  explode("/",$getdate[0]);
            }
            
            $date1 = strtotime(date('Y-m-d'));  
            $date2 = strtotime(date('Y-m-d'));

            if(!empty($newdate[1]) && !empty($newdate[2]) && !empty($newdate[0])){

                $date2 = strtotime(date('Y-m-d',strtotime($newdate[0].'/'.$newdate[1].'/'.$newdate[2])));  
            }

            $diff       = abs($date2 - $date1);
            $statusdays = ceil($diff / 86400);
            $leadclient->days_status = $statusdays;

            for ($z = 0;$z < count($getfirst);$z++){
                $getpaiddate = explode("~~", $getfirst[$z]);
                if (in_array("Pay Received", $getpaiddate) || in_array("Paid Out", $getpaiddate) || in_array("13", $getpaiddate) || in_array("14", $getpaiddate)){

                    $leadcalculatdata['paid_date'] = $getpaiddate[0];
                }
            }
        }else{
            $leadclient->days_status = '';
        }

        //echo $leadclient->prop_id; exit;
        if(!empty($leadclient->prop_id)){
            $prop_notes =   CollectionDetails::where('company_id', Auth::user()->company)
                                        ->where('property_id', $leadclient->prop_id)
                                        ->whereNotNull('collection_details')
                                        ->OrderBy('id', 'desc')
                                        ->get()
                                        ->all();
        }else{
            $prop_notes =   CollectionDetails::where('company_id', Auth::user()->company)
                                        ->where('lead_id', $id)
                                        ->whereNotNull('collection_details')
                                        ->OrderBy('id', 'desc')
                                        ->get()
                                        ->all();
        }
        
                                        
                                        
        if (Auth::User()->user_role == "2" || Auth::User()->user_role == "4")
        {
            
            $usercompany    = Auth::User()->company;
            $agentcompany   = $agent->company;

            if ($agentcompany != $usercompany)
            {
              return redirect()->route('leadclient');
            }
        }

        if (Auth::User()->user_role == "3")
        {
            $userd          = Auth::User()->id;
            $compnay        = Auth::user()->company;
            $sss            = Leadclient::where('agent_id', '=', $userd)->get();
            $user_company   = User::find($leadclient->agent_id);

            $leadcalculatdata['invoicing_cost'] = (float) $agent_invoice_cost;
            if ($user_company->company != $company)
            {
                return redirect()->back();
            }else{


//->where('status', '=', 1)->whereNotIn('id', [16,17])->orderBy('position', 'ASC')
    if (Auth::User()->user_role == "3" && empty(Auth::User()->manage_manager)){
     
        $current_status = DB::table('lead_status')
        ->select('id', 'status_name','cost','new_status_name')
        ->where('status', '=', 1)
        
        //->whereNotIn('id', [11,12,13,14,15])
        
        ->orderBy('position', 'ASC')
        ->get(); 
        
        
    }else if (Auth::User()->user_role == "3" && Auth::User()->manage_manager==1){
       
         $current_status = DB::table('lead_status')
        ->select('id', 'status_name','cost','new_status_name')
        ->where('status', '=', 1) 
        ->orderBy('position', 'ASC')
        ->get();
    } else{
        $current_status = DB::table('lead_status')
        ->select('id', 'status_name','cost','new_status_name')
        ->where('status', '=', 1) 
       
        ->orderBy('position', 'ASC')
        ->get();
    }
    
        if($user_role  ==  SUPERADMIN){
        
            $companyid      =   0;
            $company_name   =   '';
        }else{
        
            $companyid          =   Auth::user()->company;
            $company_name       =   Company::find($companyid);
            if(!empty($company_name)){
                $company_name     =   $company_name->mgmt_name;
            }else{
                $company_name     =   '';
            }
        }
        
        
        $mgmt_company  =  Company::where('company_type',2)->OrderBy('mgmt_name','ASC')->get();
        $real_company =  Company::where('company_type',1)->OrderBy('mgmt_name','ASC')->get();


    //echo "<pre>";print_r(Auth::user()->user_role); exit;     
        $id         = Auth::user()->id;
        $agent_id   = $id;
    // if (Auth::user()->user_role == AGENT)
    //     {
            
    //         Session::put('agent_id', Auth::user()->id);

    //         if (Auth::user()->manage_manager == 1){

    //             $agents = Auth::user()->agents_to_manager;
    //             $agents = explode(',', $agents);
    //             if (empty($agents)){
    //                 $agents = array(0);
    //             }

    //             $useragent  =   User::where('user_role', '=', 3)
    //                                     ->where('id', '=', $id)
    //                                     ->where('status', '=', 1)
    //                                     ->orWhere(function ($query) use ($agents){
    //                                         $query->select('*')
    //                                                 ->whereIn('id', $agents);
    //                                     })
    //                                     ->orderBy('name', 'ASC')
    //                                     ->get();   
                                        
               
    //         }else{
    //             $useragent  =   User::where('user_role', '=', 3)
    //                                     ->where('id', '=', $id)
    //                                     ->where('status', '=', 1)
    //                                     ->orderBy('name', 'ASC')
    //                                     ->get();
    //         }
    //     }elseif (Auth::user()->user_role == ARUSER){

    //         $useragent  =   User::where('user_role', '=', 3)
    //                             ->where('assign_to_ar', Auth::user()->id)
    //                             ->where('status', '=', 1)
    //                             ->orderBy('name', 'ASC')
    //                             ->get();
    //     }elseif (Auth::user()->user_role == ADMIN){

    //         $useragent  =   User::where('user_role', '=', 3)
    //                             ->where('users.create_by_user', Auth::user()->id)
    //                             ->where('status', '=', 1)
    //                             ->orderBy('name', 'ASC')
    //                             ->get();
    //     }else{
    //         $useragent  =   User::where('user_role', '=', 3)
    //                             ->orderBy('name', 'ASC')
    //                             ->get();
    //     }
        
        $user_agent_ids=array();
        
        if(!empty($leadclient->agent_id)){
      
            $useragent  =   User::where('id', '=', $leadclient->agent_id)
                                ->where('status', '=', 1)
                                ->orderBy('name', 'ASC')
                                ->get();
            // array_push($user_agent_ids,$useragent[0]->id);
            
            if(!empty($useragent[0]->assign_to_ar)){
                array_push($user_agent_ids,$useragent[0]->assign_to_ar); 
            }
            
            if(!empty($useragent[0]->agents_to_manager)){
                array_push($user_agent_ids,$useragent[0]->agents_to_manager); 
            }

            if(!empty($useragent[0]->create_by_user)){
                array_push($user_agent_ids,$useragent[0]->create_by_user); 
            }
            
            if(!empty($user_agent_ids)){
                $user_agent_ids = implode(',',$user_agent_ids);
                $user_agent_ids = explode(',',$user_agent_ids);
            }
            
        }
        
        
        $useragent  =   User::whereIn('id', $user_agent_ids)
                            ->where('status', '=', 1)
                            ->orderBy('name', 'ASC')
                            ->get();
                            
                            
            $id = $leadclient->agent_id;
            $user  =   User::find($id); 
            if((Auth::user()->user_role == SUPERADMIN) && (Auth::user()->user_role == ADMIN)){
                   
                $under_contract = (!empty($user->under_contract)?$user->under_contract:'');
                $verify_lease   = (!empty($user->verify_lease)?$user->verify_lease:'');
            
            }else{
             
            	$users = User::find($user->create_by_user);
            	 
            	$under_contract = (!empty($users->under_contract)?$users->under_contract:'');
            	$verify_lease  = (!empty($users->verify_lease)?$users->verify_lease:'');
            }
            //echo  "under_contract ".$under_contract."  vl ".$under_contract; exit;
        

            return view('leadclient.editleadclient', 
                    [
                        'prop_notes'           =>  $prop_notes, 
                        'leadclient'           =>  $leadclient, 
                        'disablebtn'           =>  $disablebtn, 
                        'assignar'             =>  $assignar, 
                        'leadcalculatdata'     =>  $leadcalculatdata, 
                        'states'               =>  $state, 
                        'propertylead'         =>  $propertylead, 
                        'agentemailcreate'     =>  $agentemailcreate, 
                        'propertys'            =>  $property, 
                        'companylead'          =>  $companylead, 
                        'other_inv'            =>  $other_inv, 
                        'show_table'           =>  $id1, 
                        'agent_name'           =>  $agent->name . ' '.$agent->last_name, 
                        'source_name'          =>  $source_name, 
                        'role'                 =>  $role, 
                        'agent_id'             =>  session('aragentsearch') ?? $agent_id, 
                        'email_log'            =>  $email_log, 
                        'invoice_log'          =>  $invoice_log, 
                        'current_status'       =>  $current_status,
                        'agentdetail'          =>  $agent,
                        'mgmt_company'  =>  $mgmt_company,
                        'real_company'  =>  $real_company,
                        'company_id'    =>  $companyid,
                        'company_name'  =>  $company_name,
                        'useragent'     => $useragent,
                        'under_contract'=>$under_contract,
                        'verify_lease'=>$verify_lease
                    ]);
            }
        }else{

            $leadcalculatdata['invoicing_cost'] = (float) $agent_invoice_cost;
            
        //echo "<pre>"; print_r($leadcalculatdata); exit;
    if (Auth::User()->user_role == "3" && empty(Auth::User()->manage_manager)){
        
        if (empty($leadclient->transaction_type_id)){
            
            $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1)
            //->whereNotIn('id', [11,12,13,14,15])
            ->orderBy('position', 'ASC')
            ->get();
            
        }else if ($leadclient->transaction_type_id == 1){
           
             $current_status = DB::table('lead_status')
                ->select('id', 'status_name','cost','new_status_name')
                ->where('status', '=', 1)
               //->whereNotIn('id', [11,12,13,14,15,16])
                ->orderBy('position', 'ASC')
                ->get(); 
        
        }else if($leadclient->transaction_type_id == 3){
            $current_status = DB::table('lead_status')
                ->select('id', 'status_name','cost','new_status_name')
                ->where('status', '=', 1)
                //->whereNotIn('id', [11,12,13,14,15,17])
                ->orderBy('position', 'ASC')
                ->get(); 
            
        }else {
           
            $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1)
            //->whereNotIn('id', [16,17])
            ->orderBy('position', 'ASC')
            ->get(); 
        }
        
        
    }else if (Auth::User()->user_role == "3" && Auth::User()->manage_manager==1){
        
        
        if (empty($leadclient->transaction_type_id)){
            
            $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1) 
           
            ->orderBy('position', 'ASC')
            ->get();
            
        }else if ($leadclient->transaction_type_id == 1){
           
             $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1)
            //->whereNotIn('id', [16])
            ->orderBy('position', 'ASC')
            ->get();
        
        }else if($leadclient->transaction_type_id == 3){
             $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1)
            //->whereNotIn('id', [17])
            ->orderBy('position', 'ASC')
            ->get();
            
        }else {
           
            $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1) 
            // ->whereNotIn('id', [16,17])
            ->orderBy('position', 'ASC')
            ->get();
        }
        
        
    } else{
        
        if (empty($leadclient->transaction_type_id)){
            
            $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1)
          
            ->orderBy('position', 'ASC')
            ->get();
            
        }else if ($leadclient->transaction_type_id == 1){
           
            $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1)
            //->whereNotIn('id', [16])
            ->orderBy('position', 'ASC')
            ->get();
        
        }else if($leadclient->transaction_type_id == 3){
            $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1)
            //->whereNotIn('id', [17])
            ->orderBy('position', 'ASC')
            ->get();
            
        }else {
           
           $current_status = DB::table('lead_status')
            ->select('id', 'status_name','cost','new_status_name')
            ->where('status', '=', 1)
            //->whereNotIn('id', [16,17])
            ->orderBy('position', 'ASC')
            ->get(); 
        }
    }
        
         if($user_role  ==  SUPERADMIN){
        
            $companyid      =   0;
            $company_name   =   '';
        }else{
        
            $companyid          =   Auth::user()->company;
            $company_name       =   Company::find($companyid);
            if(!empty($company_name)){
                $company_name     =   $company_name->mgmt_name;
            }else{
                $company_name     =   '';
            }
        }

              
        $mgmt_company  =  Company::where('company_type',2)->OrderBy('mgmt_name','ASC')->get();
        $real_company =  Company::where('company_type',1)->OrderBy('mgmt_name','ASC')->get();
 

        $user_agent_ids=array();
        
        if(!empty($leadclient->agent_id)){
      
            $useragent  =   User::where('id', '=', $leadclient->agent_id)
                            ->where('status', '=', 1)->orderBy('name', 'ASC')->get();
                     
           if ( !empty ( $useragent[0]->id ) ) {
            //   echo "<pre>"; print_r($useragent); exit;       
            //     echo "Comming here "; exit;   
                array_push($user_agent_ids,$useragent[0]->id);
                array_push($user_agent_ids,$useragent[0]->create_by_user);
            
                if(!empty($useragent[0]->assign_to_ar)){
                    array_push($user_agent_ids,$useragent[0]->assign_to_ar); 
                }
                  
                if(!empty($useragent[0]->agents_to_manager)){
                    array_push($user_agent_ids,$useragent[0]->agents_to_manager); 
                }
            
                if(!empty($user_agent_ids)){
                    $user_agent_ids = implode(',',$user_agent_ids);
                    $user_agent_ids = explode(',',$user_agent_ids);
                }
            }    
        }
        
        
        $useragent  =   User::whereIn('id', $user_agent_ids)
                            ->where('status', '=', 1)
                            ->orderBy('name', 'ASC')
                            ->get();
        
        
        $id = $leadclient->agent_id;
        $user  =   User::find($id); 
        if((Auth::user()->user_role == SUPERADMIN) && (Auth::user()->user_role == ADMIN)){
               
            $under_contract = (!empty($user->under_contract)?$user->under_contract:'');
            $verify_lease   = (!empty($user->verify_lease)?$user->verify_lease:'');
        
        }else{
         
        	$users = User::find($user->create_by_user);
        	 
        	$under_contract = (!empty($users->under_contract)?$users->under_contract:'');
        	$verify_lease  = (!empty($users->verify_lease)?$users->verify_lease:'');
        }
        //echo  "under_contract ".$under_contract."  vl ".$verify_lease; exit;
            
           //echo  "<pre>"; print_r($useragent->count()); exit;

            return view('leadclient.editleadclient', 
                        [
                            'prop_notes'        =>  $prop_notes, 
                            'disablebtn'        =>  $disablebtn, 
                            'leadclient'        =>  $leadclient, 
                            'assignar'          =>  $assignar, 
                            'leadcalculatdata'  =>  $leadcalculatdata, 
                            'states'            =>  $state, 
                            'propertylead'      =>  $propertylead, 
                            'agentemailcreate'  =>  $agentemailcreate, 
                            'propertys'         =>  $property, 
                            'companylead'       =>  $companylead, 
                            'other_inv'         =>  $other_inv, 
                            'show_table'        =>  $id1, 
                            'agent_name'        =>  $agent->name . ' ' . $agent->last_name, 
                            'source_name'       =>  $source_name, 
                            'role'              =>  $role, 
                            'agent_id'          =>  session('aragentsearch') ?? $agent_id, 
                            'email_log'         =>  $email_log, 
                            'invoice_log'       =>  $invoice_log, 
                            'current_status'    =>  $current_status,
                            'agentdetail'       =>  $agent,
                            'mgmt_company'  =>  $mgmt_company,
                            'real_company'  =>  $real_company,
                            'company_id'    =>  $companyid,
                            'company_name'  =>  $company_name,
                            'useragent'     => $useragent,
                            'under_contract'=>$under_contract,
                            'verify_lease'=>$verify_lease
                        ]);
        }  
    }

    public function getfollowup($status, $id, $lead)
    {

        $agent_id       = $id;
        $useraragent    = User::find($agent_id);
        $userrole       = $useraragent->user_role;
        $user_role      = $useraragent->user_role;
        $id1            = 1;

        if ($lead == 0){
            Session::forget('leadarray');
            Session::forget('leadstatus');
        }

        if (Session::get('leadstatus') == ''){

            $array = array($lead );
            Session::put('leadarray', $array);
            Session::put('leadstatus', $status);

        }else if (Session::get('leadstatus') == $status){

            $array = Session::get('leadarray');
            array_push($array, $lead);
            Session::put('leadarray', $array);

        }elseif (Session::get('leadstatus') != $status){

            Session::put('leadstatus', $status);
            $array = array($lead);
            Session::put('leadarray', $array);
        }

        $lead = Session::get('leadarray');

        if($status == 'FOLLOW'){
            //,'Cold'
            $statusarry     =   ['New', 'Pending', 'Repeat', 'Prospect', 'Hot', 'Warm','1','2','3','4','5','7'];
            $leadclients    =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name', 'users.create_by_user')
                                        ->whereIn('curr_status', $statusarry)->where(function ($query){
                                            $query->select('*')
                                                    ->where('lead_client.contact_nxt_date', '<=', date('Y-m-d'))
                                                    ->orWhereNull('lead_client.contact_nxt_date');
                                        });
            if ($userrole == ADMIN){
                $leadclients = $leadclients->where('users.create_by_user', '=', $agent_id);
            }else{
                $leadclients = $leadclients->where('agent_id', '=', $agent_id);
            }

            $checkempty = sizeof($leadclients->get());

            if ($lead != 0){
                $leadclients = $leadclients->whereNotIn('lead_client.id', $lead);
            }

            $leadclients = $leadclients->first();

        }elseif ($status == 'LEADS'){

            $statusarry     =   ['New', 'Repeat','1','2'];
            $leadclients    =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name')
                                        ->whereIn('curr_status', $statusarry);

            
            if ($userrole == ADMIN){
                $leadclients = $leadclients->where('users.create_by_user', '=', $agent_id);
            }else{
                $leadclients = $leadclients->where('agent_id', '=', $agent_id);
            }
            $checkempty = sizeof($leadclients->get());
            
            if ($lead != 0){
                $leadclients = $leadclients->whereNotIn('lead_client.id', $lead);
            }

            $leadclients = $leadclients->first();
        }elseif ($status == 'MOVE'){
            $id1            = 0;
            $statusarry     = ['Lease Confirmed','10'];

            $leadclients    = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name')
                                        ->whereIn('curr_status', $statusarry)
                                        ->where('users.assign_to_ar', '=', $agent_id)
                                        ->where(function ($query){
                                            $query->select('*')
                                                    ->where('lead_client.ar_contact_date_next', '<=', date('Y-m-d'))
                                                    ->orWhereNull('lead_client.ar_contact_date_next');
                                        });

            $checkempty = sizeof($leadclients->get());

            if ($lead != 0){
                $leadclients    = $leadclients->whereNotIn('lead_client.id', $lead);
            }
            $leadclients        = $leadclients->first();
        }elseif ($status == 'INVOICED'){

            $id1            = 0;
            $statusarry     = ['Invoiced','12'];
            $leadclients    = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')->select('lead_client.*', 'users.name', 'users.last_name')
                ->whereIn('curr_status', $statusarry)->where('users.assign_to_ar', '=', $agent_id)->where(function ($query)
            {
                $query->select('*')
                    ->where('lead_client.ar_contact_date_next', '<=', date('Y-m-d'))
                    ->orWhereNull('lead_client.ar_contact_date_next');
            });
            
            $checkempty = sizeof($leadclients->get());
            if ($lead != 0)
            {
                $leadclients = $leadclients->whereNotIn('lead_client.id', $lead);
            }

            $leadclients = $leadclients->where('lead_client.ar_contact_date_next', '<=', date('Y-m-d'));
            $leadclients = $leadclients->first();
        }elseif ($status == 'PAY'){
            $statusarry = ['Pay Received','13'];
            $id1 = 0;
            $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')->select('lead_client.*', 'users.name', 'users.last_name')
                ->whereIn('curr_status', $statusarry)->where('users.assign_to_ar', '=', $agent_id)->where(function ($query)
            {
                $query->select('*')
                    ->where('lead_client.ar_contact_date_next', '<=', date('Y-m-d'))
                    ->orWhereNull('lead_client.ar_contact_date_next');
            });
            
            $checkempty = sizeof($leadclients->get());
            if ($lead != 0){
                $leadclients = $leadclients->whereNotIn('lead_client.id', $lead); 
            }
            
            $leadclients = $leadclients->first();
        }elseif ($status == 'SOLD'){

            $statusarry = ['Sold','9'];
            $id1 = 0;
            $leadclients = Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                ->select('lead_client.*', 'users.name', 'users.last_name')
                ->whereIn('curr_status', $statusarry)
                ->where('users.assign_to_ar', '=', $agent_id)
                ->where(function ($query){
                        $query->select('*')
                            ->where('lead_client.ar_contact_date_next', '<=', date('Y-m-d'))
                            ->orWhereNull('lead_client.ar_contact_date_next');
                    });
            $checkempty = sizeof($leadclients->get());
            if ($lead != 0){
                $leadclients = $leadclients->whereNotIn('lead_client.id', $lead);
            }
            $leadclients = $leadclients->first();
        }elseif ($status == 'SOLDS'){

            $statusarry     =   ['Sold','9'];
            $leadclients    =   Leadclient::join('users', 'users.id', '=', 'lead_client.agent_id')
                                        ->select('lead_client.*', 'users.name', 'users.last_name')
                                        ->whereIn('curr_status', $statusarry);
            if ($userrole == ADMIN){
                $leadclients = $leadclients->where('users.create_by_user', '=', $agent_id);
            }else{
                $leadclients = $leadclients->where('agent_id', '=', $agent_id);
            }

            $checkempty = sizeof($leadclients->get());
            
            if ($lead != 0){
                $leadclients = $leadclients->whereNotIn('lead_client.id', $lead);
            }

            $leadclients = $leadclients->first();
        }

        if (!empty($leadclients)){

            $leadclient     =   Leadclient::leftJoin('property', 'property.id', 'lead_client.prop_id')
                                        ->select('prop_state', 'lead_client.*')
                                        ->where('lead_client.id', $leadclients->id)
                                        ->first();
            
            $property       =   Property::orderBy('prop_name', 'ASC')->get();
            $email_log      =   DB::table('email_log')
                                    ->Where('lead_id', $leadclients->id)
                                    ->Where('mail_for', '=', 'Lease Verification')
                                    ->get();
            $invoice_log    =   DB::table('email_log')
                                    ->Where('lead_id', $leadclients->id)
                                    ->Where('mail_for', '=', 'Invoice')
                                    ->get();

            if ($leadclient->prop_id == 0 && $leadclient->prop_id == ''){

                $propertylead   = new Property;
                $companylead    = new Company;

            }else{

                $propertylead   = Property::find($leadclient->prop_id);
                $companylead    = Company::find($propertylead->prop_mgmt_co);

                if (!isset($companylead->mgmt_name)){
                    $companylead                = new Company;
                    $companylead->mgmt_name     = $propertylead->prop_mgmt_co;
                }
            }

            $agentleaddetail    =   User::find($leadclient->agent_id);
            $agentemailcreate   =   Agentemail::where('agent_id', '=', Auth::user()->id)
                                                ->where('status', '=', 1)
                                                ->orderBy('email_name', 'ASC')
                                                ->get();

            $assignar           = User::find($agentleaddetail->assign_to_ar);
            if (empty($assignar)){
                $assignar       = new User;
            }
            
            $state              = DB::table('state')
                                        ->select('id', 'state_name', 'state_value')
                                        ->get();
            $agent_status       = $agentleaddetail->user_role;
            $unit               = $agentleaddetail->unit;
            $agent_split_hous   = $agentleaddetail->broker_cost;
            $agent_split        = $agentleaddetail->broker_cost;
            $agent_invoice_cost = $leadclient->invoicing_cost;
            $incentive          = (!empty($leadclient->incentive)?$leadclient->incentive:$leadclient['incentive_lease']);
            $sold_amt           = $leadclient->sold_amt;
            $house_comm         = $leadclient->house_comm;
            $house_bonus        = $leadclient->house_bonus;

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

            /*======== Remi ===========*/
            //calculat lead cost and agent paid amount
            $lead_cost = 0;
            $agent_paid = 0;
            $house_cost = 0;

            //for calculate house cost
            //1. Total Commission = sold_amt*(house_comm/100)+house_bonus
            if ($leadclient->sold_amt > 0)
            {
                $totalcommission = $sold_amt * ($house_comm / 100) + $house_bonus;
            }

            if ($leadclient->prop_id == 0 && $leadclient->prop_id == '')
            {
                $propertylead = new Property;
                $companylead = new Company;
            }else{

                $propertylead = Property::find($leadclient->prop_id);
                $companylead = Company::find($propertylead->prop_mgmt_co);

                if (!isset($companylead->mgmt_name))
                {
                    $companylead = new Company;
                    $companylead->mgmt_name = $propertylead->prop_mgmt_co;
                }
            }

            $agentleaddetail    = User::find($leadclient->source_id);
            $agentemailcreate   = Agentemail::where('agent_id', '=', Auth::user()->id)
                                            ->where('status', '=', 1)
                                            ->orderBy('email_name', 'ASC')
                                            ->get();

            $assignar = User::find($agentleaddetail->assign_to_ar);

            if (empty($assignar)){
                $assignar = new User;
            }
            
            $state = DB::table('state')->select('id', 'state_name', 'state_value')
                ->get();

            $agent_status = $agentleaddetail->user_role;

            $unit               = $agentleaddetail->unit;
            $agent_split_hous   = $agentleaddetail->broker_cost;
            $agent_split        = $agentleaddetail->broker_cost;
            $agent_invoice_cost = $leadclient->invoicing_cost;
            $incentive          = (!empty($leadclient->incentive)?$leadclient->incentive:$leadclient['incentive_lease']);

            $sold_amt           = $leadclient->sold_amt;
            $house_comm         = $leadclient->house_comm;
            $house_bonus        = $leadclient->house_bonus;

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

            /*======== Remi ===========*/
            //calculat lead cost and agent paid amount
            $lead_cost = 0;
            $agent_paid = 0;
            $house_cost = 0;

            //calcution house_cost for house tab
            //1. Total Commission = sold_amt*(house_comm/100)+house_bonus
            if ($leadclient->sold_amt > 0){
                $totalcommission = $sold_amt * ($house_comm / 100) + $house_bonus;
            }

            if ($agent_status == 5){

                if (!empty($lead)){

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

                    $dis_split      = 0;
                    $dis_split_unit = 0;
                }

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

                    }
                    else
                    {
                        $lead_cost = $dis_split;
                        $leadclient->lead_cost = $dis_split;
                        $leadclient->agent_paid = $leadclient->payment - $agent_invoice_cost - $incentive - $leadclient->lead_cost;
                        $agent_paid = $leadclient->payment - $agent_invoice_cost - $incentive - $leadclient->lead_cost;
                    }
                }

                if ($leadclient->sold_amt != 0)
                {

                    if ($dis_split_unit == 0)
                    {
                        // $row1['lead_cost'] =  $row1['sold_amt'] * $agent_split /  100 ;
                        $dis_split = $dis_split / 100;
                        //$row1['house_cost'] = ($totalcommission - $agent_invoice_cost) *  $dis_split;
                        $house_cost = $totalcommission * $dis_split;

                    }
                    else
                    {
                        $house_cost = $dis_split;

                    }
                }

            }
            else
            {

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

                    if ($unit == 0)
                    {
                        // $row1['lead_cost'] =  $row1['payment'] * $agent_split /  100 ;
                        $agent_split = $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 = $agent_split_hous / 100;
                        $house_cost = $totalcommission * $agent_split_hous;
                    }
                    else
                    {
                        $house_cost = $agent_split_hous;

                    }
                }

            }

            //end calculat lead cost and agent paid amount
            /*======== End Remi=========*/

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

                $commission_unit = $leadclient->commision_unit;
                $commission = $leadclient->commision;
                $bonus = $leadclient->bonus;
                $rent_amount = $leadclient->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 = $rent_amount * ($commission / 100);
                        $invoiced_total = $tot_com + $bonus;
                    }
                    else
                    {

                        $invoiced_total = $bonus;

                    }
                }
                else
                {

                    $invoiced_total = $commission + $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 = $leadclient->sold_amt * ($leadclient->house_comm / 100);
                    $invoiced_total = $tot_com + $leadclient->house_bonus;
                }
                else
                {

                    $invoiced_total = $leadclient->house_bonus;

                }

            }
            else
            {

                $invoiced_total = 0;
            }
            /*======== Remi ===========*/
            //calculate invoice amount
            

            $leadcalculatdata['invoiced_total'] = $invoiced_total;
            $leadcalculatdata['house_cost'] = $house_cost;
            $leadcalculatdata['lead_cost'] = $lead_cost;
            $leadcalculatdata['agent_paid'] = $agent_paid;

            //end calculate invoice amount
            /*======== End Remi=========*/

            //get other open invoice
            

            if ($leadclient->prop_id != 0 && $leadclient->prop_id != '')
            {
               // $otherproperty = Leadclient::where('prop_id', '=', $leadclient->prop_id)
                    //->where('curr_status', '=', 'Invoiced')
                    // ->orWhere('curr_status', '=', '12')
                    //->get();
                    
                
                 $otherproperty =  DB::select("select * from `lead_client` where `prop_id` = '$leadclient->prop_id' and (`curr_status` = 'Invoiced' OR `curr_status` = '12')");  
                 
            }
            else
            {
                $otherproperty = array();
            }

            $other_inv = '';
            if (!empty($otherproperty))
            {

                $other_inv = '';
                foreach ($otherproperty as $keyotherinvoice => $valueotherinvoice)
                {

                    $notes_arr = explode("~~~~", $valueotherinvoice->status_history);

                    if ($valueotherinvoice->curr_status == 'Invoiced')
                    {

                        $dates = explode("~~", $notes_arr[0]);
                        //$datesn = $dates[0].'-'.$dates[1].'-'.$dates[2];
                        $datesn = $dates[0];
                    }

                    $str = strtotime(date("m-d-Y")) - (strtotime($datesn));
                    if ($str > 0)
                    {
                        $days = ceil($str / (60 * 60 * 24));

                        if ($user_role == ARUSER || $user_role == ADMIN)
                        {

                            $other_inv .= '<a href="' . url('/editclientlead/' . $valueotherinvoice->id . '/0') . '" target="_blank">' . $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . '-' . $days . ' days </a><BR>';

                        }
                        else
                        {

                            $other_inv .= $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . '-' . $days . ' days <BR>';

                        }

                    }
                    else
                    {
                        if ($user_role == ARUSER || $user_role == ADMIN)
                        {

                            $other_inv .= '<a href="' . url('/editclientlead/' . $valueotherinvoice->id . '/0') . '" target="_blank">' . $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . "- 1 day</a><BR>";
                        }
                        else
                        {

                            $other_inv .= $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . "- 1 day<BR>";
                        }
                    }

                }

            }

            //end other open invoice
            // echo $leadclient->source_id;
            $user_role = Auth::user()->user_role;
            $agent = User::where('id', '=', $leadclient->agent_id)
                ->first();
            $source = User::where('id', '=', $leadclient->source_id)
                ->first();
            // print_r($source); exit;
            if (!empty($source))
            {
                $source_name = $source->name . ' ' . $source->last_name;

            }
            else
            {
                $source_name = $agent->name . ' ' . $agent->last_name;
            }

            //end calculate invoice amount
            /*======== End Remi=========*/

            /*======== Remi ===========*/
            //calculat lead cost and agent paid amount
            

            if ($user_role == ARUSER || $user_role == SUPERADMIN)
            {
                $role = 1;
            }
            else
            {
                $role = 0;
            }

            $leadcal = Leadclientcalculation::where('leadclient_id', $leadclient->id)
                ->first();
            if (!empty($leadcal))
            {
                $updateLeadclient = Leadclientcalculation::where('leadclient_id', $leadclient->id)
                    ->update($leadcalculatdata);

            }
            else
            {
                $leadcalculatdata['leadclient_id'] = $leadclient->id;
                $updateLeadclient = Leadclientcalculation::insert($leadcalculatdata);
            }

            //echo $house_cost;
            //end calculate house cost
            if ($userrole == ADMIN)
            {
                $agent_id = $agent_id;
            }
            else
            {
                if ($agent_id > 0)
                {
                    if ($id1 == 1)
                    {
                        $agent_id = $leadclient->agent_id;
                    }
                }
            }
            $leadcalculatdata['paid_date'] = '';
            if ($leadclient->status_history != '')
            {
                //  $today =date('d/m/Y');
                //   //alert(today);
                $getfirst = explode('~~~~', $leadclient->status_history);
                $getdate = explode("~~", $getfirst[0]);
                $getdate = explode("-", $getdate[0]);

                $date1 = strtotime(date('Y-m-d'));
                $date2 = strtotime(date('Y-m-d'));
                if(!empty($getdate[0]) && !empty($getdate[1]) && !empty($getdate[2])){

                    $date2 = strtotime(date('Y-m-d', strtotime($getdate[0] . '/' . $getdate[1] . '/' . $getdate[2])));
                }

                $diff = abs($date2 - $date1);
                $statusdays = ceil($diff / 86400);
                $leadclient->days_status = $statusdays;

                for ($z = 0;$z < count($getfirst);$z++)
                {
                    //  alert(getfirst[z]);
                    $getpaiddate = explode("~~", $getfirst[$z]);
                    if (in_array("Pay Received", $getpaiddate) || in_array("Paid Out", $getpaiddate) || in_array("13", $getpaiddate) || in_array("14", $getpaiddate))
                    {

                        $leadcalculatdata['paid_date'] = $getpaiddate[0];
                        //     alert(getpaiddate[0]);
                        
                    }
                }

            }
            else
            {
                $leadclient->days_status = '';

            }

            // echo $agent_id; exit;
            return view('leadclient.editfollowleadclient', ['leadclient' => $leadclient, 'assignar' => $assignar, 'leadcalculatdata' => $leadcalculatdata, 'states' => $state, 'propertylead' => $propertylead, 'agentemailcreate' => $agentemailcreate, 'propertys' => $property, 'companylead' => $companylead, 'other_inv' => $other_inv, 'show_table' => $id1, 'agent_name' => $agent->name . ' ' . $agent->last_name, 'source_name' => $source_name, 'role' => $role, 'agent_id' => $agent_id, 'status' => $status, 'email_log' => $email_log, 'invoice_log' => $invoice_log, 'current_status' => DB::table('lead_status')->select('id', 'status_name','new_status_name')
                ->where('status', '=', 1)->orderBy('position', 'ASC')
                ->get() ]);
        }
        else
        {

            if ($checkempty <= 0)
            {
                Session::flash('message', "All Done ! ");
                Session::flash('alert-class', 'alert-success');
            }
            $user_role = Auth::user()->user_role;
            if ($userrole == AGENT && $user_role == AGENT)
            {
                return redirect('leadclientresult/' . $status . '/' . $agent_id);
            }
            elseif ($userrole == AGENT && ($user_role == ADMIN || $user_role == ARUSER || $user_role == SUPERADMIN))
            {
                return redirect('dashboard/AGENT');
            }
            elseif ($userrole == ARUSER && $user_role == ARUSER)
            {
                return redirect('aruser');
            }
            elseif ($userrole == ARUSER && ($user_role == ADMIN || $user_role == SUPERADMIN))
            {
                return redirect('dashboard/ARUSER');
            }
            elseif ($userrole == ADMIN && $user_role == ADMIN)
            {
                return redirect('admin');
            }
            elseif ($userrole == ADMIN && $user_role == SUPERADMIN)
            {
                return redirect('dashboard/ADMIN');
            }

        }

    }

    public function editfollow($id, $id1, $status)
    {

        $agent_id = Auth::user()->id;
        $user_role = Auth::user()->user_role;
        $leadclient = Leadclient::find($id);

        $new_record_id = Leadclient::where('duplicate_id', '=', $leadclient->id)
            ->first();
        if (!empty($new_record_id))
        {
            $leadclient->new_record_id = $new_record_id->id;
        }
        else
        {
            $leadclient->new_record_id = 0;
        }

        if ($user_role == SUPERADMIN)
        {
            // $property = Property::all(); //commented by vinod
            $property = Property::orderBy('prop_name', 'ASC')->get();
        }
        else
        {
            $company = Auth::user()->company;
            $property = Property::where('prop_mgmt_co', $company);
        }

        $property = Property::join('company', 'company.id', '=', 'property.prop_mgmt_co')->select('property.*', 'company.mgmt_name')
            ->get();

        //echo $leadclient->agent_id; exit;
        // user rights validation
        $check = User::find($leadclient->agent_id);
        // if($user_role==AGENT && $agent_id!=$leadclient->agent_id){
        //   Session::flash('message', "You Don't have rights to edit lead details");
        //   Session::flash('alert-class', 'alert-danger');
        //   return redirect('leadclient');
        // }elseif($user_role==ARUSER && $agent_id!=$check->assign_to_ar){
        //      Session::flash('message', "You Don't have rights to edit lead details");
        //      Session::flash('alert-class', 'alert-danger');
        //      return redirect('leadclient');
        

        // }elseif($user_role==ADMIN && $agent_id!=$check->create_by_user){
        //     Session::flash('message', "You Don't have rights to edit lead details");
        //      Session::flash('alert-class', 'alert-danger');
        //      return redirect('leadclient');
        // }
        if ($leadclient->prop_id == 0 && $leadclient->prop_id == '')
        {
            $propertylead = new Property;
            $companylead = new Company;
        }
        else
        {
            $propertylead = Property::find($leadclient->prop_id);
            $companylead = Company::find($propertylead->prop_mgmt_co);

            if (!isset($companylead->mgmt_name))
            {
                $companylead = new Company;
                $companylead->mgmt_name = $propertylead->prop_mgmt_co;
            }

        }

        $agentleaddetail = User::find($leadclient->agent_id);

        //$agentemailcreate   = Agentemail::where('agent_id','=',$agent_id  )->where('status','=',1)->get();
        $agentemailcreate = Agentemail::where('agent_id', '=', Auth::user()->id)
            ->where('status', '=', 1)
            ->orderBy('email_name', 'ASC')
            ->get();

        $assignar = User::find($agentleaddetail->assign_to_ar);
        if (empty($assignar))
        {
            $assignar = new User;
        }
        //$assignar         = User::find(Auth::user()->assign_to_ar);
        $state = DB::table('state')->select('id', 'state_name', 'state_value')
            ->get();

        $agent_status = $agentleaddetail->user_role;
        $unit = $agentleaddetail->unit;
        $agent_split_hous = $agentleaddetail->broker_cost;
        $agent_split = $agentleaddetail->broker_cost;
        $agent_invoice_cost = $leadclient->invoicing_cost;
        $incentive = (!empty($leadclient->incentive)?$leadclient->incentive:$leadclient['incentive_lease']);// $leadclient->incentive;

        $sold_amt = $leadclient->sold_amt;
        $house_comm = $leadclient->house_comm;
        $house_bonus = $leadclient->house_bonus;

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

        }

        /*======== Remi ===========*/
        //calculat lead cost and agent paid amount
        if ($agent_status == 5)
        {
            $lead = Distributorleadmarket::find($leadclient->lead_id_orig);
            if (!empty($lead))
            {
                $dis_split = $lead->lead_cost;
                $dis_split_unit = $lead->unit;
            }
            else
            {
                $dis_split = 0;
                $dis_split_unit = 0;
            }

            if ($leadclient->payment != 0)
            {
                if ($dis_split_unit == 0)
                {
                    // $row1['lead_cost'] =  $row1['payment'] * $agent_split /  100 ;
                    $dis_split = $dis_split / 100;
                    $leadclient->lead_cost = ($leadclient->payment - $agent_invoice_cost) * $dis_split;
                    $leadclient->agent_paid = $leadclient->payment - $agent_invoice_cost - $incentive - $leadclient->lead_cost;

                }
                else
                {
                    $leadclient->lead_cost = $dis_split;
                    $leadclient->agent_paid = $leadclient->payment - $agent_invoice_cost - $incentive - $leadclient->lead_cost;
                }
            }
            else
            {

                $lead_cost = 0;
                $agent_paid = 0;
            }
        }
        else
        {

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

                if ($unit == 0)
                {

                    // $row1['lead_cost'] =  $row1['payment'] * $agent_split /  100 ;
                    $agent_split = $agent_split_hous / 100;
                    $lead_cost = ($leadclient->payment - $agent_invoice_cost) * $agent_split;
                    $agent_paid = $leadclient->payment - $agent_invoice_cost - $incentive - $lead_cost;

                }
                else
                {
                    $lead_cost = $agent_split;
                    $agent_paid = $leadclient->payment - $agent_invoice_cost - $incentive - $lead_cost;
                }
            }
            else
            {
                $lead_cost = 0;
                $agent_paid = 0;
            }

        }

        $leadcalculatdata['lead_cost'] = $lead_cost;
        $leadcalculatdata['agent_paid'] = $agent_paid;

        //end calculat lead cost and agent paid amount
        /*======== End Remi=========*/

        /*======== Remi ===========*/
        //calculate invoice amount
        $commission_unit = $leadclient->commision_unit;
        $commission = $leadclient->commision;
        $bonus = $leadclient->bonus;
        $rent_amount = $leadclient->rent_amount;

        if ($commission_unit == '1')
        {
            if ($commission > 0)
            {
                $tot_com = $rent_amount * ($commission / 100);
                $invoiced_total = $tot_com + $bonus;
            }
            else
            {
                $invoiced_total = $bonus;
            }
        }
        else
        {
            $invoiced_total = $commission + $bonus;
        }

        $leadcalculatdata['invoiced_total'] = $invoiced_total;

        //end calculate invoice amount
        /*======== End Remi=========*/

        //for calculate house cost
        //calcution house_cost for house tab
        //1. Total Commission = sold_amt*(house_comm/100)+house_bonus
        if ($leadclient->sold_amt > 0)
        {
            $totalcommission = $sold_amt * ($house_comm / 100) + $house_bonus;
        }

        if ($agent_status == 5)
        {
            $lead = Distributorleadmarket::find($leadclient->lead_id_orig);
            if (!empty($lead))
            {
                $dis_split = $lead->lead_cost;
                $dis_split_unit = $lead->unit;
            }
            else
            {
                $dis_split = 0;
                $dis_split_unit = 0;
            }

            if ($leadclient->sold_amt != 0)
            {

                if ($dis_split_unit == 0)
                {
                    // $row1['lead_cost'] =  $row1['sold_amt'] * $agent_split /  100 ;
                    $dis_split = $dis_split / 100;
                    //$row1['house_cost'] = ($totalcommission - $agent_invoice_cost) *  $dis_split;
                    $house_cost = $totalcommission * $dis_split;

                }
                else
                {
                    $house_cost = $dis_split;

                }
            }
            else
            {
                $house_cost = 0;

            }
        }
        else
        {

            if ($leadclient->sold_amt != 0)
            {

                if ($unit == 0)
                {
                    $agent_split_hous = $agent_split_hous / 100;
                    $house_cost = $totalcommission * $agent_split_hous;
                }
                else
                {
                    $house_cost = $agent_split_hous;

                }
            }
            else
            {
                $house_cost = 0;

            }

        }
        //get other open invoice
            
 //DB::enableQueryLog();

        //$otherproperty = Leadclient::where('prop_id', '=', $leadclient->prop_id)
          //  ->where('curr_status', '=', 'Invoiced')
          //  ->orWhere('curr_status', '=', '12')
          //  ->get();
            
           $otherproperty =  DB::select("select * from `lead_client` where `prop_id` = '$leadclient->prop_id' and (`curr_status` = 'Invoiced' OR `curr_status` = '12')");  
            
//dd(DB::getQueryLog()); exit;
        if (!empty($otherproperty))
        {
            $other_inv = '';
            foreach ($otherproperty as $keyotherinvoice => $valueotherinvoice)
            {

                $notes_arr = explode("~~~~", $valueotherinvoice->status_history);

                if ($valueotherinvoice->curr_status == 'Invoiced' || $valueotherinvoice->curr_status == '12')
                {

                    $dates = explode("~~", $notes_arr[0]);
                    // $datesn = $dates[0].'-'.$dates[1].'-'.$dates[2];
                    $datesn = $dates[0];

                }

                $str = strtotime(date("m-d-Y")) - (strtotime($datesn));
                if ($str > 0)
                {
                    $days = ceil($str / (60 * 60 * 24));

                    if ($user_role == ARUSER || $user_role == ADMIN)
                    {
                        $other_inv .= '<a href="' . url('/editclientlead/' . $valueotherinvoice->id . '/0') . '" target="_blank">' . $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . '-' . $days . ' days </a><BR>';

                    }
                    else
                    {
                        $other_inv .= $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . '-' . $days . ' days <BR>';

                    }

                }
                else
                {
                    if ($user_role == ARUSER || $user_role == ADMIN)
                    {

                        $other_inv .= '<a href="' . url('/editclientlead/' . $valueotherinvoice->id . '/0') . '" target="_blank">' . $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . "- 1 day</a><BR>";
                    }
                    else
                    {

                        $other_inv .= $valueotherinvoice->fname . ' ' . $valueotherinvoice->lname . "- 1 day<BR>";
                    }
                }

            }

        }
        else
        {
            $other_inv = '';
        }

        //end other open invoice
        // echo $leadclient->source_id;
        $user_role = Auth::user()->user_role;
        $agent = User::where('id', '=', $leadclient->agent_id)
            ->first();
        $source = User::where('id', '=', $leadclient->source_id)
            ->first();
        // print_r($source); exit;
        if (!empty($source))
        {
            $source_name = $source->name . ' ' . $source->last_name;

        }
        else
        {
            $source_name = $agent->name . ' ' . $agent->last_name;
        }

        if ($user_role == ARUSER || $user_role == SUPERADMIN)
        {
            $role = 1;
        }
        else
        {
            $role = 0;
        }

        $leadcalculatdata['house_cost'] = $house_cost;

        $updateLeadclient = Leadclientcalculation::where('leadclient_id', $id)->update($leadcalculatdata);

        //echo $house_cost;
        //end calculate house cost
        if ($agent_id > 0)
        {
            if ($id1 == 1)
            {
                $agent_id = $leadclient->agent_id;
            }
        }

        if ($leadclient->status_history != '')
        {
            $today = date('m/d/Y');
            //alert(today);
            $getfirst = explode('~~~~', $leadclient->status_history);
            $getdate = explode("~~", $getfirst[0]);

            $getdate = strtotime(date('m/d/Y', strtotime($getdate[0])));
            $today = strtotime($today);
            $statusdays = ($today - $getdate) / 60 / 60 / 24;

            $leadclient->days_status = $statusdays;
        }
        else
        {
            $leadclient->days_status = '';
        }
        //echo $id1; exit;
        if ($leadclient->status_history != '')
        {
            //  $today =date('d/m/Y');
            //   //alert(today);
            $getfirst = explode('~~~~', $leadclient->status_history);
            $getdate = explode("~~", $getfirst[0]);
            $getdate = explode("-", $getdate[0]);

            $date1 = strtotime(date('Y-m-d'));
            $date2 = strtotime(date('Y-m-d'));
            if(!empty($getdate[0]) && !empty($getdate[1]) && !empty($getdate[2])){

                $date2 = strtotime(date('Y-m-d', strtotime($getdate[0] . '/' . $getdate[1] . '/' . $getdate[2])));
            }

            $diff = abs($date2 - $date1);
            $statusdays = ceil($diff / 86400);
            $leadclient->days_status = $statusdays;
        }
        else
        {
            $leadclient->days_status = '';
        }

        return view('leadclient.editfollowleadclient', ['leadclient' => $leadclient, 'assignar' => $assignar, 'leadcalculatdata' => $leadcalculatdata, 'states' => $state, 'propertylead' => $propertylead, 'agentemailcreate' => $agentemailcreate, 'propertys' => $property, 'companylead' => $companylead, 'other_inv' => $other_inv, 'show_table' => $id1, 'agent_name' => $agent->name, 'source_name' => $source_name, 'role' => $role,

        'agent_id' => $agent_id, 'status' => $status, 'current_status' => DB::table('lead_status')->select('id', 'status_name','new_status_name')
            ->where('status', '=', 1)->orderBy('position', 'ASC')
            ->get() ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\model\Leadclient  $leadclient
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        
        //echo "<pre>"; print_r($_POST); exit;

        $id         = $request['id'];
        $id1        = $request['id1'];
        
        unset($request['id1']);
        unset($request['props_id']);
        unset($request['message']);
        unset($request['old_status']);
        unset($request['user_role']);
        unset($request['w9files']);

        $data = $request->input();
   
        $leadclient = Leadclient::find($id);

        if (isset($data['prop_notes']))
        {
          $notes = $data['prop_notes'];
        }
        else
        {
          $notes = '';
        }

        $agentleadsave = array();
        $tempkey = ['_token', 'send_email', 'prop_add', 'prop_city', 'prop_state', 'prop_zip', 'apt_bonus', 'apt_prop_id', 'prop_email', 'prop_phone', 'prop_fax', 'lease_email', 'lead_source', 'house_cost','clhouse_add','clcommision_unit','clhouse_city','clhouse_state','clhouse_fax','clhouse_zip','clclose_date','clb_or_s','cllease_term','clsold_amt','clhouse_comm','clhouse_bonus','cltitle','lease_email_house', 'inv_num', 'days_status', 'mgmt_name', 'property_phone', 'prop_manager', 'invoiced_total', 'paid_date', 'agent_paid', 'prop_notes', 'inv_email', 'docurl', 'apt_incentive', 'apt_reg_po', 'apt_commision_unit', 'apt_commision', 'apt_rent_amount', 'apt_lease_term', 'apt_start_date', 'apt_lease_email', 'ctitle_officer', 'ctitle_phone', 'ctitle_fax', 'ctitle_email', 'rsmls', 'rshouse_add', 'rshouse_state','rshouse_city','rshouse_zip','rsclose_date','rsb_or_s','rssold_amt','rshouse_comm','rshouse_bonus','rstitle','rstitle_add','rstitle_city','rstitle_state','rstitle_zip','rstitle_officer','rstitle_phone','rstitle_fax','rstitle_email','cs_cprop_type','rsap_method','cl_prop_type','clrent_amount','cltitle_add','cltitle_city','cltitle_state','cltitle_zip','cltitle_phone','cltitle_fax','clbroker_name','clbroker_phone','clbroker_email','clbroker_fax','cshouse_add','cshouse_state','cshouse_city','cshouse_zip','csclose_date','csb_or_s','cssold_amt','cshouse_comm','cshouse_bonus','cstitle','cstitle_add','cstitle_city','cstitle_state','cstitle_zip','cstitle_phone','cstitle_fax','cstitle_email','cstitle_officer','csap_method','rslease_email_house','cslease_email_house'];

        foreach ($data as $key => $value)
        {

            if (!in_array($key, $tempkey))
            {
                $agentleadsave[$key] = $value;

                if ($key == 'notes_history')
                {
                    if ($value != '')
                    {
                        if ($leadclient->notes_history != '')
                        {
                            $agentleadsave[$key] = date('m-d-Y') . '~~' . $value . '~~~~' . $leadclient->notes_history;
                        }
                        else
                        {

                            $agentleadsave[$key] = date('m-d-Y') . '~~' . $value;
                        }
                    }
                    else
                    {
                        $agentleadsave[$key] = $leadclient->notes_history;
                    }
                }

                // AR NOTE HISTORY
                if ($key == 'ar_notes_history')
                {
                    if ($value != '')
                    {
                        if ($leadclient->ar_notes_history != '')
                        {
                            $agentleadsave[$key] = date('m-d-Y') . '-' . $value . '~~~~' . $leadclient->ar_notes_history;
                        }
                        else
                        {

                            $agentleadsave[$key] = date('m-d-Y') . '-' . $value;
                        }
                    }
                    else
                    {
                        $agentleadsave[$key] = $leadclient->ar_notes_history;
                    }
                }

                if ($key == 'contact_nxt_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'move_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
               
                if ($key == 'paid_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'rebateform_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'rebatesent_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'ar_contact_date_next')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }

            }

            if(!empty($leadclient->curr_status) && is_numeric($leadclient->curr_status))
            {
                $leadStatus = $leadclient->curr_status;
            } else {
                $leadStatus = get_status_id($leadclient->curr_status);
            }
             
            if (!empty($data['curr_status']) && $data['curr_status'] != $leadStatus)
            {
                if ($leadclient->status_history != '')
                {
                    $agentleadsave['status_history'] = date('m-d-Y') . '~~' . get_status_name($data['curr_status']) . '~~~~' . $leadclient->status_history;
                }else{

                    $agentleadsave['status_history'] = date('m-d-Y') . '~~' . $data['curr_status'];
                }

                if ($data['curr_status'] == 'Pay Received' || $data['curr_status'] == 'Paid Out' || $data['curr_status'] == 'Invoiced' || $data['curr_status'] == '13' || $data['curr_status'] == '14' || $data['curr_status'] == '12'){
                    $agentleadsave['inv_date'] = date('Y-m-d');
                }
            }else{
                $agentleadsave['status_history'] = $leadclient->status_history;
            }
          $agentleadsave['agent_id'] = $leadclient->agent_id; 
        }
        $agentleadsave['update_by_user'] = Auth::user()->id;

        /* Apartment Lease data */
        if ($data['transaction_type_id'] == 1){  // Apartment Lease

            $agentleadsave['transaction_type_id']           = $data['transaction_type_id'];
            $agentleadsave['prop_id']                       = $data['apt_prop_id'];
            $agentleadsave['bonus']                         = $data['apt_bonus'];
            $agentleadsave['incentive']                     = $data['apt_incentive'];
            $agentleadsave['reg_po']                        = $data['apt_reg_po'];
            $agentleadsave['commision_unit']                = $data['apt_commision_unit'];
            $agentleadsave['commision']                     = $data['apt_commision'];
            $agentleadsave['rent_amount']                   = $data['apt_rent_amount'];
            $agentleadsave['apt_unit']                      = $data['apt_unit'];
            $agentleadsave['lease_term']                    = $data['apt_lease_term'];
            $agentleadsave['start_date']                    = $data['apt_start_date'] ? setdbdate($data['apt_start_date']) : NULL;
        }

        if ($data['transaction_type_id'] == 2){  // Residential Lease

            $agentleadsave['transaction_type_id']           = $data['transaction_type_id'];
            $agentleadsave['mls']                           = $data['mls'];
            $agentleadsave['house_add']                     = $data['house_add'];
            $agentleadsave['house_state']                   = $data['house_state'];
            $agentleadsave['house_city']                    = $data['house_city'];
            $agentleadsave['house_zip']                     = $data['house_zip'];
            $agentleadsave['close_date']                    = $data['close_date'] ? setdbdate($data['close_date']) : NULL;
            $agentleadsave['b_or_s']                        = $data['b_or_s'];
            $agentleadsave['sold_amt']                      = $data['sold_amt'];
            $agentleadsave['house_comm']                    = $data['house_comm'];
            $agentleadsave['house_bonus']                   = $data['house_bonus'];
            $agentleadsave['title']                         = $data['title'];
            $agentleadsave['title_add']                     = $data['title_add'];
            $agentleadsave['title_city']                    = $data['title_city'];
            $agentleadsave['title_state']                   = $data['title_state'];
            $agentleadsave['title_zip']                     = $data['title_zip'];
            $agentleadsave['incentive']                     = $data['incentive'];
            $agentleadsave['title_officer']                 = $data['title_officer'];
            $agentleadsave['title_phone']                   = $data['title_phone'];
            $agentleadsave['title_fax']                     = $data['title_fax'];
            $agentleadsave['title_email']                   = $data['title_email'];
        }

        if ($data['transaction_type_id'] == 3){  // Residential Sale

            $agentleadsave['transaction_type_id']           = $data['transaction_type_id'];
            $agentleadsave['mls']                           = (!empty($data['rsmls']) ? $data['rsmls'] : NULL);
            $agentleadsave['house_add']                     = $data['rshouse_add'];
            $agentleadsave['house_state']                   = $data['rshouse_state'];
            $agentleadsave['house_city']                    = $data['rshouse_city'];
            $agentleadsave['house_zip']                     = $data['rshouse_zip'];
            $agentleadsave['close_date']                    = $data['rsclose_date'] ? setdbdate($data['rsclose_date']) : NULL;
            $agentleadsave['b_or_s']                        = $data['rsb_or_s'];
            $agentleadsave['sold_amt']                      = $data['rssold_amt'];
            $agentleadsave['house_comm']                    = $data['rshouse_comm'];
            $agentleadsave['house_bonus']                   = $data['rshouse_bonus'];
            $agentleadsave['title']                         = $data['rstitle'];
            $agentleadsave['title_add']                     = $data['rstitle_add'];
            $agentleadsave['title_city']                    = $data['rstitle_city'];
            $agentleadsave['title_state']                   = $data['rstitle_state'];
            $agentleadsave['title_zip']                     = $data['rstitle_zip'];
            $agentleadsave['title_officer']                 = $data['rstitle_officer'];
            $agentleadsave['title_phone']                   = $data['rstitle_phone'];
            $agentleadsave['title_fax']                     = $data['rstitle_fax'];
            $agentleadsave['title_email']                   = $data['rstitle_email'];
            $agentleadsave['ap_method']                     = $data['rsap_method'];
        }

        if ($data['transaction_type_id'] == 5){  // Commercial Lease

            $agentleadsave['transaction_type_id']           = $data['transaction_type_id'];
            $agentleadsave['prop_type']                     = $data['cl_prop_type'];
            $agentleadsave['house_add']                     = $data['clhouse_add'];
            $agentleadsave['commision_unit']                = $data['clcommision_unit'];
            $agentleadsave['house_state']                   = $data['clhouse_state'];
            $agentleadsave['house_city']                    = $data['clhouse_city'];
            $agentleadsave['house_zip']                     = $data['clhouse_zip'];
            $agentleadsave['close_date']                    = $data['clclose_date'] ? setdbdate($data['clclose_date']) : NULL;
            $agentleadsave['b_or_s']                        = $data['clb_or_s'];
            $agentleadsave['rent_amount']                   = $data['clrent_amount'];
            $agentleadsave['lease_term']                    = $data['cllease_term'];
            $agentleadsave['house_comm']                    = $data['clhouse_comm'];
            $agentleadsave['title']                         = $data['cltitle'];
            $agentleadsave['title_add']                     = $data['cltitle_add'];
            $agentleadsave['title_city']                    = $data['cltitle_city'];
            $agentleadsave['title_state']                   = $data['cltitle_state'];
            $agentleadsave['title_zip']                     = $data['cltitle_zip'];
            $agentleadsave['title_phone']                   = $data['cltitle_phone'];
            $agentleadsave['title_fax']                     = (!empty($data['cltitle_fax']) ? $data['cltitle_fax'] : NULL);
            $agentleadsave['broker_name']                   = $data['clbroker_name'];
            $agentleadsave['broker_phone']                  = $data['clbroker_phone'];
            $agentleadsave['broker_email']                  = $data['clbroker_email'];
            $agentleadsave['broker_fax']                    = $data['clbroker_fax'];
        }

        if ($data['transaction_type_id'] == 6){  // Commercial Sales

            $agentleadsave['transaction_type_id']           = $data['transaction_type_id'];
            $agentleadsave['prop_type']                     = (!empty($data['cs_cprop_type'])?$data['cs_cprop_type']:NULL);
            $agentleadsave['house_add']                     = (!empty($data['cshouse_add'])?$data['cshouse_add']:NULL);
            $agentleadsave['house_state']                   = $data['cshouse_state'];
            $agentleadsave['house_city']                    = $data['cshouse_city'];
            $agentleadsave['house_zip']                     = $data['cshouse_zip'];
            $agentleadsave['close_date']                    = $data['csclose_date'] ? setdbdate($data['csclose_date']) : NULL;
            $agentleadsave['b_or_s']                        = $data['csb_or_s'];
            $agentleadsave['sold_amt']                      = $data['cssold_amt'];
            $agentleadsave['house_comm']                    = $data['cshouse_comm'];
            $agentleadsave['house_bonus']                   = $data['cshouse_bonus'];
            $agentleadsave['title']                         = $data['cstitle'];
            $agentleadsave['title_add']                     = $data['cstitle_add'];
            $agentleadsave['title_city']                    = $data['cstitle_city'];
            $agentleadsave['title_state']                   = $data['cstitle_state'];
            $agentleadsave['title_zip']                     = $data['cstitle_zip'];
            $agentleadsave['title_phone']                   = $data['cstitle_phone'];
            $agentleadsave['title_fax']                     = $data['cstitle_fax'];
            $agentleadsave['title_email']                   = $data['cstitle_email'];
            $agentleadsave['title_officer']                 = $data['cstitle_officer'];
            $agentleadsave['ap_method']                     = $data['csap_method'];   
        }

        if ($data['transaction_type_id'] == 4 || $data['transaction_type_id'] == 0){  // Reset

            $agentleadsave['transaction_type_id']           = $data['transaction_type_id'];
            $agentleadsave['mls']                           = "";
            $agentleadsave['prop_id']                       = "";
            $agentleadsave['bonus']                         = 0;
            $agentleadsave['reg_po']                        = "";
            $agentleadsave['start_date']                    = NULL;
            $agentleadsave['close_date']                    = NULL;
            $agentleadsave['prop_type']                     = "";
            $agentleadsave['house_add']                     = "";
            $agentleadsave['house_state']                   = "";
            $agentleadsave['house_city']                    = "";
            $agentleadsave['house_zip']                     = "";
            $agentleadsave['b_or_s']                        = "";
            $agentleadsave['apt_unit']                      = "";
            $agentleadsave['sold_amt']                      = 0;
            $agentleadsave['house_comm']                    = 0;
            $agentleadsave['house_bonus']                   = 0;
            $agentleadsave['commision_unit']                = "";
            $agentleadsave['commision']                     = "";
            $agentleadsave['rent_amount']                   = 0;
            $agentleadsave['title']                         = "";
            $agentleadsave['title_add']                     = "";
            $agentleadsave['title_city']                    = "";
            $agentleadsave['title_state']                   = "";
            $agentleadsave['title_zip']                     = "";
            $agentleadsave['title_phone']                   = "";
            $agentleadsave['title_fax']                     = "";
            $agentleadsave['title_email']                   = "";
            $agentleadsave['title_officer']                 = "";
            $agentleadsave['incentive']                     = 0;
            $agentleadsave['ap_method']                     = "";
            $agentleadsave['broker_name']                   = "";
            $agentleadsave['broker_phone']                  = "";
            $agentleadsave['broker_email']                  = "";
            $agentleadsave['broker_fax']                    = "";   
        }
        $agentleadsave['curr_status_cost']  = (!empty($data['curr_status_cost'])?$data['curr_status_cost']:'');
        
    
        if (!empty($data['curr_status']) && ($data['curr_status']=='Under Contract' || $data['curr_status']=='16'))
        {
            $agentleadsave['under_contract'] = (!empty($data['curr_status_cost'])?$data['curr_status_cost']:'');
        }
        
        if (!empty($data['curr_status']) && ($data['curr_status']=='Verifying Lease' || $data['curr_status']=='17'))
        {
            $agentleadsave['verify_lease'] = (!empty($data['curr_status_cost'])?$data['curr_status_cost']:'');
        }
        
        if (!empty($data['payment']))
        {
            $agentleadsave['payment'] = $data['payment'];
            
           $data['agent_paid']= (lead_calculate($data['id'],$data['payment'])['agent_paid']);
        }
        
       
        
        
        if (!empty($data['agent_paid']))
        {
            $agentleadsave['agent_paid'] = $data['agent_paid'];
        }
        
         //echo "<pre>"; print_r($agentleadsave); exit;
        if (!empty($data['invoiced_total']))
        {
            $agentleadsave['invoiced_total'] = $data['invoiced_total'];
        }
        
        if (!empty($data['deducation']))
        {
            $agentleadsave['deducation'] = $data['deducation'];
        }
        
        if (!empty($data['days_status']))
        {
            $agentleadsave['days_in_status'] = $data['days_status'];
        }
        
        if (!empty($data['prop_notes']))
        {
            $agentleadsave['prop_notes'] = $data['prop_notes'];
        }
    
        
        //echo $data['curr_status']."= ".$leadclient->curr_status; exit;
        //echo "<pre>"; print_r($_POST); exit;

        $lead_status_history            = new Leasstatus_history();
        $lead_status_history->lead_id   = $leadclient->id;
        $lead_status_history->status    = (!empty($agentleadsave['curr_status'])?get_status_name($agentleadsave['curr_status']):'');
        $lead_status_history->curr_status_cost  = (!empty($data['curr_status_cost'])?$data['curr_status_cost']:'');
        $lead_status_history->date      = date('Y-m-d');
        //date('Y-m-d',strtotime($_POST['paid_date']));
        $lead_status_history->time      = date('Y-m-d h:i:s');
    
    //echo"<pre>";print_r($data); exit;
     
        $updateLeadclient = Leadclient::where('id', $id)->update($agentleadsave);
        
        if ($updateLeadclient && ($data['curr_status'] != $leadclient->curr_status))
        {
            $lead_status_history->save();

            // if (isset($data['apt_prop_id']) && $data['apt_prop_id'] != 0)
            // {

                if ($notes != ''){

                    $prop_notes = array('collection_details' => $notes );
                        if(!empty($data['apt_prop_id'])){
                            
                            $last_collection = CollectionDetails::where('company_id', Auth::user()->company)
                                                        ->where('property_id', $data['apt_prop_id'])
                                                        ->OrderBy('id', 'desc')
                                                        ->first();
                        }else{
                            $last_collection = CollectionDetails::where('company_id', Auth::user()->company)
                                                        ->where('lead_id', $id)
                                                        ->OrderBy('id', 'desc')
                                                        ->first();
                        }
                    

                    if (!empty($last_collection)){

                      CollectionDetails::where('id', $last_collection->id)->update($prop_notes);
                    }else{

                        $collection                       = new CollectionDetails();
                        $collection->collection_details   = isset($notes) ? $notes : '';
                        $collection->company_id           = Auth::user()->company;
                        $collection->lead_id              = $id;
                        $collection->property_id          = (!empty($data['apt_prop_id'])?$data['apt_prop_id']:0);
                        // echo "<pre>"; print_r($data['apt_prop_id']); exit;
                        
                        $collection->save();
                    }
                }
            //}

            if (!empty($data['curr_status']) && ($data['curr_status'] == 'Paid Out' || $data['curr_status'] == '14')){

                if ($leadclient->curr_status != 'Paid Out' || $leadclient->curr_status != '14'){

                    $this->create_duplicate_lead($request['id']);
                }
            }

            Session::flash('message', 'Updated');
            Session::flash('alert-class', 'alert-success');
        }else{
    
            Session::flash('message', 'Updated');
            Session::flash('alert-class', 'alert-success');
            
            // Session::flash('message', 'Lead not Updated!');
            // Session::flash('alert-class', 'alert-danger');
        }
        return redirect('/editclientlead/' . $id . '/' . $id1);
    }

    public function updatefollow(Request $request, Leadclient $leadclient)
    {
        $id                     = $request['id'];
        $id1                    = $request['id1'];
        $chck_status            = $request['chckstatus'];
        unset($request['id1']);
        unset($request['props_id']);
        unset($request['chckstatus']);
        $data                   = $request->input();
        $leadclient             = Leadclient::find($id);
        $agentleadsave          = array();
        foreach ($data as $key => $value){

            if ($key != '_token' && $key != 'send_email' && $key != 'prop_add' && $key != 'prop_city' && $key != 'prop_state' && $key != 'prop_zip' && $key != 'prop_email' && $key != 'prop_phone' && $key != 'prop_fax' && $key != 'lease_email' && $key != 'lead_source' && $key != 'house_cost' && $key != 'lease_email_house' && $key != 'inv_num' && $key != 'days_status' && $key != 'mgmt_name' && $key != 'property_phone' && $key != 'prop_manager' && $key != 'invoiced_total' && $key != 'paid_date' && $key != 'agent_paid' && $key != 'prop_notes' && $key != 'inv_email' && $key != 'docurl')
            {
                $agentleadsave[$key] = $value;

                if ($key == 'notes_history')
                {
                    if ($value != '')
                    {
                        if ($leadclient->notes_history != '')
                        {
                            $agentleadsave[$key] = date('m-d-Y') . '~~' . $value . '~~~~' . $leadclient->notes_history;
                        }
                        else
                        {

                            $agentleadsave[$key] = date('m-d-Y') . '~~' . $value;
                        }
                    }
                    else
                    {
                        $agentleadsave[$key] = $leadclient->notes_history;
                    }
                }

                if ($key == 'ar_notes_history')
                {
                    if ($value != '')
                    {
                        if ($leadclient->ar_notes_history != '')
                        {
                            $agentleadsave[$key] = date('m-d-Y') . '-' . $value . '~~~~' . $leadclient->ar_notes_history;
                        }
                        else
                        {

                            $agentleadsave[$key] = date('m-d-Y') . '-' . $value;
                        }
                    }
                    else
                    {
                        $agentleadsave[$key] = $leadclient->ar_notes_history;
                    }
                }

                if ($key == 'contact_nxt_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'move_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'start_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'close_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'ar_contact_date_next')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'paid_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'rebateform_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }
                if ($key == 'rebatesent_date')
                {
                    $agentleadsave[$key] = setdbdate($value);
                }

            }

            if ($data['curr_status'] != $leadclient->curr_status)
            {
                if ($leadclient->status_history != '')
                {
                    $agentleadsave['status_history'] = date('m-d-Y') . '~~' . $data['curr_status'] . '~~~~' . $leadclient->status_history;
                }
                else
                {

                    $agentleadsave['status_history'] = date('m-d-Y') . '~~' . $data['curr_status'];
                }

                if ($data['curr_status'] == 'Pay Received' || $data['curr_status'] == 'Paid Out' || $data['curr_status'] == 'Invoiced' || $data['curr_status'] == '14' || $data['curr_status'] == '13' || $data['curr_status'] == '12')
                {
                    $agentleadsave['inv_date'] = date('Y-m-d');
                }
            }
            else
            {
                $agentleadsave['status_history'] = $leadclient->status_history;
            }

            $agentleadsave['lead_id_orig'] = 0;
            $agentleadsave['agent_id'] = $leadclient->agent_id; 
        }

        $updateLeadclient = Leadclient::where('id', $id)->update($agentleadsave);

        if ($updateLeadclient)
        {

            $lead_status_history = new Leasstatus_history();
            $lead_status_history->lead_id = $leadclient->id;
            $lead_status_history->status = $agentleadsave['curr_status'];
            $lead_status_history->curr_status_cost  = (!empty($input['curr_status_cost'])?$input['curr_status_cost']:'');
            $lead_status_history->date = date('Y-m-d');
            $lead_status_history->time = date('Y-m-d h:i:s');
            $lead_status_history->save();

            if ($data['curr_status'] == 'Paid Out' || $data['curr_status'] == '14')
            {
                $this->create_duplicate_lead($request['id']);
            }

            Session::flash('message', 'failadd');
            Session::flash('alert-class', 'alert-success');

        }
        else
        {
            Session::flash('message', 'Lead not Updated!');
            Session::flash('alert-class', 'alert-danger');

        }
        return redirect()->back();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\model\Leadclient  $leadclient
     * @return \Illuminate\Http\Response
     */
    public function destroy(Leadclient $leadclient)
    {
        //
        
    }

    public function sendemail(){
        $leadclient         = Leadclient::find($_POST['lead_id_email']);
        $agent              = Auth::user();
        $message            = $_POST['email_body'];
        $data               = array('body' => $_POST['email_body']);
        $bcc_emails         = array();

        if(isset($_POST['lease_email_bcc']) && $_POST['lease_email_bcc'] != ''){
            $bcc_emails = explode(',', $_POST['lease_email_bcc']);
        }
        
        $otherdata['subject']   = $_POST['email_sub'];
        $otherdata['to']        = $leadclient->email;
        $otherdata['from']      = $agent->email;
        $otherdata['bcc']       = $bcc_emails;
        $otherdata['from_name'] = ucfirst($agent->name) . " " . ucfirst($agent->last_name);
        $otherdata['is_important']   = (!empty($_POST['email_IMP'])?$_POST['email_IMP']:'0');
       
     
        if (!empty($_POST['send_email'])){

            $emaildata  = Agentemail::find($_POST['send_email']);
            $email_name = $emaildata->email_name;
        }else{
            $email_name = $_POST['email_name'];
        }

        $pathToFile     = asset('images/spiritre.png');

        if (sendmail($data, $otherdata, $pathToFile, '', strip_tags($message))){

            if ($email_name != ''){
                if ($leadclient->email_hist != ''){
                    $agentemailsend['email_hist'] = date('m-d-Y') . '~~' . $email_name . '~~~~' . $leadclient->email_hist;
                }else{
                    $agentemailsend['email_hist'] = date('m-d-Y') . '~~' . $email_name;
                }
            }else{
                $agentemailsend['email_hist'] = $leadclient->email_hist;
            }

            $updateLeadclient = Leadclient::where('id', $_POST['lead_id_email'])->update($agentemailsend);

            if ($updateLeadclient){
                Session::flash('message', 'smail');
                Session::flash('alert-class', 'alert-success');
            }else{
                Session::flash('message', 'nmail');
                Session::flash('alert-class', 'alert-danger');
            }
        }
    }

    public function setleaseemail()
    {

            $id             = $_POST['leas_id'];
            $mail           = $_POST['toemail'];
            $type           = $_POST['type'];
            $agent_id       = Auth::user()->id;
            $email_id       = Auth::user()->id;
            $leaddetail     = $id;
            $sendemail      = $mail;
            
            if ($type == 'lease'){
                $agentemail = Agentemail::where('email_name', '=', 'Lease Verification')->get()
                    ->first();
            }else{
                $agentemail = Agentemail::where('email_name', '=', 'CDA')->get()->first();
            }
    
            $leaddetail     =   Leadclient::find($leaddetail);
            $agentdetail    =   User::find($leaddetail->agent_id);
            $agentdetail    =   User::find($agentdetail->assign_to_ar);
    
            if (empty($agentemail)){
                $agentemail =   Agentemail::where('agent_id','=',Auth::user()->id)->first();
            }
    
            $agentemail     =   setemaildata($agentemail, $leaddetail, $agentdetail);
            
            return view('leadclient.emailtemplate', [
                'agentemail'        =>  $agentemail, 
                'toemail'           =>  $sendemail, 
                'agentemailcreate'  =>  Agentemail::where('agent_id', '=', $agent_id)
                                                    ->where('status', '=', 1)
                                                    ->orderBy('email_name', 'ASC')
                                                    ->get() ,
                'lead_id'           =>  $leaddetail->id, 
                'type'              =>  $type
            ]);
    }
    /*
    *  @function_name:   sendleaseemail
    *  @params: Request data
    *  @return:  Json response
    *  @updatedBy: Chintesh k
    */
    public function sendleaseemail()
    {
        $id                     = $_POST['leas_id'];
        $messagesend            = $_POST['message'];
        $type                   = $_POST['type'];
        $toemail                = $_POST['toemail'];
        
        $agent_id               = Auth::user()->id;
        $leadclient             = Leadclient::find($id);
        $property               = Property::find($leadclient->prop_id);
        $company_id             = User::find($leadclient->agent_id)->company;
        $company                = Company::find($company_id);
        $reg_po                 = $leadclient->reg_po;
        $bcc_emails             = array();

        if(isset($_POST['bcc_emails']) && $_POST['bcc_emails'] != ''){
            $bcc_emails = explode(',', $_POST['bcc_emails']);
        }
        /*echo "this 2<pre>"; print_r($bcc_emails);die;*/
        $total = 0;
        if (trim($leadclient->commision) == ""){
            $leadclient->commision = 0;
        }else{
            $leadclient->commision = number_format((float)$leadclient->commision, 2, '.', '');
        }

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

        $leadclient->rent_amount = number_format((float)$leadclient->rent_amount, 2, '.', '');
        $leadclient->bonus = number_format((float)$leadclient->bonus, 2, '.', '');
        $total = number_format((float)$total, 2, '.', '');
        if ($leadclient->commision_unit == "Flat Fee"){
            $leadclient->commision = "$" . $leadclient->commision;
        }

        $pdf = PDF::loadView('leadclient.apartmentLeaseVerification', ['property' => $property, 'total' => $total, 'reg_po' => $reg_po, 'clientdetail' => Auth::user() , 'company' => $company], compact('leadclient'));
        $pdf->save(storage_path('pdf/leaseverification/' . $leadclient->id . '_leaseverify.pdf'));


        $data           = array('body' => $messagesend, 'view' => 'text/plain');
        $otherdata['subject']   = 'Lease Verification for ' . $leadclient->fname . ' ' . $leadclient->lname;
       
        $otherdata['from']          = Auth::user()->email;
        $otherdata['bcc']           = $bcc_emails;
        $otherdata['from_name']     = ucfirst(Auth::user()->name) . " " . ucfirst(Auth::user()
            ->last_name);
        $otherdata['is_important']   = (!empty($_POST['email_IMP'])?$_POST['email_IMP']:'0');

        if ($type == 'Email'){
            $otherdata['to'] = $toemail;
        }else if($type == 'Fax'){
            $otherdata['to'] = preg_replace("/[^0-9]/", "", $property->prop_fax) . "@faxage.com";
        }
        
        $pathToFile = storage_path('pdf/leaseverification/' . $leadclient->id . '_leaseverify.pdf');

        if ($pathToFile){

            if ($type == 'Email'){

                if (sendmail($data, $otherdata, $pathToFile, '', strip_tags($messagesend))){
                    $data['res'] = true;
                }else{
                    $data['res'] = false;
                }

                if (isset($data['res']) && $data['res'] == true){

                    $log                = new EmailLog();
                    $log->lead_id       = $id;
                    $log->mail_from     = $type;
                    $log->email         = $toemail;
                    $log->mail_subject  = $otherdata['subject'];
                    $log->mail_text     = $messagesend;
                    $log->mail_for      = 'Lease Verification';
                    $log->cc_email      = '';
                    $log->created_at    = date('Y-m-d h:i:s');
                    $log->save();
                }
            }elseif ($type == 'Fax'){

                $file = File::get($pathToFile);
                $this->logindata('35324', '35324', 'Scab7410.');
                $this->set_fax_number($otherdata['to']);
                $this->set_fax_content($file);
                $this->set_recipient_name('bryan');

                if ($this->send_fax()){
                    $data['res'] = true;
                }else{
                    $data['res'] = false;
                }

                if (isset($data['res']) && $data['res'] == true){

                    $log                    = new EmailLog();
                    $log->lead_id           = $id;
                    $log->mail_from         = $type;
                    $log->email             = $otherdata['to'];
                    $log->mail_subject      = $otherdata['subject'];
                    $log->mail_text         = $messagesend;
                    $log->mail_for          = 'Lease Verification';
                    $log->cc_email          = '';
                    $log->created_at        = date('Y-m-d h:i:s');
                    $log->save();
                }
            }elseif ($type == 'PrintPDF'){
                if($_SERVER['SERVER_NAME'] == 'development.realm.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'development.flexsin.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'realm.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'testing.clientmgr.us'){

                    $data['link'] = url('/') . '/../storage/pdf/leaseverification/' . $leadclient->id . '_leaseverify.pdf';
                }else{
                    $data['link'] = PDFPATH . '../crmrewrite/storage/pdf/leaseverification/' . $leadclient->id . '_leaseverify.pdf';
                }
            }
            echo json_encode($data);
        }
    }

    /*
    *  @function_name:   sendhouseinfo
    *  @params: Request data
    *  @return:  Json response
    *  @updatedBy: Chintesh k
    */
    public function sendhouseinfo()
    {
        //$str_numbers_only = preg_replace("/[^\d]/", "", $_POST['invoiced_total']);
        
        

        
        $id                     = $_POST['leas_id'];
        $type                   = $_POST['type'];
        $messagesend            = $_POST['message'];
        $lease_email_house      = $_POST['lease_email_house'];
        $invoiced_total = preg_replace("/[^0-9.]/", "", $_POST['invoiced_total']);
        $bcc_emails             = array();
    //
        if(isset($_POST['lease_sent_emailbcc']) && $_POST['lease_sent_emailbcc'] != ''){
            $bcc_emails = explode(',', $_POST['lease_sent_emailbcc']);
        }
        
        
        
        /*echo "this 3<pre>"; print_r($bcc_emails);die;*/
        $agent                  = Auth::user();
        $agent_id               = Auth::user()->id;
        $leadclient             = Leadclient::find($id);
        $agentdetail            = User::find($leadclient->agent_id);
        $property               = Property::find($leadclient->prop_id);
        $company                = Company::find($agentdetail->company);
        $state_name             = DB::table('state')
                                        ->where('id', $leadclient->title_state)
                                        ->pluck('state_name')
                                        ->first();

        $sold_amts              = (float) $leadclient->sold_amt;
        $house_comms            = (float) $leadclient->house_comm;
        $house_bonuss           = (float) $leadclient->house_bonus;
        $curr_status_cost        = (float) $leadclient->curr_status_cost;
       
        $statusarrychk      =   ['Pay Received', 'Paid Out','13','14'];
        $agent_invcosts=0;
        if(in_array($leadclient->curr_status, $statusarrychk) && $leadclient->inv_date < '2021-12-01'){
            //$agent_invcosts =   (float) $leadclient->invoicing_cost;
        }else{
            //$agent_invcosts =  (float) $agentdetail->invoicing_cost;
        }
        //$agent_invcosts         = (float) $leadclient->invoicing_cost;
        $agent_name             =  $agentdetail->name .' ' .$agentdetail->last_name;

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

        if (empty($leadcalculatdata)){
            $leadcalculatdata[0]['house_cost'] = 0;
        }

        $total_commission   = ((float) $sold_amts * ((float) $house_comms / 100)) + (float) $house_bonuss;

        $net_to_agent       = (float) $total_commission - (float) $agent_invcosts - (float) $leadcalculatdata[0]['house_cost'];
        $net_commission_to_spirit_REG = (float) $agent_invcosts + (float) $leadcalculatdata[0]['house_cost'];

        $otherdata['total_commission']                  = $total_commission;
        $otherdata['net_to_agent']                      = $net_to_agent;
        $otherdata['net_commission_to_spirit_REG']      = $net_commission_to_spirit_REG;
        $otherdata['agent_invcosts']                    = $agent_invcosts;
        $otherdata['agent_name']                        = $agent_name;
        $otherdata['curr_status_cost']                  = $curr_status_cost;
        $otherdata['invoiced_total']                    = $invoiced_total;
       
        $pdf    = PDF::loadView('leadclient.houseinfopdf', 
                        [
                            'property' => $property, 
                            'clientdetail' => Auth::user() , 
                            'company' => $company, 
                            'leadcalculatdata' => $leadcalculatdata, 
                            'total_commission' => $total_commission, 
                            'otherdata' => $otherdata, 
                            'state_name' => $state_name,
                            'invoiced_total'=>$invoiced_total
                ], compact('leadclient'));

       $pdf->save(storage_path('pdf/houseinfopdf/' . $leadclient->id . '_leaseverify.pdf'));
       
        $data                       = array('body' => $messagesend);
        $otherdata['from']          = $agent->email;
        $otherdata['from_name']     = ucfirst($agent->name) . " " . ucfirst($agent->last_name);
        $otherdata['subject']       = (!empty($_POST['email_sub'])?$_POST['email_sub']:'');
        $otherdata['bcc']           = $bcc_emails;
        $otherdata['to']            = $lease_email_house;
        $pathToFile                 = storage_path('pdf/houseinfopdf/' . $leadclient->id . '_leaseverify.pdf');

        if ($pathToFile){
            if ($type == 'Email'){
                    $otherdata['is_important']   = (!empty($_POST['email_IMP'])?$_POST['email_IMP']:'0');
                if (sendmail($data, $otherdata, $pathToFile, '', strip_tags($messagesend))){
                   
                    $data['res'] = true;
                }else{
                    $data['res'] = false;
                }

                if (isset($data['res']) && $data['res'] == true){

                    $log                = new EmailLog();
                    $log->lead_id       = $id;
                    $log->mail_from     = $type;
                    $log->email         = $otherdata['to'];
                    $log->mail_subject  = $otherdata['subject'];
                    $log->mail_text     = $messagesend;
                    $log->mail_for      = (!empty($_POST['email_sub'])?$_POST['email_sub']:'CDA Emailed');
                    $log->cc_email      = '';
                    $log->created_at    = date('Y-m-d h:i:s');
                    $log->save();
                }
            }elseif ($type == 'PrintPDF'){
                if($_SERVER['SERVER_NAME'] == 'development.realm.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'development.flexsin.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'realm.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'testing.clientmgr.us'){

                    $data['link'] = url('/') . '/../storage/pdf/houseinfopdf/' . $leadclient->id . '_leaseverify.pdf';
                }else{
                    $data['link'] = PDFPATH . '../crmrewrite/storage/pdf/houseinfopdf/' . $leadclient->id . '_leaseverify.pdf';
                }
            }
            echo json_encode($data);
        }
    }

    /*
    *  @function_name:   setinvoiceemail
    *  @params: Request data
    *  @return:  Json response
    *  @updatedBy: Chintesh k
    */
    public function setinvoiceemail()
    {
        $email_id           = $_POST['email_id'];
        $leaddetail         = $_POST['lead_id'];
        $sendemail          = $_POST['sendemail'];
        // $agentemail         = Agentemail::where('agent_id', '=', Auth::user()->id)
        //                                     ->get()
        //                                     ->first();

        $leaddetail         = Leadclient::find($leaddetail);
        $agentdetail        = User::find($leaddetail->agent_id);
        $agentdetail        = User::find($agentdetail->assign_to_ar);
        
        
        
         if(Auth::user()->user_role==1 || Auth::user()->user_role==2){
           $agent_id = $leaddetail->agent_id;
        }else{
             $agent_id = Auth::user()->id;
        }
        
        $agentemail = Agentemail::where('agent_id', '=', Auth::user()->id)
                            ->get()
                            ->first();
                                            
        $agentemail         = setemaildata($agentemail, $leaddetail, $agentdetail);                             

        return view('leadclient.setinvoiceemail', [
            'agentemail'        => $agentemail, 
            'toemail'           => $sendemail, 
            'agentemailcreate'  =>  Agentemail::where('agent_id', '=', Auth::user()->id)
                                            ->where('status', '=', 1)
                                            ->orderBy('email_name', 'ASC')
                                            ->get() ,
            'lead_id'           => $leaddetail->id
        ]);
    }

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

        $id             =   $request->input('leas_id');
        $type           =   $request->input('type');
        $email_id       =   $request->input('email_id');
        $send_email     =   $request->input('send_email');
        $email_to       =   $request->input('email_to');
        $email_sub      =   $request->input('email_sub');
        $messagesend    =   $_POST['email_body'];
        $bcc_emails     =   array();
        
    //print_r($_POST); exit;
        if(isset($_POST['bcc_email']) && $_POST['bcc_email'] != ''){
            $bcc_emails = explode(',', $_POST['bcc_email']);
        }
        
        
        //print_r($_POST); exit;
        
        /*echo "this 4<pre>"; print_r($bcc_emails);die;*/
        if($type == 'Email' && ($send_email == null || $email_sub == null || $messagesend == null)){
          $resdata['res'] = false;
          echo json_encode($resdata);die;
        }

        /* Get logged in user id & company */
        $agent_id       =   Auth::user()->id;
        $company        =   Auth::user()->company;
        $leadclient     =   Leadclient::find($id);
        $agentdetail    =   User::find($leadclient->agent_id);
        
        $collection     =   CollectionDetails::where('property_id', $leadclient->prop_id)
                                        ->where('company_id', $company)
                                        ->OrderBy('id', 'desc')
                                        ->first();

        $vendor         =   VendorDetails::where('property_id', $leadclient->prop_id)
                                ->where('company_id', $company)
                                ->OrderBy('id', 'desc')
                                ->first();

        $property       =   Property::find($leadclient->prop_id);
        $real_state     =   Company::find(Auth::user()->company);

        if (empty($property)){
            
            $property   = (object) array(
                'prop_name'             => '',
                'bill_add'              => '',
                'bill_city'             => '',
                'bill_state'            => '',
                'prop_phone'            => '',
                'prop_fax'              => '',
                'prop_manager'          => '',
                'bill_zip'              => ''
            );

            $company    = array();
        }

        /* Get the details of client and company */
        $agent_id       = $leadclient->agent_id;
        $leadagent      = User::find($agent_id);
        $company        = Company::find($leadagent->company);

        if (!empty($collection)){
          $collection_notes = $collection->collection_details;
        }else{
          $collection_notes = '';
        }

        if (!empty($vendor)){
          $vendor_id    = $vendor->vendor_id;
        }else{
          $vendor_id    = '';
        }

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

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

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

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

            $tot_com                    = (float) $leadclient->commision;
            $total                      = (float) $leadclient->commision + (float) $leadclient->bonus;
            $leadclient->commision_unit = "Flat Fee";
        }
        
        /* Get all related data here for calculation  */
        $leadclient->commision      =   number_format((float)$leadclient->commision, 2, '.', '');
        $leadclient->tot_com        =   number_format((float)$leadclient->tot_com, 2, '.', '');
        $leadclient->rent_amount    =   number_format((float)$leadclient->rent_amount,2, '.', '');
        $leadclient->bonus          =   number_format((float)$leadclient->bonus, 2, '.', '');
        $total                      =   number_format((float)$total, 2, '.', '');
        $date                       =   date("m/d/Y");
        
        if ($leadclient->commision_unit == "Flat Fee"){
          $leadclient->commision = "$" . $leadclient->commision;
        }

        /* calculate total commision here */
        $otherdata['tot_com'] = (float) $tot_com;
        $otherdata['total']   = (float) $total;

        $pdf    =   PDF::loadView('leadclient.invoicepdf', 
                                [
                                    'property'          =>  $property, 
                                    'clientdetail'      =>  Auth::user() , 
                                    'leadclient'        =>  $leadclient, 
                                    'agentdetail'       =>  $agentdetail, 
                                    'otherdata'         =>  $otherdata, 
                                    'company'           =>  $company, 
                                    'collection_notes'  =>  $collection_notes, 
                                    'vendor_id'         =>  $vendor_id
                                ],

        compact('leadclient'));
        $pdf->save(storage_path('pdf/invoicepdf/' . $leadclient->id . '_leaseverify.pdf'));

        $files = request()->file();
        /* Check if user upload more files to send as an attachments */
        if (!empty($files)){

            foreach ($files as $key => $value){

                $lead_id        = 2;
                $filedetail     = request()->file($key);
                $nameonly       = preg_replace("/[^a-zA-Z0-9.]/", "",preg_replace('/\..+$/', '', $filedetail->getClientOriginalName())).'_'.substr(time(),-3).'_'.$leadclient->id.'_'.$key;
                $imageName      = $nameonly.'.'.$filedetail->getClientOriginalExtension();
                $filedetail->move(storage_path('pdf/invoicedocument/'),$imageName);
                $imgarr[]     = storage_path('pdf/invoicedocument/'.$imageName);
            }
        }else{
            $imgarr = array();
        }
        
        $data                       = Auth::user();
        $otherdata['from']          = $data->email;
        $otherdata['bcc']           = $bcc_emails;
        $otherdata['from_name']     = ucfirst($data->name) . " " . ucfirst($data->last_name);
        $data                       = array('body' => $messagesend );
        $otherdata['subject']       = $email_sub;
    
        
        if ($type == 'Email'){
          $otherdata['to'] = $email_to;
        }else if ($type == 'Fax'){
            
            
            if(!empty($property->prop_fax)){
                $fax_no = $property->prop_fax;
            }else if(!empty($leadclient->title_fax)){
                $fax_no = $leadclient->title_fax;
            }else{
                $fax_no = $leadclient->broker_fax;
            }
            //echo "<pre>"; print_r($leadclient); exit;
          $otherdata['to'] = preg_replace("/[^0-9]/","",$fax_no)."@faxage.com";
        }

        /* path to the invoice file attached to email.*/
        $pathToFile = storage_path('pdf/invoicepdf/'.$leadclient->id.'_leaseverify.pdf');

        if ($pathToFile){
            
          if ($type == 'Email'){
              
            $otherdata['is_important']   = (!empty($_POST['email_IMP'])?$_POST['email_IMP']:'0');
            if (sendmail($data, $otherdata, $pathToFile, $imgarr, strip_tags($messagesend))){
              $data['res'] = true;
            }else{
              $data['res'] = false;
            }

            if (isset($data['res']) && $data['res'] == true){

              $log                = new EmailLog();
              $log->lead_id       = $id;
              $log->mail_from     = $type;
              $log->email         = $otherdata['to'];
              $log->mail_subject  = $otherdata['subject'];
              $log->mail_text     = $messagesend;
              $log->mail_for      = 'Invoice';
              $log->cc_email      = '';
              $log->created_at    = date('Y-m-d h:i:s');
              $log->save();
            }
          }elseif ($type == 'Fax'){

            $file     = File::get($pathToFile);
            $message  = strip_tags($messagesend);
            $this->logindata('35324', '35324', 'Scab7410.');
            $this->set_fax_number($otherdata['to']);
            $this->set_fax_content($file);
            $this->set_recipient_name('bryan');

            if ($this->send_fax()){
                $data['res'] = true;
            }else{
                $data['res'] = false;
            }

            if (isset($data['res']) && $data['res'] == true){

                $log                  = new EmailLog();
                $log->lead_id         = $id;
                $log->mail_from       = $type;
                $log->email           = $otherdata['to'];
                $log->mail_subject    = $otherdata['subject'];
                $log->mail_text       = $messagesend;
                $log->mail_for        = 'Invoice';
                $log->cc_email        = '';
                $log->created_at      = date('Y-m-d h:i:s');
                $log->save();
            }
          }elseif ($type == 'PrintPDF'){
            
            if($_SERVER['SERVER_NAME'] == 'development.realm.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'development.flexsin.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'realm.clientmgr.us' || $_SERVER['SERVER_NAME'] == 'testing.clientmgr.us'){

                //$data['link'] = PDFPATH . '../storage/pdf/invoicepdf/'.$leadclient->id . '_leaseverify.pdf';
                
                $data['link'] =  url('/'). '/../storage/pdf/invoicepdf/'.$leadclient->id . '_leaseverify.pdf';
            }else{
                $data['link'] =  PDFPATH. '../crmrewrite/storage/pdf/invoicepdf/'.$leadclient->id . '_leaseverify.pdf';
            }
          }
          
          //print_r($data); exit;
          echo json_encode($data);
        }
    }

/*
*  @function:  documentupload
*  @params: Request data
*  @return: json response with status
*  @updatedBy: Chintesh k
*/
    public function documentupload(Request $request){
        
        $request->file('uploadfiles');
        $validation = Validator::make($request->all() , ['uploadfiles' => 'required']);

        if ($validation->passes()){

            $request->input();
            $lead_id    = $request->input('lead_id');
            $uploadpath = uploadedocumentpath($lead_id);
            if (!File::exists($uploadpath)){
              File::makeDirectory($uploadpath, 0777, true, true);
            }
    
        
    
            /* for check old uploaded data */
            $leaddetail           = Leadclient::find($lead_id);
            if (!empty($leaddetail)){
              $leaddetaildoc = json_decode($leaddetail->document_upload);
            }

            $icou = 0;
            foreach ($request->file('uploadfiles') as $key => $image){

                $nameonly = preg_replace("/[^a-zA-Z0-9.]/", "",preg_replace('/\..+$/', '', $image->getClientOriginalName())).'_'.substr(time(),-3).'_'.$leaddetail->id . '_' . $key;
                
                $name = $nameonly.'.'.$image->getClientOriginalExtension();
                
                $image->move($uploadpath, $name);
                $leaddetaildoc[] = $name;
                $icou++;
            }

            $updatedocument['document_upload']  = json_encode($leaddetaildoc);
            
           // echo "<pre>"; print_r($updatedocument);exit;
            
            $updateLeadclient                   = Leadclient::where('id', $lead_id)->update($updatedocument);

            if ($updateLeadclient){
                $view_show = view('leadclient.showadddoc', ['updatedocument' => json_encode($leaddetaildoc) , 'leaddetail' => $leaddetail])->render();
                return response()
                    ->json(['status'=> 1,'message' => 'All Done! Documents uploaded successfully!', 'class_name' => 'alert-success', 'docshow' => $view_show, 'icou' => $icou, ]);
            }
        }else{
            return response()->json(['status'=> 0, 'message' => "Please upload some documents." , 'class_name' => 'alert-danger']);
        }
    }

    /*
*  @function:  getLeadScraper
*  @params: Request data
*  @return: json response with status
*  @createdBy: Chintesh k
*/
    public function getLeadScraper(Request $request){
        
        try{
            
            $request->input();
            $email_address      = $request->input('email_address');
            $password           = $request->input('password');
            $lead_source        = $request->input('lead_source');
            $lead_cost          = $request->input('lead_cost');

            if ($email_address && $password){

                /* Code to read mailbox for Distributor */
                $distributor    =   User::where([
                                        'email'                 =>  $email_address,
                                        'user_role'             =>  AGENT,
                                        'manage_distributor'    =>  1,
                                        'status'                =>  1
                                    ])->first();
                if($distributor){

                    set_time_limit(0);
                    ini_set('memory_limit','500M');

                    $ondate             = date("j F Y"); 
                    $matchsubjectstr    = 'Zumper tenant lead';
                    $subsearchstr       = 'UNSEEN SUBJECT "'.$matchsubjectstr.'"';
                    $imap               = imap_open("{mail.spiritre.com:993/imap/ssl/novalidate-cert}INBOX", $email_address, $password) or die('Cannot connect to MailBox: ' . imap_last_error());

                    $msgs           = imap_search($imap, $subsearchstr);
                    $no_of_msgs     = $msgs ? count($msgs) : 0;

                    if ($no_of_msgs){
        
                        for ($i = 0; $i < $no_of_msgs; $i++) {
                            // Get Message Unique ID in case mail box changes in the middle of this operation
                            $message_id = $msgs[$i];
                            $header     = imap_header($imap,$msgs[$i]);
                            $mailbody   = quoted_printable_decode(imap_body($imap, $message_id));
                            $string     = preg_replace( "/\n\s+/", "\n", rtrim(html_entity_decode(strip_tags($mailbody))));
                             
                            $prettydate = date("Y-m-d H:i:s", $header->udate);
                            $replacearr = ["Property","Floorplan of Interest","Estimated Move Date"];
                            $string     =   str_replace($replacearr, "", $string);
                            $parsedstring = $this->get_string_between($string, 'Lead via', 'All of your leads, in one place');
                            $str_arr2 = explode("\n",$parsedstring);
                            $lead_arr = array_values(array_filter($str_arr2));
                            
                            if(count($lead_arr) > 0){

                                unset($lead_arr[0]);
                                $lead_arr = array_values($lead_arr);
                
                                $unit          = 0;
                                $rep_arr       = ['$',',','+','(',') ','-'];
                                $lead_name     = $lead_arr[0];
                               
                                if (!filter_var($lead_arr[1], FILTER_VALIDATE_EMAIL)) {
                                    
                                    $lead_estimated  = $lead_arr[4] == 'Unknown' ? 'N/A': $lead_arr[4];
                                    $lead_email = 'no_email@spiritre.com';
                                    $lead_phone = str_replace($rep_arr, '',$lead_arr[1]);
                                    $lead_area  = $lead_arr[2] ? explode(':',$lead_arr[2])[0] : 'N/A';
                                    $lead_desc  = 'Property: '.$lead_arr[2] . ' ----More Details : '.$lead_arr[3]. ' ----Estimated Move Date : '.$lead_estimated .' ----Message : '.$lead_arr[5].' => '.$lead_arr[6];
                                    $lead_rent  = $lead_arr[3] ? str_replace($rep_arr, '', explode('|',$lead_arr[3])[0]) : 0;
                                }else{

                                    $lead_estimated  = $lead_arr[5] == 'Unknown' ? 'N/A': $lead_arr[5];
                                    $lead_email = $lead_arr[1];
                                    $lead_phone = str_replace($rep_arr, '',$lead_arr[2]);
                                    $lead_area  = $lead_arr[3] ? explode(':',$lead_arr[3])[0] : 'N/A';
                                    $lead_desc  = 'Property : '.$lead_arr[3] . ' ----More Details : '.$lead_arr[4]. ' ----Estimated Move Date : '.$lead_estimated.' ----Message : '.$lead_arr[6];
                                    $lead_rent  = $lead_arr[4] ? str_replace($rep_arr, '', explode('|',$lead_arr[4])[0]) : 0;
                                }

                                /* Insert lead data into distributor lead table */
                                $created_lead_id = DB::table('lead')->insertGetId([
                                        'lead_date'         =>  $prettydate, 
                                        'lead_name'         =>  $lead_name,
                                        'lead_email'        =>  $lead_email,
                                        'lead_phone'        =>  $lead_phone,
                                        'lead_area'         =>  $lead_area,
                                        'lead_rent'         =>  $lead_rent,
                                        'lead_desc'         =>  $lead_desc,
                                        'source'            =>  $lead_source,
                                        'lead_cost'         =>  $lead_cost,
                                        'unit'              =>  $unit,
                                        'lead_from'         =>  2,
                                        'distributor_id'    =>  $distributor->id,
                                      ]);
                            }
                        }
                        
                        /* Save data for getting data with cron */
                        $checkscraper = DB::table('lead_scraper')->where(['distributor_id'    =>  $distributor->id])->first();

                        if(!$checkscraper){

                            $created_lead_scraper = DB::table('lead_scraper')
                                    ->insertGetId([
                                            'email'             =>  $email_address,
                                            'token'             =>  $password,
                                            'source'            =>  $lead_source,
                                            'lead_cost'         =>  $lead_cost,
                                            'distributor_id'    =>  $distributor->id,
                                          ]);
                        }
                        return response()
                        ->json(['status'=> 1, 'message' => 'All Done! Leads Fetched successfully and assign to distributor '.$email_address, 'class_name' => 'alert-success']);
                    }else{
                        return response()
                        ->json(['status'=> 0,'message' => 'No lead available for distributor '.$email_address, 'class_name' => 'alert-success']);
                    }
                }else{
                    return response()->json(['status'=> 0, 'message' => "No distributor found with email address ".$email_address , 'class_name' => 'alert-danger']);
                } 
            }else{
                return response()->json(['status'=> 0, 'message' => "Something went wrong. Please try again later." , 'class_name' => 'alert-danger']);
            }
        } catch (\Exception $e) {
            return response()->json([
                                "status" => 0,
                                'class_name' => 'alert-danger',
                                "message" => $e->getMessage()
                            ], 200);
        }
    }

    public function get_string_between($string, $start, $end){
        $string = ' ' . $string;
        $ini    = strpos($string, $start);
        if ($ini == 0) return '';
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        return substr($string, $ini, $len);
    }

        /*
*  @function:  updateLeadScraper
*  @params: Request data
*  @return: json response with status
*  createdBy: Chintesh k
*/
    public function updateLeadScraper(Request $request){

        try{
            
            
            $email_address      = $request->input('email_address');
            $password           = $request->input('password');
            $lead_source        = $request->input('lead_source');
            $lead_cost          = $request->input('lead_cost');
            $scraper_id         = $request->input('scraper_id');

            if ($email_address && $password && $scraper_id){

                /* Code to read mailbox for Distributor */
                $distributor    =   User::where([
                                        'email'                 =>  $email_address,
                                        'user_role'             =>  AGENT,
                                        'manage_distributor'    =>  1,
                                        'status'                =>  1
                                    ])->first();
                if($distributor){

                    /* Save data for getting data periodically */
                    $checkscraper = DB::table('lead_scraper')->where(['distributor_id'    =>  $distributor->id])->first();
                    if($checkscraper){

                        $created_lead_scraper = DB::table('lead_scraper')->where('id', $scraper_id)->update([
                                        'email'             =>  $email_address,
                                        'token'             =>  $password,
                                        'source'            =>  $lead_source,
                                        'lead_cost'         =>  $lead_cost]);
                        return response()->json(['status'=> 1, 'message' => 'Details updated successfully.']); 
                    }else{
                        return response()->json(['status'=> 0,'message' => 'Something went wrong. Please try again later.', 'class_name' => 'alert-success']);
                    }
                }else{
                    return response()->json(['status'=> 0,'message' => 'Something went wrong. Please try again later.']);
                } 
            }else{
                return response()->json(['status'=> 0, 'message' => "Something went wrong. Please try again later." , 'class_name' => 'alert-danger']);
            }
        } catch (\Exception $e) {
            return response()->json([
                                "status" => 0,
                                'class_name' => 'alert-danger',
                                "message" => $e->getMessage()
                            ], 200);
        }
    }

/*
*  @function:  ackDocumentUpload
*  @params: Request data
*  @return: json response with status
*  @updatedBy: Chintesh k
*/
    public function ackDocumentUpload(Request $request){
        $updated_id =  $request->updated_id;
        
        $request->file('uploadfiles');
        $validation = Validator::make($request->all() , ['uploadfiles' => 'required']);

        if ($validation->passes()){

            $request->input();
            $uploadpath = public_path('/images/ackdocuments');
            if (!File::exists($uploadpath)){
              File::makeDirectory($uploadpath, 0777, true, true);
            }

            /* for check old uploaded data */
            $userdetail           = User::find($updated_id);
            if (!empty($userdetail) && !empty($userdetail->ack_documents)){
              $userackdoc = json_decode($userdetail->ack_documents);
            }

            $icou = 0;
            foreach ($request->file('uploadfiles') as $key => $image){
                

                $nameonly = preg_replace("/[^a-zA-Z0-9.]/", "",preg_replace('/\..+$/', '', $image->getClientOriginalName())).'_'.substr(time(),-3).'_'.Auth::user()->id . '_' . $key;
                
                $name = $nameonly.'.'.$image->getClientOriginalExtension();

                $image->move($uploadpath, $name);
                $userackdoc[] = $name;
                $icou++;
            }

            $updatedocument['ack_documents']  = json_encode($userackdoc);
            $updateUserAckdata   = User::where('id',$updated_id)->update($updatedocument);

            if ($updateUserAckdata){
                $view_show = view('leadclient.showackdoc', ['updatedocument' => json_encode($userackdoc) , 'userdetail' => $userdetail])->render();
                return response()
                    ->json(['status'=> 1,'message' => 'Success! Documents uploaded successfully!', 'docshow' => $view_show, 'icou' => $icou, ]);
            }
        }else{
            return response()->json(['status'=> 0, 'message' => "Please upload some documents." , 'class_name' => 'alert-danger']);
        }
    }

    /*
    *  @function:  deleteackdoc
    *  @params: Request data
    *  @return: json response with status
    *  @updatedBy: Chintesh k
    */
    public function deleteackdoc(Request $request)
    {

            
            $id= $request->id; 
        if ($id != ''){

            $userackdocument        = User::find($id);
            $userackdoc             = json_decode($userackdocument->ack_documents);

            if (($key = array_search($request->input('image') , $userackdoc)) !== false){
              unset($userackdoc[$key]);
            }

            $updated_array                      =   array_values($userackdoc);
            $newuploadedoc['ack_documents']     =   json_encode($updated_array);
            
            $updateuserackdoc                   =   User::where('id', $id)->update($newuploadedoc);
            if ($updateuserackdoc){

                $uploadpath     = public_path('/images/ackdocuments');
                if($uploadpath . '/' . $request->input('image')){
                     unlink($uploadpath . '/' . $request->input('image'));
                }
               
                return response()
                    ->json(['message' => 'Documents Removed successfully!', 'class_name' => 'alert-success']);
            }else{
                return response()
                    ->json(['message' => 'Documentnot Remove!', 'uploaded_image' => '', 'class_name' => 'alert-danger']);
            }
        }else{
          return response()
                    ->json(['message' => 'Documentnot Remove!', 'uploaded_image' => '', 'class_name' => 'alert-danger']);
        }
    }

    /*
    *  @function:  deleteleaddoc
    *  @params: Request data
    *  @return: json response with status
    *  @updatedBy: Chintesh k
    */
    public function deleteleaddoc(Request $request)
    {

        if ($request->input('id') != ''){

            $id             = $request->input('id');
            $leaddetail     = Leadclient::find($id);
            $leaddetaildoc  = json_decode($leaddetail->document_upload);

            if (($key = array_search($request->input('image') , $leaddetaildoc)) !== false){
              unset($leaddetaildoc[$key]);
            }

            $updated_array                        = array_values($leaddetaildoc);
            $newuploadedoc['document_upload']     = json_encode($updated_array);
            $updateLeadclient                     = Leadclient::where('id', $id)
                                                                ->update($newuploadedoc);
            if ($updateLeadclient){

                $uploadpath     = uploadedocumentpath($id);
                unlink($uploadpath . '/' . $request->input('image'));

                return response()
                    ->json(['message' => 'Documents Removed successfully!', 'class_name' => 'alert-success']);
            }else{
                return response()
                    ->json(['message' => 'Documentnot Remove!', 'uploaded_image' => '', 'class_name' => 'alert-danger']);
            }
        }else{
          return response()
                    ->json(['message' => 'Documentnot Remove!', 'uploaded_image' => '', 'class_name' => 'alert-danger']);
        }
    }

    public function checkemailclient(Request $request)
    {
        $email = $request->input('email');
        $id = $request->input('id');
        
        if ($id == 0){
            $getuser    =   Leadclient::join('users', 'users.id', 'lead_client.agent_id')
                                        ->select('users.email', 'lead_client.fname', 'lead_client.lname')
                                        ->where(['lead_client.email' => $email])
                                        ->orderBy('lead_client.id', 'DESC')
                                        ->first();
        }else{

            $getuser    =   Leadclient::join('users', 'users.id', 'lead_client.agent_id')
                                        ->select('users.email', 'lead_client.fname', 'lead_client.lname')
                                        ->where(['lead_client.email' => $email])
                                        ->where('lead_client.id', '!=', $id)
                                        ->orderBy('lead_client.id', 'DESC')
                                        ->first();
        }

        if (isset($getuser['email']) && $getuser['email'] != ''){
            $data['email']  =   $getuser['email'];
            $data['name']   =   $getuser['fname'] . ' ' . $getuser['lname'];

            echo '{"status":false,"message":"Record Already Exists","name":" <a href=' . "'" . 'mailto:' . $data['email'] . '?body=Hello ' . $data['name'] . "' " . ' target=' . "'" . '_top' . "'" . '>' . $data['email'] . '</a>"}';
        }else{
            echo '{"status":true,"message":"Record does not Exists"}';
        }
    }

    public function logindata($user_name, $company_id, $password)
    {
        if (!is_numeric($company_id)) throw new Exception('Company ID must be numeric only.');

        $this->user_name    = $user_name;
        $this->company_id   = $company_id;
        $this->password     = $password;
    }
    public function set_fax_number($fax_number)
    {
        //echo $fax_number; exit;
        $this->fax_number = preg_replace('/[^0-9]/', '', $fax_number);
        if (strlen($this->fax_number) != 10) throw new Exception('Fax number must be 10 digits, numeric only.');
        return $this;
    }

    public function set_fax_content($fax_content)
    {
        if (!$fax_content) throw new Exception('Fax Content is required.');
        $this->fax_content = base64_encode($fax_content);
        return $this;
    }

    public function set_recipient_name($recipient_name)
    {
        if (strlen($recipient_name) > 32) throw new Exception('Recipient name max is 32 char.');
        $this->recipient_name = $recipient_name;
        return $this;
    }

    public function set_job_id($job_id)
    {
        if (!is_numeric($job_id)) throw new Exception('Job ID must be numeric only.');
        $this->job_id = $job_id;
        return $this;
    }
    /**
     * On success returns unique fax ID which can be later used to track status of this specific send
     *
     */
    public function send_fax()
    {
        $fields = array(
            'faxno'             => $this->fax_number,
            'recipname'         => $this->recipient_name,
            'faxfiledata[0]'    => $this->fax_content,
            'operation'         => 'sendfax',
            'faxfilenames[0]'   => $this->fax_number . ".pdf",
        );

        $response = $this->curl($fields);
        if (strstr(strtolower($response) , 'jobid:')){
            $job_id_arr = explode(":", $response);
            return trim($job_id_arr[1]);
        }else{
            return "error";
            //throw new Exception("Faxage returns error: " . $response . ".");
        }
    }

    /**
     * On success returns Tab delimited string jobid | commid | destname | shortstatus | longstatus | sendtime
     * | completetime | xmittime
     *
     */
    public function get_status()
    {
        $fields = array('jobid'     => $this->job_id, 'operation' => 'status');
        return $this->curl($fields);
    }

    public function curl($parameters)
    {
        
        $fields = array_merge($parameters, array(
            'username'  => $this->user_name,
            'company'   => $this->company_id,
            'password'  => $this->password,
           
            
        ));
       // echo "<pre>";print_r(http_build_query($fields)); exit;

        $ch     = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->faxage_api_url);
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
// if (curl_errno($ch)){
//     $error = curl_error($ch);
//     print_r($error); exit;
// }
// echo "<pre>";print_r($result); exit;
// exit;
        
        //if (curl_errno($ch)){
           // $error = curl_error($ch);
           // curl_close($ch);
          //  return 'Invalid login';
            //throw new Exception("Failed retrieving  '" . $this->faxage_api_url . "' because of ' " . $error . "'.");
       // }
        return $result;
    }
    
    public function update_agent(Request $request){
        $hidden_lead_id = $_POST['hidden_lead_id'];
        $new_agent_id = $_POST['new_agent_id'];
        $old_agent_id = $_POST['old_agent_id'];
        
         $status = DB::select("select * from lead_client where id='$hidden_lead_id'")[0]->curr_status;
         //print_r($status); exit;
        //if($status=='New' || $status=='Repeat' || $status=='Prospect' || $status=='Hot' || $status=='Warm' || $status=='Cold' || $status=='Pending'){
            if(!empty($hidden_lead_id) && !empty($new_agent_id)){
                $result = DB::select("update lead_client set agent_id='$new_agent_id',old_agent_id='$old_agent_id',source_id='$new_agent_id' where id='$hidden_lead_id'");
                echo "1";
            }else{
                echo"0";
            }
        // }else{
        //     echo"2";
        // }
    }
    
    
    
   // <!--------------- Randhir kumar---------------->
   
   public function add_property(Request $request){
       
        $pdata=$request->input();
        
        //print_r($pdata); exit;
       
        $user_role          = Auth::user()->user_role;
        $user               = Auth::user()->id;
        $company            = Auth::user()->company;
        $input              = request()->all();

       //print_r($user_role); exit;
       
        $updatedId = (!empty($pdata['updated_id'])?$pdata['updated_id']:'');
        $validator = \Validator::make($request->all(), [
            'property_name' => 'required',
            'phone' => 'required',
            'pemail' => 'required',
            //'pmgmt_id' => 'required',
            'paddress' => 'required',
            'Market' => 'required',
            ],[
            'property_name.required' => 'The Name is empty.',
            'phone.required' =>'The Phone is empty.',
            'pemail.required' =>'The Email is empty.',
            //'pmgmt_id.required' => 'The Company is empty.',
            'paddress.required' =>'The Address is empty.',
            'Market.required' => 'Select Market is empty.'

        ]);


        if ($validator->fails())
        {
            $errors = $validator->errors()->all();
            $key = $validator->errors()->keys();

            for($i=0;$i<count($errors);$i++) {
                $datas[$key[$i]]=$errors[$i];
            }

            $response['err']='1';
            $response['msg']=$datas;
            return response()->json($response); exit;
        }
        
        $prop_email = $request->input('pemail');
        $prop_add = $request->input('paddress');
        $prop_phone = $request->input('phone');
        
        // if(empty($updatedId)){
        //     if($user_role==2 || $user_role==4){
        //         if(checkDuplicateValue("property","prop_add='$prop_add' or prop_phone='$prop_phone'")>0){
        //             $response['err'] = '3';
        //             $response['msg'] = array('paddress'=>'This property is already in the CRM. To update please click "continue"');
        //             return response()->json($response); exit;
        //         }
        //     }else{
        //         if(checkDuplicateValue("property","prop_add='$prop_add' or prop_email='$prop_email'")>0){
        //             $response['err'] = '3';
        //             $response['msg'] = array('paddress'=>'This property is already in the CRM. To update please click "continue"');
        //             return response()->json($response); exit;
        //         }  
        //     }
        // }
        
        $property['prop_name']    =   $input['property_name'];
        $property['prop_phone']   =   $input['phone'];
        $property['prop_add']     =   $input['paddress'];
        $property['prop_mgmt_co'] =   !empty($input['pmgmt_id'])?$input['pmgmt_id']:''; 
        $property['prop_email']   =   $input['pemail'];
        $property['prop_city']    =    !empty($input['city'])?$input['city']:'';
        $property['prop_state']   =    !empty($input['State'])?$input['State']:''; 
        $property['prop_zip']     =    !empty($input['zip'])?$input['zip']:'';
        $property['lat']          =    !empty($input['lat'])?$input['lat']:''; 
        $property['lng']          =    !empty($input['lng'])?$input['lng']:'';
        $property['prop_market']  =    !empty($input['Market'])?$input['Market']:'';
        $property['prop_manager'] =    !empty($input['Manager'])?$input['Manager']:'';
        $property['prop_fax']     =    !empty($input['fax'])?$input['fax']:'';
        $property['prop_web']     =    !empty($input['website'])?$input['website']:'';
        $property['prop_notes']   =    !empty($input['note'])?$input['note']:'';
        $property['vendor_id']    =    !empty($input['VendorID'])?$input['VendorID']:'0';
        $property['bill_add']     =    !empty($input['Billingress'])?$input['Billingress']:'';
        $property['bill_city']    =    !empty($input['BillingCity'])?$input['BillingCity']:'';
        $property['bill_state']   =    !empty($input['BillingState'])?$input['BillingState']:'';
        $property['bill_zip']     =    !empty($input['BillingZip'])?$input['BillingZip']:'';
        $property['create_by_user']= $user;
        $property['update_by_user']=0;
        $property['company_id']   =   $company;
    //echo "<pre>";print_r($property); exit;
        if(empty($updatedId)){
            //print_r($property); exit;
            $insert = Property::create($property);
            //$insert=$property->save();
        }else{
           $property['update_by_user'] = $user;
           $property['updated_at'] = date('Y-m-d H:i:s');
           
           $insert = Property::find($updatedId)->update($property); 
        }
           
        if($insert){
            $response['err']='0';
            if(empty($updatedId)){
                $response['msg']=' Data successfully saved.';
            }else{
                $response['msg']=' Data successfully updated.';
            }
            return response()->json($response); exit;
        }else{
            $response['err']='2';
            $response['msg']=' Error ';
            return response()->json($response); exit; 
        }
    }
    
//   public function get_company(Request $request){
       
//         $input  =   request()->all();
//         //print_r($input); exit;
//         $address    =   $input['paddress'];
//         $email      =   $input['pemail'];
        
//         $whereData = array(array('prop_email',$email),array('prop_add',$address));
//     //DB::enableQueryLog();
//         $propertys = Property::where('prop_email', $email)->orWhere('prop_add', $address)->get();
        
//         //dd(DB::getQueryLog()); exit;
//         if(count($propertys)>0){
//             return response()->json($propertys[0]); exit;
//         }else{
//             echo"0";
//         } 
//   }


public function get_company(Request $request){
       
        $input  =   request()->all();
       
        // $address    =   $input['paddress'];
        // $email      =   $input['pemail'];
        $id      =   $input['id'];
        
        //$whereData = array(array('prop_email',$email),array('prop_add',$address));
    //DB::enableQueryLog();
        $propertys = Property::where('id', $id)->get();
        
        //dd(DB::getQueryLog()); exit;
        if(count($propertys)>0){
            return response()->json($propertys[0]); exit;
        }else{
            echo"0";
        } 
   }
   
   
   public function save_flag(Request $request){
       
      
        $pdata=$request->input();
        
        //print_r($_POST); exit;
        
        $updatedId = (!empty($pdata['updated_id'])?$pdata['updated_id']:'');
        
        $validator = \Validator::make($request->all(), [
            'description' => 'required',
            'sendto' => 'required',
            
            ],[
            'description.required' => 'The Description is empty.',
            'sendto.required' => 'The User is empty.',
        ]);


        if ($validator->fails())
        {
            $errors = $validator->errors()->all();
            $key = $validator->errors()->keys();

            for($i=0;$i<count($errors);$i++) {
                $datas[$key[$i]]=$errors[$i];
            }

            $response['err']='1';
            $response['msg']=$datas;
            return response()->json($response); exit;
        }
        
        $flage['description']    =   $pdata['description'];
        $flage['lead_id']        =   $pdata['leadid'];
        $flage['created_by']     =   Auth::user()->id;
        $flage['created_at']     =   date('Y-m-d H:i');
            
         
        $insert = DB::insert('insert into flag_data ( sendto,description,lead_id,created_by,created_at) values (?, ?, ?,?,?)', [$request->sendto,$request->description,$request->leadid,$flage['created_by'],$flage['created_at']]);
       
        if($insert){
            $response['err']='0';
            $response['msg']=' Data successfully saved.';
            return response()->json($response); exit;
        }else{
            $response['err']='2';
            $response['msg']=' Error ';
            return response()->json($response); exit; 
        }
    }
    public function flags(){
        return view('leadclient.flag', ['agentemails' => []]);
    }
    
    public function flag_list(){
        $params = $_REQUEST;
        
        //print_r($params['order'][0]); exit;
        $columns = array('','flag_data.lead_id','lead_client.fname','users.name','flag_data.description');
        $lead_id            = (!empty($params['lead_id'])?$params['lead_id']:'');
         $agent_id  = (!empty($params['agent_id'])?$params['agent_id']:'');
         
        if(empty($lead_id)){
            //$order_column = (!empty($columns[$params['order'][0]['column']])?$columns[$params['order'][0]['column']]:'lead_id');
            $order_column = (!empty($columns[$params['order'][0]['column']])?$columns[$params['order'][0]['column']]:'created_at');
            $orderby = (!empty($columns[$params['order'][0]['dir']])?$columns[$params['order'][0]['dir']]:"DESC");
        }else{
            //$order_column = 'lead_id';
            $order_column = 'created_at';
            $orderby = "DESC";
        }
         
        $user_role          = Auth::user()->user_role;
        $user               = Auth::user()->id;
        //echo "Lead ".$lead_id; exit;
        
        if($user_role=='1' || $user_role=='2' || $user_role=='4'){
            if(!empty($lead_id)){
                
                if(!empty($agent_id)){
                    $user_agent_ids =array();
                    $useragent  =   User::where('id', '=', $agent_id)
                            ->where('status', '=', 1)->orderBy('name', 'ASC')->get();
                     
                   if ( !empty ( $useragent[0]->id ) ) {
                    //   echo "<pre>"; print_r($useragent); exit;       
                    //     echo "Comming here "; exit;   
                        array_push($user_agent_ids,$useragent[0]->id);
                        array_push($user_agent_ids,$useragent[0]->create_by_user);
                    
                        if(!empty($useragent[0]->assign_to_ar)){
                            array_push($user_agent_ids,$useragent[0]->assign_to_ar); 
                        }
                          
                        if(!empty($useragent[0]->agents_to_manager)){
                            array_push($user_agent_ids,$useragent[0]->agents_to_manager); 
                        }
                    
                        if(!empty($user_agent_ids)){
                            $user_agent_ids = implode(',',$user_agent_ids);
                            $user_agent_ids = explode(',',$user_agent_ids);
                        }
                    }    
                }
        
        
                    $useragent  =   User::whereIn('id', $user_agent_ids)
                            ->where('status', '=', 1)
                            ->orderBy('name', 'ASC')
                            ->get();
                            
                    $useragent = json_decode(json_encode(json_decode($useragent),true));
                      
                      $useragent = implode(',',array_column($useragent,'id'));
                
                    //echo "<pre>"; print_r($useragent); exit;
                 $condition = "flag_data.lead_id = '$lead_id' and flag_data.is_deleted='0' and flag_data.sendto IN($useragent) or created_by IN($useragent) and lead_id = '$lead_id'";
            }else{
                 //$condition = "flag_data.is_deleted='0' and flag_data.sendto='$user' or created_by='$user'";
                 $condition = "flag_data.is_deleted='0' and flag_data.sendto='$user'";
            }
           
        }else{
            //$condition = "flag_data.is_deleted='0' and flag_data.sendto='$user'  or created_by='$user' ";
            $condition = "flag_data.is_deleted='0' and flag_data.sendto='$user'";
        }
        
        $searColumns = array('lead_id','description',"CONCAT(lead_client.fname,' ',lead_client.lname)");
        if( !empty($params['search']['value']) ) {
            $where="AND (";
            for($i=0;$i<count($searColumns);$i++)
                {
                $where .=$searColumns[$i]." Like '%".$params['search']['value']."%' OR ";
                } 
            $condition .=substr($where,0,strlen($where)-3);
            $condition .=")";
        }
        
        if(empty($lead_id)){
            $limit="order by $order_column $orderby LIMIT ".$params['start']." ,".$params['length']." ";
        }else{
            // $limit='';
            $limit='order by id asc';
        }
        
        //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,(select CONCAT(users.name,' ',users.last_name)as agent_name from users where id=flag_data.sendto)as sndtoname,(select CONCAT(users.name,' ',users.last_name)as agent_name from users where id=flag_data.created_by)as receivername  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 $limit"; 
        //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,(select CONCAT(users.name,' ',users.last_name)as agent_name from users where id=flag_data.sendto)as sndtoname  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");
        //DB::enableQueryLog();
        $results = 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,(select CONCAT(users.name,' ',users.last_name)as agent_name from users where id=flag_data.sendto)as sndtoname,(select CONCAT(users.name,' ',users.last_name)as agent_name from users where id=flag_data.created_by)as receivername  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 $limit");

        /** 
         * code for flag history listing
         * updated on 26th june 2023
         * By Flexsin Dev **/
        
        if(count($resultscount) > 0)
        {
            $adminagent = [];
            $aragent = [];
            $adminar = [];
            $arId = '';
            $agentId = '';
            $adminId = '';

            if(!empty($lead_id)){
                $data = [];
                if($agent_id == '')
                {
                    $agentId = Leadclient::where('id',$lead_id)->first();
                    if($agentId){
                        $agent_id = $agentId->agent_id;
                    }
                }
                if(!empty($agent_id)){
                    $useragent  =   User::where('id', '=', $agent_id)
                            ->where('status', '=', 1)->orderBy('name', 'ASC')->get();
                     
                   if ( !empty ( $useragent[0]->id ) ) {
                        $agentId = $useragent[0]->id;
                        $adminId = $useragent[0]->create_by_user;
                        $arId = $useragent[0]->assign_to_ar;
                        foreach($results as $data)
                        {
                            if(($data->sendto == $agentId && $data->created_by == $adminId) || ($data->created_by == $agentId && $data->sendto == $adminId))
                            {
                                $adminagent[] = $data;
                            }

                            if(($data->sendto == $arId && $data->created_by == $adminId) || ($data->created_by == $arId && $data->sendto == $adminId))
                            {
                                $adminar[] = $data;
                            }
                            if(($data->sendto == $arId && $data->created_by == $agentId) || ($data->created_by == $arId && $data->sendto == $agentId))
                            {
                                $aragent[] = $data; 
                            }

                        }

                        

                        // array_push($user_agent_ids,$useragent[0]->id);
                        // array_push($user_agent_ids,$useragent[0]->create_by_user);
                        // array_push($user_agent_ids,$useragent[0]->assign_to_ar);
                    }    
                }
            }

            if(count($adminagent) != 0 || count($aragent) != 0 || count($adminar) != 0)
            {
                $results = ['adminagent' => $adminagent, 'aragent' => $aragent, 'adminar' => $adminar, 'ar' => $arId, 'admin' => $adminId, 'agent' => $agentId];
            }

        }

        /** 
         * code update end **/

        $datas = array();
        
        if(empty($lead_id)){
            if(count($results)>0){
                foreach ($results as $row) {
    
                    
                    $classs="onclick=getSelectdCheckboxVal('cus');";
                    
                    //$action = '<a href="javascript:void(0);" data-placement="left" data-toggle="tooltip" class="tooltips" data-original-title="Delete!" onclick="deleteFlag('.$row->id.');"><i class="fa fa-times"></i></a>';
                    if($row->status == 1)
                    {
                        $action = '<a href="javascript:void(0);" data-placement="left" data-toggle="tooltip" class="tooltips" data-original-title="Mark as Read!" onclick="readFlag('.$row->id.','.$row->status.');">Mark as Read</a>';
                    } else {
                        $action = '<a href="javascript:void(0);" data-placement="left" data-toggle="tooltip" class="tooltips" data-original-title="Mark as UnRead!" onclick="readFlag('.$row->id.','.$row->status.');">Mark as UnRead</a>';
                    }

                    $firstname = '';
                    $lastname = '';
                    $firstname = isset($row->fname) ? $row->fname : '';
                    $lastname = isset($row->lname) ? $row->lname : '';

                    $url = url('/').'/editclientlead/'.$row->lead_id.'/1';
                    
                    $nestedData = array();
                    $nestedData['DT_RowId'] = "row_".(!empty($row->sendto)?$row->sendto:$row->receivername);
                    $nestedData[] = '<input type="checkbox" class="cus" name="id" value="'.$row->id.'" id="'.$row->id.'" '.$classs.' >' ;
                    $nestedData[] = '<a href="'.$url.'" target="_blank" onclick="return markRead('.$row->id.','.$row->status.',1);">#'.$row->lead_id.'</a>' ;
                    $nestedData[] = $row->agent_name;
                    $nestedData[] = $row->sndtoname;
                    $nestedData[] = $firstname.' '.$lastname;
                    $nestedData[] = $row->description;
                    $nestedData[] = convertDateFormat($row->created_at,'m-d-Y');

                    if($row->status == 1)
                    {
                        $nestedData[] =  '<div style="text-align:center;"><i class="fa fa-envelope-o" aria-hidden="true"></i><span style="margin-left: 3px;"> UnRead</span>
                                            </div>';
                    } else {                        
                        $nestedData[] =  '<div style="text-align:center;"><i class="fa fa-envelope-open-o" aria-hidden="true"></i><span style="margin-left: 3px;"> Read</span>
                                            </div>';                        
                    }
                   
                    $nestedData[] = $action;
                    $datas[] = $nestedData; 
                }
              
                $json_data = array(
                    "draw"            => intval($params['draw'] ),   
                    "recordsTotal"    => intval(count($resultscount)),  
                    "recordsFiltered" => intval(count($resultscount)),
                    "data"            => $datas
                    );
                 return response()->json($json_data); exit;
              
            }else{
                $json_data = array(
                "draw"            => intval($params['draw'] ),   
                "recordsTotal"    => intval(count($resultscount)),  
                "recordsFiltered" => intval(count($resultscount)),
                "data"            => $datas
                );
                
                
             return response()->json($json_data); exit;
            }
        }else{
            return response()->json($results); exit; 
        }
    }
    
    public function sent_flag_list(){
        $params = $_REQUEST;
        
         
         $columns = array('','flag_data.lead_id','lead_client.fname',"CONCAT(users.name,' ',users.last_name)",'flag_data.description');
        
        $order_column = (!empty($columns[$params['order'][0]['column']])?$columns[$params['order'][0]['column']]:'created_at');
        $orderby = (!empty($columns[$params['order'][0]['dir']])?$columns[$params['order'][0]['dir']]:"DESC");
        
        $user_role          = Auth::user()->user_role;
        $user               = Auth::user()->id;
        $lead_id            = (!empty($params['lead_id'])?$params['lead_id']:'');
         
        $condition = "flag_data.is_deleted='0' and created_by='$user' ";
            
        $searColumns = array('lead_id','description',"CONCAT(lead_client.fname,' ',lead_client.lname)");
        if( !empty($params['search']['value']) ) {
            $where="AND (";
            for($i=0;$i<count($searColumns);$i++)
                {
                $where .=$searColumns[$i]." Like '%".$params['search']['value']."%' OR ";
                } 
            $condition .=substr($where,0,strlen($where)-3);
            $condition .=")";
        }
        
        if(empty($lead_id)){
            $limit="order by $order_column $orderby LIMIT ".$params['start']." ,".$params['length']." ";
        }else{
            $limit='';
        }
        
        // 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,(select CONCAT(users.name,' ',users.last_name)as agent_name from users where id=flag_data.sendto)as sndtoname  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 $limit";
        // 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,(select CONCAT(users.name,' ',users.last_name)as agent_name from users where id=flag_data.sendto)as sndtoname  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");
        //DB::enableQueryLog();
        $results = 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,(select CONCAT(users.name,' ',users.last_name)as agent_name from users where id=flag_data.sendto)as sndtoname  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 $limit");
       //dd(DB::getQueryLog()); 
       // echo "<pre>"; print_r($results); exit;
        //echo $results; exit;
        $datas = array();
        
        if(empty($lead_id)){
            if(count($results)>0){
                foreach ($results as $row) {
    
                    
                    $classs="onclick=getSelectdCheckboxVal('cus');";
                    
                    $action = '<a href="javascript:void(0);" data-placement="left" data-toggle="tooltip" class="tooltips" data-original-title="Delete!" onclick="deleteFlag('.$row->id.');"><i class="fa fa-times"></i></a>';
                    $url = url('/').'/editclientlead/'.$row->lead_id.'/1';
                    
                    $firstname = '';
                    $lastname = '';
                    $firstname = isset($row->fname) ? $row->fname : '';
                    $lastname = isset($row->lname) ? $row->lname : '';

                    $nestedData = array();
                    $nestedData['DT_RowId'] = "row_".$row->sendto;
                    $nestedData[] = '<input type="checkbox" class="cus1" name="id" value="'.$row->id.'" id="'.$row->id.'" '.$classs.' >' ;
                    $nestedData[] = '<a href="'.$url.'" target="_blank">#'.$row->lead_id.'</a>' ;
                    $nestedData[] = $row->agent_name;
                    $nestedData[] = $row->sndtoname;
                    $nestedData[] = $firstname.' '.$lastname;
                    $nestedData[] = $row->description;
                    $nestedData[] = convertDateFormat($row->created_at,'m-d-Y');
                   
                    $nestedData[] = $action;
                    $datas[] = $nestedData; 
                }
              
                $json_data = array(
                    "draw"            => intval($params['draw'] ),   
                    "recordsTotal"    => intval(count($resultscount)),  
                    "recordsFiltered" => intval(count($resultscount)),
                    "data"            => $datas
                    );
                 return response()->json($json_data); exit;
              
            }else{
                $json_data = array(
                "draw"            => intval($params['draw'] ),   
                "recordsTotal"    => intval(count($resultscount)),  
                "recordsFiltered" => intval(count($resultscount)),
                "data"            => $datas
                );
                
                
             return response()->json($json_data); exit;
            }
        }else{
            return response()->json($results); exit; 
        }
    }
    public function deleteFlag(Request $request){
          
        $id=$request->input('id');
        //DB::enableQueryLog();
        $deleted_by = Auth::user()->id;
        $deleted_at = date('Y-m-d H:i');
        
        $results=DB::update("update flag_data set is_deleted=not is_deleted,deleted_by='$deleted_by',deleted_at='$deleted_at' where id='$id'");
         //dd(DB::getQueryLog()); 

        if($results){
            $responce['err'] = 0;
            $responce['msg'] = " Successfully Deleted.";
            $responce['total'] = count_flag();
             return response()->json($responce); exit;
        }else{
            $responce['err'] = 2;
            $responce['msg'] = "Error.";
            return response()->json($responce); exit;
        }
    }

    public function readFlag(Request $request){
        
        $id=$request->input('id');
        $status = $request->status;
        
        //DB::enableQueryLog();
        if($status == 1)
        {
            $results=DB::update("update flag_data set status = '0' where id='$id'");
        } else {
            $results=DB::update("update flag_data set status = '1' where id='$id'");
         //dd(DB::getQueryLog()); 
        }

        if($results){
            $responce['err'] = 0;
            $responce['msg'] = "Status Successfully Updated.";
            $responce['total'] = count_flag();
             return response()->json($responce); exit;
        }else{
            $responce['err'] = 2;
            $responce['msg'] = "Error.";
            return response()->json($responce); exit;
        }
    }
    
    
    public function deleteMultiFlag(Request $request){
          
        $id=implode(',',$request->input('id'));
        
        $deleted_by = Auth::user()->id;
        $deleted_at = date('Y-m-d H:i');
        
        $results=DB::update("update flag_data set is_deleted=not is_deleted,deleted_by='$deleted_by',deleted_at='$deleted_at' where id IN($id)");
       
        if($results){
            $responce['err'] = 0;
            $responce['msg'] = " Successfully Deleted.";
            $responce['total'] = count_flag();
             return response()->json($responce); exit;
        }else{
            $responce['err'] = 2;
            $responce['msg'] = "Error.";
            return response()->json($responce); exit;
        }
    }
    
    // for security question operation //
     public function questions(){
        return view('leadclient.question', ['agentemails' => []]);
    }
    
    public function question_list(){
        $params = $_REQUEST;
        $columns = array('name','slug','status','action');
        
        $user_role          = Auth::user()->user_role;
        $user               = Auth::user()->id;
        $lead_id            = (!empty($params['lead_id'])?$params['lead_id']:'');
        
      
           
    $condition = "security_question.is_deleted='0' ";
            
           
       
        $searColumns = array('question');
        if( !empty($params['search']['value']) ) {
            $where="AND (";
            for($i=0;$i<count($searColumns);$i++)
                {
                $where .=$searColumns[$i]." Like '%".$params['search']['value']."%' OR ";
                } 
            $condition .=substr($where,0,strlen($where)-3);
            $condition .=")";
        }
        
        if(empty($lead_id)){
            $limit="order by security_question.id desc LIMIT ".$params['start']." ,".$params['length']." ";
        }else{
            $limit='';
        }
        
        //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 security_question.* from security_question WHERE $condition");
        //DB::enableQueryLog();
        $results = DB::select("select security_question.* from security_question WHERE $condition $limit");
      //dd(DB::getQueryLog()); 
      // echo "<pre>"; print_r($results); exit;
        //echo $results; exit;
        $datas = array();
        
        if(empty($lead_id)){
            if(count($results)>0){
                $i=$params['start']+1;
                foreach ($results as $row) {
                        
                        //<a href="javascript:void(0);" onclick="editQuestion('.$row->id.');" data-placement="left" data-toggle="tooltip" class="tooltips" data-original-title="Edit!" style="text-decoration:none;padding-right: 5%;"><i class="fa fa-pencil"></i></a>;
                        
                    $action = ' <a href="javascript:void(0);" data-placement="left" data-toggle="tooltip" class="tooltips" data-original-title="Delete!" onclick="deleteQuestion('.$row->id.');"><i class="fa fa-times"></i></a>';
                  
                    if($row->status=='1'){
                        $status= '<a href="javascript:void(0);" onclick="changeQuestionStatus('.$row->id.');" class="btn btn-xs btn-success">Active</a>';
                    }else{
                        $status= '<a href="javascript:void(0);" onclick="changeQuestionStatus('.$row->id.');" class="btn btn-xs btn-danger">Inactive</a>';
                    }


                    $nestedData = array();
                    $nestedData['DT_RowId'] = "row_".$row->id;
                   
                        $nestedData[] = $i;
                        $nestedData[] = $row->question;
                        $nestedData[] = $status;
                        $nestedData[] = $action;
                    $datas[] = $nestedData; 
                    
                    $i++;
                }
                $json_data = array(
                    "draw"            => intval($params['draw'] ),   
                    "recordsTotal"    => intval(count($resultscount)),  
                    "recordsFiltered" => intval(count($resultscount)),
                    "data"            => $datas
                    );
                 return response()->json($json_data); exit;
              
            }else{
                $json_data = array(
                "draw"            => intval($params['draw'] ),   
                "recordsTotal"    => intval(count($resultscount)),  
                "recordsFiltered" => intval(count($resultscount)),
                "data"            => $datas
                );
                
                
             return response()->json($json_data); exit;
            }
        }else{
            return response()->json($results); exit; 
        }
    }
    public function savequestion(Request $request){
        
         $id = $request->input('id');
        $pdata=$request->input();
        $created_by = Auth::user()->id;
        $created_at = date('Y-m-d H:i');
        
         $validator = \Validator::make($request->all(), [
            'question' => 'required'
            
            ],[
            'question.required' => 'The question is empty.'
        ]);


        if ($validator->fails())
        {
            $errors = $validator->errors()->all();
            $key = $validator->errors()->keys();

            for($i=0;$i<count($errors);$i++) {
                $datas[$key[$i]]=$errors[$i];
            }

            $response['err']='1';
            $response['msg']=$datas;
            return response()->json($response); exit;
        }
        
        
        $flage['question']    =   $pdata['question'];
    
        $flage['created_by']     =   Auth::user()->id;
        $flage['created_at']     =   date('Y-m-d H:i');
            
         
        $insert = DB::insert('insert into security_question (question,created_by,created_at) values (?,?,?)', [$request->question,$flage['created_by'],$flage['created_at']]);
       
        if($insert){
            $response['err']='0';
            $response['msg']=' Data successfully saved.';
            return response()->json($response); exit;
        }else{
            $response['err']='2';
            $response['msg']=' Error ';
            return response()->json($response); exit; 
        }
        
        print_r($request); exit;
    }
    
    
    
    public function deleteQuestion(Request $request){
          
        $id=$request->input('id');
        //DB::enableQueryLog();
        $deleted_by = Auth::user()->id;
        $deleted_at = date('Y-m-d H:i');
        
        $results=DB::update("update security_question set is_deleted=not is_deleted where id='$id'");
         //dd(DB::getQueryLog()); 

        if($results){
            $responce['err'] = 0;
            $responce['msg'] = " Successfully Deleted.";
            $responce['total'] = count_flag();
             return response()->json($responce); exit;
        }else{
            $responce['err'] = 2;
            $responce['msg'] = "Error.";
            return response()->json($responce); exit;
        }
    }
    
    public function changeQuestionStatus(Request $request){
          
        $id=$request->input('id');
        //DB::enableQueryLog();
        $deleted_by = Auth::user()->id;
        $deleted_at = date('Y-m-d H:i');
        
        $results=DB::update("update security_question set status=not status where id='$id'");
         //dd(DB::getQueryLog()); 

        if($results){
            $responce['err'] = 0;
            $responce['msg'] = " Successfully Deleted.";
            $responce['total'] = count_flag();
             return response()->json($responce); exit;
        }else{
            $responce['err'] = 2;
            $responce['msg'] = "Error.";
            return response()->json($responce); exit;
        }
    }
    
    function view_flag(Request $request){
        $id = Auth::user()->id;
        $results=DB::update("update users set flag_modal=not flag_modal where id='$id'");
    }
    
    function get_email_body(Request $request){
        $send_email = $_POST['send_email'];
        $propid = $_POST['propid'];
        
        $results=DB::select("select * from `email_list` WHERE `id` = '$send_email'")[0];
        
        $property_name = DB::select("select * from `property` WHERE `id` = '$propid'")[0]->prop_name;
        
        $body = $results->email_body;
        
        $email_signature = nl2br($results->email_signature); //str_replace(",",'<br>',$results->email_signature);
        
        
        $email_body['email_body'] = str_replace("[Signature]",$email_signature,$body);
        
        $email_body['email_body'] = str_replace("Hello [Client Name],",'To Whom is May Concern:', $email_body['email_body']);
        
        $email_body['email_body'] = str_replace("[Client Name]",$property_name, $email_body['email_body']);
        
        
            
        
        //print_r($email_body); exit;
        
         //$agentemail->email_body = str_replace("[Invoice No]",$leaddetail->id,$agentemail->email_body);
         
         
        
        //  $email_id       =   $_POST['email_to'];
        // $leaddetail     =   $_POST['send_email'];
        // $agentemail     =   Agentemail::find($email_id);
        // $leaddetail     =   Leadclient::find($leaddetail);
        // $agentdetail    =   User::find(Auth::user()->id);
        
        // $agentemail     =   setemaildata($agentemail, $leaddetail, $agentdetail);
        
        
        
        //setemaildata($agentemail , $leaddetail ,$agentdetail);
        
        
        return response()->json($email_body); exit;
    }

    /*
    *  @function_name:   index
    *  @params: Request data
    *  @return:  Json response
    *  @updatedBy: Chintesh k
    */    
    public function testdoublehistory(Request $request)
    {
        //dd('this');
        $data = DB::select("SELECT status_history,id FROM lead_client WHERE concat('',curr_status * 1) = curr_status");
        //dd($data[0]->status_history);
        $arr = [];
        $msg = [];
        
        

        foreach ($data as $key => $status){
            //dd($status);
            $msg = explode('~~~~', $status->status_history);
            $prev = '';
            $keyobj = [];
            foreach ($msg as $key => $data){
                $exp = explode('~~',$data);
                // print_r()
                $arrayy[] = $exp;
                if(count($exp)>=1)
                {
                    if($prev == $exp[1])
                    {
                        array_pop($keyobj);
                        array_push($keyobj,['date' => $exp[0],'message' => $exp[1]]);
                        $prev = $exp[1];
                    } else {

                        array_push($keyobj,['date' => $exp[0],'message' => $exp[1]]);
                        $prev = $exp[1];
                    }
                } else {
                    dd($status->id);
                }

            }
            //dd($arrayy);
            $list = '';
            foreach ($keyobj as $key => $statuslist)
            {
                $list .= $statuslist['date'].'~~'.$statuslist['message'].'~~~~';
            }
            $list = rtrim($list,'~~~~');
            //status_history_old status_history
            //print_r($status->id.'<br>new: '.$list.'<br> old: '.$status->status_history.'<br>*********<br>');
            //DB::enableQueryLog();
            $update = DB::update("update lead_client set status_history_new='$list' where id ='$status->id'");
            //dd(DB::getQueryLog());
            

            //dd($keyobj);
            //dd(array_unique($keyobj));
            //$arr[$key] = $history;

            //dd($arr[0]->status_history);
        }

        echo 'sucess'; die;
    }
}

