<?php

namespace App\Http\Controllers;

use App\model\Property;
use Illuminate\Http\Request;
use Auth;
use Session;
use DB;
use Mail;
use App\model\Company;
use App\model\CollectionDetails;
use App\model\VendorDetails;
use App\model\Leadclient;
use App\model\Agentemail;

use App\User;
use PDF;

class PropertyController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

      $agent_id     =Auth::user()->id;
      $user_role    =Auth::user()->user_role;
      $items        = $request->items ?? 25;
      
         $propertys = Property::leftJoin('company','company.id','=','property.prop_mgmt_co')
                      ->select('property.*','company.mgmt_name');

        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::find($companyid)->mgmt_name;
          }else{
            $company_name   =   '';
          }
        }

          $pref               = '';

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

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

            $propertyresult   = session('propertyresult');
            $dataser          = $propertyresult;

            if(($pref == 'myone' || $pref == '')  && session('propertyresult') != ''){

                $propertys    =   $propertys->where(function($query) use ($dataser,$pref) {
                                        $query->select('property.*','company.mgmt_name')
                                                    ->where('prop_name', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orWhere('mgmt_name', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orWhere('prop_email', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orWhere('prop_add', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }

            if ($pref == "prop_name"){
                $propertys    =   $propertys->where(function($query) use ($dataser,$pref) {
                                        $query->select('property.*','company.mgmt_name')
                                                    ->where('prop_name', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "prop_email"){
                $propertys    =   $propertys->where(function($query) use ($dataser,$pref) {
                                        $query->select('property.*','company.mgmt_name')
                                                    ->where('prop_email', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "prop_add"){
                $propertys    =   $propertys->where(function($query) use ($dataser,$pref) {
                                        $query->select('property.*','company.mgmt_name')
                                                    ->where('prop_add', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "prop_manager"){
                $propertys    =   $propertys->where(function($query) use ($dataser,$pref) {
                                        $query->select('property.*','company.mgmt_name')
                                                    ->where('prop_manager', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "prop_market"){
                $propertys    =   $propertys->where(function($query) use ($dataser,$pref) {
                                        $query->select('property.*','company.mgmt_name')
                                                    ->where('prop_market', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "prop_mgmt_co"){
                $propertys    =   $propertys->where(function($query) use ($dataser,$pref) {
                                        $query->select('property.*','company.mgmt_name')
                                                    ->where('mgmt_name', 'LIKE', '%' . session('propertyresult') . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else if ($pref == "prop_phone"){
                $propertys    =   $propertys->where(function($query) use ($dataser,$pref) {
                                        $query->select('property.*','company.mgmt_name')
                                                    ->where('prop_phone', 'LIKE', '%' . preg_replace("/[^0-9.]/", "", session('propertyresult')) . '%')
                                                    ->orderBy($pref, 'ASC');
                                                });
            }else{

                $propertys  =   $propertys->where(function($query) use ($propertyresult,$dataser) {
                                  $query->select('property.*','company.mgmt_name')
                                    ->orWhere('prop_name', 'LIKE', '%'.$dataser.'%')
                                    ->orWhere('prop_add', 'LIKE', '%'.$dataser.'%')
                                    ->orWhere('prop_phone', 'LIKE', '%'.preg_replace("/[^0-9.]/", "", $dataser).'%')
                                    ->orWhere('prop_manager', 'LIKE', '%'.$dataser.'%')
                                    ->orWhere('prop_market', 'LIKE', '%'.$dataser.'%')
                                    ->orWhere('prop_name', 'LIKE', '%'.$dataser.'%')
                                    ->orWhere('prop_email','LIKE','%'.$dataser.'%')
                                    ->orWhere('prop_notes','LIKE','%'.$dataser.'%')
                                    ->orWhere('mgmt_name','LIKE','%'.$dataser.'%');
                                });
            }
          }
       
        $propertys = $propertys->orderby('prop_name','ASC')->paginate($items);

        $state = DB::table('state')->select('id','state_name','state_value')->get(); 
        
         $agentemailcreate = Agentemail::where('agent_id', '=', Auth::user()->id)->where('status', '=', 1)->orderBy('email_name', 'ASC')->get();
                                            

        return view('property.index', compact('propertys'),[
            'companys' => Company::get(),
            'state' => $state,
            'company_id'=>$companyid,
            'company_name'=>$company_name,
            'agentemailcreate'=>$agentemailcreate,
          ])->withMembers($propertys)->withItems($items);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
           $input = request()->all();
           //echo '<pre>'; print_r($input); echo '</pre>'; die();

           // $getcomp=Company::where('mgmt_name',$input['ManagementCompany'])
           //          ->first();

           //      if(!empty($getcomp)){
           //       $company_id= $getcomp->id;
                
           //      }else{
           //        $company = new Company();
           //        $company->mgmt_name = $input['ManagementCompany'];
           //        $company->mgmt_identifier=substr($input['ManagementCompany'],0,5);
           //        $company->save();
           //        $company_id=$company->id; 
           //      } 
    
            $property = DB::table('property')->where('prop_add',$input['address'])->first();
              
            if($property){
             
                    Session::flash('message', 'pdradd');   
                    Session::flash('alert-class', 'alert-success'); 
                    return response()->json(['success'=>1]); 
            }
            
            
           $user=Auth::user()->id;
           $company=Auth::user()->company;
           $property               = new Property(); 
           $property->prop_name    =   $input['property_name'];
           $property->prop_add     =   $input['address'];
           $property->prop_city    =   $input['city'];
           $property->prop_state   =   $input['State'];
           $property->prop_zip     =   $input['zip'];
           $property->prop_market  =   $input['Market'];
           $property->prop_manager =   $input['Manager'];
           $property->prop_phone   =   $input['phone'];
           $property->prop_fax     =   $input['fax'];
           $property->prop_email   =   $input['email'];
          // $property->prop_mgmt_co =   $input['ManagementCompany']; Commented By Shashi 
           $property->prop_mgmt_co =   $input['mgmt_id'];  // management company 
           $property->prop_web     =   $input['website'];
           $property->prop_notes   =   isset($input['note'])?$input['note']:'';
           $property->vendor_id    =    isset($input['VendorID'])?$input['VendorID']:'0';
           $property->bill_add     =   $input['BillingAddress'];
           $property->bill_city    =   $input['BillingCity'];
           $property->bill_state   =   $input['BillingState'];
           $property->bill_zip     =   $input['BillingZip'];
           $add_billadd            =    (!empty($input['add_billadd'])?$input['add_billadd']:'0');
          // $property->company_id   =   $input['company_id']; // real state company
           $property->create_by_user= $user;
           $property->update_by_user=0;
           $property->company_id   =   $company;

          


           //echo '<pre>'; print_r($property); echo '</pre>'; die();

           // add other fields
           if($property->save())
           {
              $collection=new CollectionDetails();
              $collection->property_id=$property->id;
             // $collection->company_id=$input['company_id'];
              $collection->company_id=Auth::user()->company;
              $collection->lead_id=0;
              $collection->collection_details=isset($input['note'])?$input['note']:'';
              $collection->save();

              $vendor=new VendorDetails();
              $vendor->property_id=$property->id;
              $vendor->company_id=Auth::user()->company;
              //$vendor->company_id=$input['company_id'];
              $vendor->vendor_id=isset($input['VendorID'])?$input['VendorID']:'0';
              $vendor->save();
             Session::flash('message', 'pradd');   
             Session::flash('alert-class', 'alert-success'); 
             return response()->json(['success'=>1]); 
         }
         else{
             Session::flash('message', 'nopadd');   
             Session::flash('alert-class', 'alert-danger');
             return response()->json(['success'=>0]); 

         } 

        
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */

    public function checkvendorid(Request $request){
     $vendor_id= $request->input('vendorid');

    $vendor= Property::where('vendor_id','=',$vendor_id)->get()->first();

    if(isset($vendor['vendor_id']) && $vendor!=''){
     $data['res'] = 'failed';
    }else{
       $data['res'] = 'success';

    }
      
       echo  json_encode($data);
        
    }
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\model\Property  $property
     * @return \Illuminate\Http\Response
     */
    public function show()
    {   
      $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     =   '';
        }
      }
    
        $state = DB::table('state')->select('id','state_name','state_value')->get(); 

        return view('property.addproperty',[
          'mgmt_company'  =>  Company::where('company_type',2)->OrderBy('mgmt_name','ASC')->get(),
          'real_company'  =>  Company::where('company_type',1)->OrderBy('mgmt_name','ASC')->get(),
          'state'         =>  $state,
          'company_id'    =>  $companyid,
          'company_name'  =>  $company_name
        ]);
    }

    public function companysearch(Request $request){

      $ser = $request->input('inputVal'); //exit;
      $company_list=Company::where('status',1)
             ->where('mgmt_name','LIKE','%'.$ser.'%')
             ->where('company_type',2)
             ->get();
        $html='';
      
         if(!empty($company_list)){
           foreach($company_list as $company){
              $html='<p onclick="getcompany('."'".$company->mgmt_name."'".','.$company->id.')">';
               echo    $html .= $company->mgmt_name.'('.$company->mgmt_identifier.')</p>';
           }
         }else{
          echo '<p>No Match Found..</p>';
         }    

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\model\Property  $property
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {    
        $input                      =   request()->all();
        $id                         =   $input['id'];
        $propertys                  =   Property::find($id);
        $company                    =   Company::find($propertys->prop_mgmt_co);
        $propertys->company_name    =   (!empty($company->mgmt_name)?$company->mgmt_name:'');
        $collection                 =   CollectionDetails::where('company_id',Auth::user()->company)
                                                          ->where('property_id',$id)
                                                          ->OrderBy('id','desc')
                                                          ->first();
                                                          
    //echo "<pre>";print_r($id); exit;
        
        $vendor                     =   VendorDetails::where('company_id',Auth::user()->company)
                                                      ->where('property_id',$id)
                                                      ->OrderBy('id','desc')
                                                      ->first();
        if(!empty($collection)){
          $propertys->prop_notes=$collection->collection_details;
        }else{
          $propertys->prop_notes='';
        }
        
        //echo $propertys->prop_notes; exit;

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

        $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)->mgmt_name;
        }
        
        $state = DB::table('state')->select('id','state_name','state_value')->get();
        return view('property.editproperty', compact('propertys'),
          [
            'mgmt_company'  => Company::where('company_type',2)->OrderBy('mgmt_name','ASC')->get(),
            'real_company'  => Company::where('company_type',1)->OrderBy('mgmt_name','ASC')->get(),
            'company_id'    => $companyid,
            'company_name'  => $company_name,
            'state'         => $state
          ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\model\Property  $property
     * @return \Illuminate\Http\Response
     */
    public function update()
    {
        
        //echo"<pre>"; print_r($_REQUEST); exit;
        $input    = request()->all();
        $id       = $input['id'];
        $phone    = $input['phone'];
        
        
         $property = DB::table('property')->where('prop_add',$input['address'])->where('id','!=',$id)->first();
              
            if($property){
             
                    Session::flash('message', 'pdradd');   
                    Session::flash('alert-class', 'alert-success'); 
                    return response()->json(['success'=>1]); 
            }
            
            
            //print_r($input); exit;
            
            // 'prop_phone'   =>   $this->usPhoneFormat($input['phone']),
            //                 'prop_fax'     =>   $this->usPhoneFormat($input['fax']),
                            
        $phone = (!empty($input['phone'])?$this->usPhoneFormat($input['phone']):'');
        $fax = (!empty($input['fax'])?$this->usPhoneFormat($input['fax']):'');
    
        $property = array(
                'prop_name'    =>   $input['property_name'],
                'prop_add'     =>   $input['address'],
                'prop_city'    =>   $input['city'],
                'prop_state'   =>   $input['State'],
                'prop_zip'     =>   $input['zip'],
                'prop_market'  =>   $input['Market'],
                'prop_manager' =>   $input['Manager'],
                'prop_phone'   =>   $phone,
                'prop_fax'     =>   $fax,
                'prop_email'   =>   $input['email'],
                'prop_mgmt_co' =>   (!empty($input['mgmt_id'])?$input['mgmt_id']:''),
                'prop_web'     =>   $input['website'],
                //'prop_mgmt_co' =>   (!empty($input['mgmt_id'])?$input['mgmt_id']:''),
                'prop_notes'   =>   isset($input['note'])?$input['note']:'',
                'vendor_id'  => isset($input['VendorID'])?$input['VendorID']:'',
                'bill_add'     =>   $input['BillingAddress'],
                'bill_city'    =>   $input['BillingCity'],
                'bill_state'   =>   $input['BillingState'],
                'bill_zip'     =>   $input['BillingZip'],
                'add_billadd' =>    (!empty($input['add_billadd'])?$input['add_billadd']:'0'),
                'update_by_user'=> Auth::user()->id 
              );
                          
                          
      

        $updateuser = Property::where('id', $id)->update($property);

        if($updateuser){


            $collection   =   CollectionDetails::where('company_id',Auth::user()->company)
                      ->where('property_id',$id)
                      ->OrderBy('id','desc')
                      ->first();
          
          if(!empty($collection)){
              $notes  = array('collection_details' => isset($input['note']) ? $input['note'] : '');
              CollectionDetails::where('id',$collection->id)->update($notes);
          }else{
            $collection = new CollectionDetails();
            $collection->collection_details=isset($input['note'])?$input['note']:'';
            $collection->company_id=Auth::user()->company;
            $collection->lead_id=0;
            $collection->property_id=$id;
            $collection->save();
          }
          $vendor=VendorDetails::where('company_id',Auth::user()->company)->where('property_id',$id)->OrderBy('id','desc')->first();

          if(!empty($vendor)){
            $vendors=array('vendor_id'=>isset($input['VendorID'])?$input['VendorID']:'');
            VendorDetails::where('id',$vendor->id)->update($vendors);
          }else{
            $vendor = new VendorDetails();
            $vendor->vendor_id=isset($input['VendorID'])?$input['VendorID']:'';
            $vendor->company_id=Auth::user()->company;
            $vendor->property_id=$id;
            $vendor->save();
          }
          
          Session::flash('message', 'pupdate');   
          Session::flash('alert-class', 'alert-success');  
        }else{
          Session::flash('message', 'pnot');   
          Session::flash('alert-class', 'alert-danger');
        } 
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\model\Property  $property
     * @return \Illuminate\Http\Response
     */
    public function setAgentAdminPrefrence(Request $request){
      $pref = $request->input('pref');
      Session::put('setAgentAdminPrefrence',$pref);
      echo 'success';
    }

    public function propertysearch(Request $request){
      
      $ser      =   $request->input('inputVal'); 
      $role     =   Auth::user()->user_role;
      $id       =   Auth::user()->id;
      $company  =   Auth::user()->company;
      $pref     =   session('setAgentAdminPrefrence');
      
      if($pref == 'prop_phone'){
          
        $students = \DB::select("SELECT CONCAT('(',substr(prop_phone,0,3),') ',substr(prop_phone,3,3),'-',substr(prop_phone,6)) As result from property LEFT JOIN company ON company.id=property.prop_mgmt_co where prop_phone LIKE '%".preg_replace("/[^0-9.]/", "", $ser)."%'
            ORDER BY result ASC");

      }else if($pref=='prop_name'){
          
       $students = \DB::select("SELECT CONCAT(prop_name) As result from property LEFT JOIN company ON company.id=property.prop_mgmt_co where prop_name LIKE '%".$ser."%'
            ORDER BY result ASC");

      }else if($pref=='prop_add'){
          
       $students = \DB::select("SELECT CONCAT(prop_add) As result from property LEFT JOIN company ON company.id=property.prop_mgmt_co where prop_add LIKE '%".$ser."%'
            ORDER BY result ASC");

      }else if($pref=='prop_manager'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(prop_manager) As result from property LEFT JOIN company ON company.id=property.prop_mgmt_co where prop_manager LIKE '%".$ser."%'
            ORDER BY result ASC");

      }else if($pref=='prop_market'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(prop_market) As result from property LEFT JOIN company ON company.id=property.prop_mgmt_co where prop_market LIKE '%".$ser."%'
            ORDER BY result ASC");

      }else if($pref=='prop_email'){
          
       $students = \DB::select("SELECT CONCAT(prop_email) As result from property LEFT JOIN company ON company.id=property.prop_mgmt_co where prop_email LIKE '%".$ser."%'
            ORDER BY result ASC");

      }else if($pref=='prop_mgmt_co'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(mgmt_name) as result from company where mgmt_name LIKE '".$ser."%' AND company_type = 2
            ORDER BY result ASC");
      }else{

        $students = \DB::select("SELECT DISTINCT CONCAT(prop_name) As result from property LEFT JOIN company ON company.id=property.prop_mgmt_co where prop_name LIKE '".$ser."%'UNION SELECT CONCAT(prop_city) As result from property INNER JOIN company ON company.id=property.prop_mgmt_co where prop_city LIKE '".$ser."%'UNION SELECT CONCAT(prop_add) As result from property INNER JOIN company ON company.id=property.prop_mgmt_co where prop_add LIKE '".$ser."%'UNION SELECT CONCAT(prop_manager) As result from property INNER JOIN company ON company.id=property.prop_mgmt_co where prop_manager LIKE '".$ser."%'UNION SELECT CONCAT(prop_market) As result from property INNER JOIN company ON company.id=property.prop_mgmt_co where prop_market LIKE '".$ser."%'UNION SELECT CONCAT(prop_phone) As result from property INNER JOIN company ON company.id=property.prop_mgmt_co where prop_phone LIKE '%".preg_replace("/[^0-9.]/", "", $ser)."%' UNION SELECT CONCAT(prop_email) As result from property INNER JOIN company ON company.id=property.prop_mgmt_co where prop_email LIKE '".$ser."%' UNION SELECT CONCAT(prop_notes) As result from property INNER JOIN company ON company.id=property.prop_mgmt_co where prop_notes LIKE '".$ser."%' UNION SELECT CONCAT(mgmt_name) as result from company where mgmt_name LIKE '".$ser."%' AND company_type = 2 ORDER BY result ASC");
      }

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

  }
   
public function setpropertyresult(Request $request)
  {
       $agenrt_id = $request->input('property');

     
          Session::put('propertyresult',$agenrt_id);
          echo 'success';

  }

    public function unsetpropertyresult(Request $request)
  {
      $agenrt_id = $request->input('property');

          Session::forget('propertyresult');
          echo 'success';

  }

    public function destroy($id)
    {
        $istru = DB::table("property")->delete($id);
         if($istru)
         {
              Session::flash('message', 'pdy');   
              Session::flash('alert-class', 'alert-success');  

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

          } 
          return redirect('/property');
    }

    public function getcompany()
    {
       $input = request()->all();
       $company_id= $input['company_id'];

       $company = Company::find($company_id);
       if(!empty($company))
       {
         $data['status']  = 'Success';
         $data['note']  = $company['mgmt_notes'];

       }
       else
       {
         $data['status']  = 'Failed';
         
       }
       
       echo json_encode($data);
    }

    function usPhoneFormat($n)
    {
      // preg_match_all('!\d+!', $n, $matches);
      // $n = $matches;
      
      
      $ON = '(';
      for ($i=0; $i < 10 ; $i++) { 
        if($i == 2)
        {
          $ON .= $n[$i].')';
        }
        else if($i == 5)
        {
          $ON .= $n[$i].'-';
        }
        else
        {

          $ON .= $n[$i];
        }
      }
      
     // echo $ON; exit;
      return $ON;

    }
    
    
    public function open_status_mail(Request $request)
    {
        $lead_id = explode(',',$_POST['lead_id']);
        //print_r($lead_id); exit;
        
        $messagesend    =  '';
        $messagesend .='<p><img src="https://www.clientmgr.us/crmrewrite/public/images/bannerimages/1579879193.jpg" /></p>';
        $messagesend .='<p>To Whom is May Concern:</p>';
        $messagesend .='<p>Hello, my name is Bryan Bjerke and I am the Principal Broker for Spirit Real Estate Group, LLC. Attached is an invoice for Adam Kleyweg that has moved into one of your units. Please let me know if there is anything else you need from us. We are happy to complete any vendor requirements that you may have.</p>';
        $messagesend .='<p>&nbsp;</p>';
        $messagesend .='<p>Also, could you please confirm at your earliest convenience that you received this email and the invoice will be processed?</p>';
        $messagesend .='<p>Best Regards,<br /><br />';
        $messagesend .='Bryan Bjerke<br />';
        $messagesend .='Principal Broker<br />';
        $messagesend .='Bryan.Bjerke@spiritre.com<br />';
        $messagesend .='Spirit Real Estate Group, LLC<br />';
        $messagesend .='214.396.3888</p>';
        
        $agent_id       =   Auth::user()->id;
        $company        =   Auth::user()->company;
    
        $datas=array();
        for($i=0;$i<count($lead_id);$i++){
            
            $leadclient     =   Leadclient::find($lead_id[$i]);
            $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.open_invoice_pdf', 
                    [
                        '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/open_invoice_pdf/' . $leadclient->id . '_leaseverify.pdf'));
            
            $pathToFile = storage_path('pdf/open_invoice_pdf/'.$leadclient->id.'_leaseverify.pdf');
            $imgarr=[];
            $data                       = Auth::user();
            $otherdata['from']          = $data->email;
            
            $otherdata['from_name']     = ucfirst($data->name) . " " . ucfirst($data->last_name);
            $data                       = array('body' => $messagesend );
            $otherdata['subject']       = "Open invoice";
        
            //$otherdata['to'] = "bryan.bjerke@spiritre.com";
            $otherdata['to'] = "danish_ali@flexsin.org";
            //$otherdata['to'] = $property['prop_email'];
            $otherdata['bcc'] = "randhir.muz11@gmail.com";
            
            //$otherdata['to'] = (!empty($leadclient->title_email)?$leadclient->title_email:$leadclient->email);
            //echo "<pre>"; print_r($otherdata['to']); exit;
            if(!empty($otherdata['to'])){
                sendmail($data, $otherdata, $pathToFile, $imgarr, strip_tags($messagesend)); 
                echo "1.";
            }
        }
    }
    
     public function multi_open_status_mail(Request $request)
    {
        $lead_id = explode(',',$_POST['lead_id']);
        
        
        //print_r($lead_id); exit;
        
        $cc_emails     =   array();
        
   
        if(isset($_POST['cc_email']) && $_POST['cc_email'] != ''){
            
            $email = explode(',', $_POST['cc_email']);
            for($i=0;$i<count($email);$i++){
               if (filter_var($email[$i], FILTER_VALIDATE_EMAIL)) {
                  array_push($cc_emails,$email[$i]);
                }else{
                    continue;
                }
            }
        }
        
        $messagesend    =  '';
        // $messagesend .='<p><img src="https://www.clientmgr.us/crmrewrite/public/images/bannerimages/1579879193.jpg" /></p>';
        
        if(empty($_POST['email_body'])){
            
            $messagesend .='<p>To Whom is May Concern:</p>';
            $messagesend .='<p>Hello, my name is Bryan Bjerke and I am the Principal Broker for Spirit Real Estate Group, LLC. Attached is an invoice for Adam Kleyweg that has moved into one of your units. Please let me know if there is anything else you need from us. We are happy to complete any vendor requirements that you may have.</p>';
            $messagesend .='<p>&nbsp;</p>';
            $messagesend .='<p>Also, could you please confirm at your earliest convenience that you received this email and the invoice will be processed?</p>';
        
        }else{
            $messagesend .=$_POST['email_body'];
        }
        
        // $messagesend .='<p>Best Regards,<br /><br />';
        // $messagesend .='Bryan Bjerke<br />';
        // $messagesend .='Principal Broker<br />';
        // $messagesend .='Bryan.Bjerke@spiritre.com<br />';
        // $messagesend .='Spirit Real Estate Group, LLC<br />';
        // $messagesend .='214.396.3888</p>';
        
        $agent_id       =   Auth::user()->id;
        $company        =   Auth::user()->company;
    
        $datas=array();
        for($i=0;$i<count($lead_id);$i++){
            
            $leadclient     =   Leadclient::find($lead_id[$i]);
            $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;
            }
            
           array_push($datas,$leadclient);
        }
            //echo"<pre>"; print_r($datas); exit;
        
            /* calculate total commision here */
            $otherdata['tot_com'] = (float) $tot_com;
            $otherdata['total']   = (float) $total;
            
            $pdf    =   PDF::loadView('leadclient.multi_open_invoice_pdf', 
                    [
                        'property'          =>  $property, 
                        'clientdetail'      =>  Auth::user() , 
                        'leadclient'        =>  $datas, 
                        'agentdetail'       =>  $agentdetail, 
                        'otherdata'         =>  $otherdata, 
                        'company'           =>  $company, 
                        'collection_notes'  =>  $collection_notes, 
                        'vendor_id'         =>  $vendor_id
                    ],compact('leadclient'));
                    
            $pdf->save(storage_path('pdf/open_invoice_pdf/' . date('Y-m-d H:i:s') . '_leaseverify.pdf'));
            
            $pathToFile = storage_path('pdf/open_invoice_pdf/'.date('Y-m-d H:i:s').'_leaseverify.pdf');
            
        
            // $imgarr=[];
            // $files = request()->file();
            // if (!empty($files)){
            //     $request->file('document1');

            //     $lead_id        = 2;
            //     $filedetail     = request()->file('document1');
            //     $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=[];
            // }
            
            
        $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['from_name']     = ucfirst($data->name) . " " . ucfirst($data->last_name);
            $data                       = array('body' => $messagesend );
            $otherdata['subject']       = (!empty($_POST['subject'])? $_POST['subject']:"Open invoice");
            
            //echo "<pre>"; print_r($property['prop_email']); exit;
        
            $otherdata['to'] = (!empty($_POST['email_to'])? $_POST['email_to']:$property['prop_email']);
            
            //"bryan.bjerke@spiritre.com"
            //$property['prop_email']
            //$otherdata['to'] = "danwebdeveloper8564@gmail.com";
            
            $otherdata['cc'] = $cc_emails;
            $otherdata['bcc'] = "randhir.muz11@gmail.com";
            
            //$otherdata['to'] = (!empty($leadclient->title_email)?$leadclient->title_email:$leadclient->email);
            //echo "<pre>"; print_r($otherdata['to']); exit;
            if(!empty($otherdata['to'])){
                sendmail($data, $otherdata, $pathToFile, $imgarr, strip_tags($messagesend)); 
                
                echo "1";
            }
        }
    
    // public function multi_open_status_mail(Request $request)
    // {
    //     $lead_id = explode(',',$_POST['lead_id']);
    //     //print_r($lead_id); exit;
        
    //     $messagesend    =  '';
    //     $messagesend .='<p><img src="https://www.clientmgr.us/crmrewrite/public/images/bannerimages/1579879193.jpg" /></p>';
    //     $messagesend .='<p>To Whom is May Concern:</p>';
    //     $messagesend .='<p>Hello, my name is Bryan Bjerke and I am the Principal Broker for Spirit Real Estate Group, LLC. Attached is an invoice for Adam Kleyweg that has moved into one of your units. Please let me know if there is anything else you need from us. We are happy to complete any vendor requirements that you may have.</p>';
    //     $messagesend .='<p>&nbsp;</p>';
    //     $messagesend .='<p>Also, could you please confirm at your earliest convenience that you received this email and the invoice will be processed?</p>';
    //     $messagesend .='<p>Best Regards,<br /><br />';
    //     $messagesend .='Bryan Bjerke<br />';
    //     $messagesend .='Principal Broker<br />';
    //     $messagesend .='Bryan.Bjerke@spiritre.com<br />';
    //     $messagesend .='Spirit Real Estate Group, LLC<br />';
    //     $messagesend .='214.396.3888</p>';
        
    //     $agent_id       =   Auth::user()->id;
    //     $company        =   Auth::user()->company;
    
    //     $datas=array();
    //     for($i=0;$i<count($lead_id);$i++){
            
    //         $leadclient     =   Leadclient::find($lead_id[$i]);
    //         $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;
    //         }
            
    //       array_push($datas,$leadclient);
    //     }
    //         //echo"<pre>"; print_r($datas); exit;
        
    //         /* calculate total commision here */
    //         $otherdata['tot_com'] = (float) $tot_com;
    //         $otherdata['total']   = (float) $total;
            
    //         $pdf    =   PDF::loadView('leadclient.multi_open_invoice_pdf', 
    //                 [
    //                     'property'          =>  $property, 
    //                     'clientdetail'      =>  Auth::user() , 
    //                     'leadclient'        =>  $datas, 
    //                     'agentdetail'       =>  $agentdetail, 
    //                     'otherdata'         =>  $otherdata, 
    //                     'company'           =>  $company, 
    //                     'collection_notes'  =>  $collection_notes, 
    //                     'vendor_id'         =>  $vendor_id
    //                 ],compact('leadclient'));
                    
    //         $pdf->save(storage_path('pdf/open_invoice_pdf/' . date('Y-m-d H:i:s') . '_leaseverify.pdf'));
            
    //         $pathToFile = storage_path('pdf/open_invoice_pdf/'.date('Y-m-d H:i:s').'_leaseverify.pdf');
    //         $imgarr=[];
    //         $data                       = Auth::user();
    //         $otherdata['from']          = $data->email;
            
    //         $otherdata['from_name']     = ucfirst($data->name) . " " . ucfirst($data->last_name);
    //         $data                       = array('body' => $messagesend );
    //         $otherdata['subject']       = "Open invoice";
            
    //         //echo "<pre>"; print_r($property['prop_email']); exit;
        
    //         //$otherdata['to'] = "bryan.bjerke@spiritre.com";
    //         $otherdata['to'] = "danwebdeveloper8564@gmail.com";
            
    //       // $otherdata['to'] = $property['prop_email'];
    //         $otherdata['bcc'] = "randhir.muz11@gmail.com";
            
            
    //         //$otherdata['to'] = (!empty($leadclient->title_email)?$leadclient->title_email:$leadclient->email);
    //         //echo "<pre>"; print_r($otherdata['to']); exit;
    //         if(!empty($otherdata['to'])){
    //             sendmail($data, $otherdata, $pathToFile, $imgarr, strip_tags($messagesend)); 
    //             echo "1.";
    //         }
    //     }
    

    // public function check_duplicate_property(Request $request){
    //         $address = $request->input('address');
    //         $street = explode(' ',$address)[0];
    //         // $city = explode(',',$address)[1];
    //         $city =  (!empty($request->input('city'))?$request->input('city'):'');
             
    //         $id =  (!empty($request->input('id'))?$request->input('id'):'');
             
      
           
    //     $address = (!empty($request->input('address'))?$request->input('address'):'');
            
    //         if(empty($id)){
                
            
    //     if(!empty($address) && empty($city)){
            
    //       $property = DB::table('property')->Where('prop_add', 'like',$address . '%')->first();
           
           
    //       if($property){
    //             $success['error'] =1;
    //             $success['msg'] ='Record already exist.';
    //             return response()->json($success); exit;
    //         }else{
    //             $success['error'] =0;
    //             $success['msg'] ='ok.';
    //             return response()->json($success);exit;
              
    //         }
    //     }
            
    //     if(!empty($address) && !empty($city)){
    //         $property = DB::table('property')->Where('prop_add', 'like',$street . '%')->where('prop_city',$city)->first();
            
            
    //         if($property){
    //             $success['error'] =1;
    //             $success['msg'] ='Record already exist.';
    //             return response()->json($success);  exit;
    //         }else{
    //             $success['error'] =0;
    //             $success['msg'] ='ok.';
    //             return response()->json($success); exit;
              
    //         }
    //     }
        
    //         }else{
                
    //             if(!empty($address) && empty($city)){
            
    //               $property = DB::table('property')->where('prop_add',$address)->where('id','!=',$id)->first();
                   
    //               if($property){
    //                     $success['error'] =1;
    //                     $success['msg'] ='Record already exist.';
    //                     return response()->json($success); exit;
    //                 }else{
    //                     $success['error'] =0;
    //                     $success['msg'] ='ok.';
    //                     return response()->json($success);exit;
                      
    //                 }
    //             }
            
    //             if(!empty($address) && !empty($city)){
    //                 $property = DB::table('property')->where('prop_add',$street)->where('prop_city',$city)->where('id','!=',$id)->first();
                    
                    
    //                 if($property){
    //                     $success['error'] =1;
    //                     $success['msg'] ='Record already exist.';
    //                     return response()->json($success);  exit;
    //                 }else{
    //                     $success['error'] =0;
    //                     $success['msg'] ='ok.';
    //                     return response()->json($success); exit;
                      
    //                 }
    //             }
                
                
    //         }
        
    //     }
        
    public function address_list(Request $request)
    {
        $userId = Auth::user()->id;
        
        $validate = (!empty($_POST['validate'])?$_POST['validate']:'');
      
        if(!empty($validate)){
           
           if(!empty($_POST["keyword"]) && !empty($_POST["city"])) {
            
                $key = trim($_POST["keyword"]);
                $city=$_POST['city'];
                
                $sql= "select * from property where prop_add like '$key %' and `prop_city` = '$city'";
              //echo $sql; exit;
                $results = (json_decode(json_encode(DB::select($sql)), true));
                
                if($results){
                    $success['error'] =1;
                    $success['msg'] ='Record already exist.';
                    $success['lists'] =$results;
                    return response()->json($success);  exit;
                }else{
                    $success['error'] =0;
                    $success['msg'] ='ok.';
                    $success['lists'] ='';
                    return response()->json($success); exit;
                  
                }
            }
            
        }else{
            
          if(!empty($_POST["keyword"])) {
                $key = trim($_POST["keyword"]);
                $sql= "select * from property where prop_add like '%$key%' group by prop_add ";
               
                $results = (json_decode(json_encode(DB::select($sql)), true));
                
                //echo"<pre>"; print_r($results); exit;
                //echo $sql; exit;
                $data='<ul id="country-list" style="position: absolute;z-index: 9;width: 100%;max-height: 350px;overflow: scroll;margin-top:0%;">';
                
                foreach($results as $result){
                 
                    $data.="<li onClick='selectCountry(".$result["id"].");' id='li_".$result["id"]."' data='".filter_var($result["prop_add"], FILTER_SANITIZE_NUMBER_INT)."' state='".$result["prop_state"]."' city='".$result["prop_city"]."' zip='".$result["prop_zip"]."' >".($result["prop_add"])."</li>";
                }
                $data.='</ul>';
                echo $data;
            }  
            
        } 
       
    }
    
    
    
    public function address_list_lead(Request $request)
    {
        
        $userId = Auth::user()->id;
        
        $validate = (!empty($_POST['validate'])?$_POST['validate']:'');
      
        if(!empty($validate)){
           
           if(!empty($_POST["keyword"]) && !empty($_POST["city"])) {
            
                $key = trim($_POST["keyword"]);
                $city=$_POST['city'];
                
                $sql= "select * from property where prop_add like '$key %' and `prop_city` = '$city'";
              //echo $sql; exit;
                $results = (json_decode(json_encode(DB::select($sql)), true));
                
                if($results){
                    $success['error'] =1;
                    $success['msg'] ='Record already exist.';
                    $success['lists'] =$results;
                    return response()->json($success);  exit;
                }else{
                    $success['error'] =0;
                    $success['msg'] ='ok.';
                    $success['lists'] ='';
                    return response()->json($success); exit;
                }
            }
            
        }else{
            
          if(!empty($_POST["keyword"])) {
                $key = trim($_POST["keyword"]);
                $sql= "select * from property where prop_add like '%$key%' group by prop_add ";
               
                $results = (json_decode(json_encode(DB::select($sql)), true));
                
                //echo"<pre>"; print_r($results); exit;
                //echo $sql; exit;
                $data='<ul id="country-list" style="position: absolute;z-index: 9;width: 100%;max-height: 350px;overflow: scroll;margin-top:0%;">';
                
                foreach($results as $result){
                 
                    $data.="<li onClick='selectCountry(".$result["id"].");' id='li_".$result["id"]."' data='".filter_var($result["prop_add"], FILTER_SANITIZE_NUMBER_INT)."' state='".$result["prop_state"]."' city='".$result["prop_city"]."' zip='".$result["prop_zip"]."' >".($result["prop_add"])."</li>";
                }
                $data.='</ul>';
                echo $data;
            }  
        }
       
    }
}