<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Lead;
use App\LeadStatus;
use App\User;
use App\CardDetail;
use App\PreviousData;
use App\Reminder;
use App\Contact;
use App\StateZoneList;
use App\TimeZoneList;
use Validator;
use DataTables;
use Auth;
use DB;

use Illuminate\Validation\Rule;
use App\Imports\LeadsImport;
use Maatwebsite\Excel\Facades\Excel;
use Carbon\Carbon;

class LeadController extends Controller
{
	
	/**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        date_default_timezone_set(get_company_option('timezone', get_option('timezone','Asia/Dhaka'))); 

        $this->middleware(function ($request, $next) {
            if( has_membership_system() == 'enabled' ){
                if( ! has_feature( 'project_management_module' ) ){
                    if( ! $request->ajax()){
                        return redirect('membership/extend')->with('message', _lang('Sorry, This feature is not available in your current subscription. You can upgrade your package !'));
                    }else{
                        return response()->json(['result'=>'error','message'=>_lang('Sorry, This feature is not available in your current subscription !')]);
                    }
                }
            }

            return $next($request);
        });
    }
	
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($view_type = '')
    {
        if($view_type == 'kanban'){
            $company_id = company_id();

            $lead_status = LeadStatus::where('company_id', $company_id)
                                     ->orderBy('order','asc')
                                     ->get();                                   
            return view('backend.accounting.lead.kanban_view',compact('lead_status'));
        }else{
            return view('backend.accounting.lead.list');
        }
    }

    /* Get Logs Data*/
    public function load_more_lead(Request $request, $lead_status_id, $last_lead_id){

        if( $request->ajax()){
            $leads = Lead::where('company_id', company_id())
                         ->where('lead_status_id',$lead_status_id)
                         ->where('id','<', $last_lead_id)
                         ->with(['assigned_user','lead_source'])
                         ->latest()
                         ->limit(20)
                         ->get();
            echo json_encode($leads);  
        }                                      
    }

    /** Update Lead Status **/
    public function update_lead_status(Request $request, $lead_status_id, $lead_id){

        if( $request->ajax()){
            $lead = Lead::where('id',$lead_id)
                        ->where('company_id', company_id())
                        ->first();
             
            if($lead){
               $lead->lead_status_id = $lead_status_id;
               $lead->save();
               echo json_encode($lead); 
            } 
        }                                      
    }
    
    public function calculate(Request $request){
        if(isset($request->year)){
            $leads = Lead::where('assigned_user_id', '=',$request->assigned_user_id)
            ->whereYear('assigned_date', '=', $request->year)
              ->whereMonth('assigned_date', '=', $request->month)
              ->orderBy("id","desc")
              ->get();
           return view('backend.accounting.lead.calculate')->with('leads', $leads);
        }
         
              return view('backend.accounting.lead.calculate');
    }

    public function get_table_data(Request $request){
        
        $user_type = Auth::user()->user_type;
        $permissions = permission_list();
        $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                      ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.company_id",company_id());
        if(Auth::user()->role_id == 8){
            $leads ->where('assigned_user_id', '=', Auth::user()->id);
                    
        }
        
        if(Auth::user()->role_id == 17){
            /*$leads = Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->select('leads.*')
                     ->where("leads.company_id",company_id())
                     ->where('assigned_user_id', '=', Auth::user()->id)
                     ->orderBy("leads.id","desc");*/
            
        }
        
        if(Auth::user()->role_id == 9){
            $leads ->where('created_user_id', '=', Auth::user()->id);
        }
        
        if(Auth::user()->role_id == 10){
            
        }
        
        if(Auth::user()->user_type == 'user'){
            
        }
        
             if ($request->has('assigned_user_id')) {
                 $anuj_id=$request->post('assigned_user_id');
                 if($anuj_id=='notassign'){
                     $leads->where(function ($q) use ($anuj_id) {
                         $q->whereNull('assigned_user_id')->orWhereNull('created_user_id');
                     });
                 }else {
                     $leads->where(function ($q) use ($anuj_id) {
                         $q->where('assigned_user_id', $anuj_id)->orWhere('created_user_id', $anuj_id);
                     });
                 }
            }
            if ($request->has('time_zone')) {
                 $anuj_id1=$request->post('time_zone');
                 $leads->where(function($q) use($anuj_id1){
                     $q->where('time_zone', $anuj_id1);
                 });
                
            }

            if ($request->has('lead_status_id')) {
               // dd($request->post("lead_status_id"),json_decode($request->post('lead_status_id')));
                $leads->whereIn('lead_status_id', json_decode($request->post('lead_status_id')));
            }

            if ($request->has('lead_source_id')) {
                $leads->where('lead_source_id', 'like', "%{$request->post('lead_source_id')}%");
            }
if ($request->has('zone_state')) {
                $leads->where('zone_state', 'like', "%{$request->post('zone_state')}%");
            }

            if ($request->has('country')) {
                $leads->where('country', 'like', "%{$request->post('country')}%");
            }
            if ($request->has('project_type')) {
                $leads->where('project_type', 'like', "%{$request->post('project_type')}%");
            }
            if ($request->has('keyword')) {
                $leads->where('name', 'like', "%{$request->post('keyword')}%");
            }
            if ($request->has('email')) {
                $leads->where('email', 'like', "%{$request->post('email')}%");
            }
            
            /*if ($request->has('status_date')) {
                $dates = explode("-",$request->status_date);
                $leads->where('status_date', '>=', trim($dates[0]))->where('status_date', '<=', trim($dates[1]));
            }*/
        $leads=$leads ->orderBy("leads.id","desc");

                //    $timezones=TimeZoneList::all();


        return Datatables::eloquent($leads)
                        
                        ->editColumn('company_name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->company_name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                         ->editColumn('zonename.name', function ($lead) {
                            

                            if ($lead->zonename->name != '') {
                              $status = $lead->zonename->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a  target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank"  href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank"  href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank"  href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank"  href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name','company_name','address', 'created_at','phone', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }

    /* Get Logs Data*/
    public function get_logs_data($lead_id){
        
        $logs = \App\ActivityLog::with('created_by')
                                ->select('activity_logs.*')
                                ->where("activity_logs.company_id",company_id())
                                ->where('related_to','leads')
                                ->where('related_id',$lead_id)
                                ->orderBy("activity_logs.id","desc")
                                ->get();

        echo json_encode($logs);                            
    }

    /** Import Lead **/
    public function import(Request $request)
    {       
        if($request->isMethod('get')){
            return view('backend.accounting.lead.import');
        }else{
            @ini_set('max_execution_time', 0);
            @set_time_limit(0);

            // $validator = Validator::make($request->all(), [
            //     'lead_status_id'    => 'required',
            //     'lead_source_id'    => 'required',
            //     'assigned_user_id'  => 'required',
            //     'file'              => 'required|mimes:xlsx',
            // ]);
            $validator = Validator::make($request->all(), [
                'file'              => 'required|mimes:xlsx',
            ]);
            if ($validator->fails()) {
                if($request->ajax()){ 
                    return response()->json(['result'=>'error','message'=>$validator->errors()->all()]);
                }else{
                    return redirect('leads/import')->withErrors($validator)
                                                      ->withInput();
                }           
            }
              // die('ddddd'); 
            //Import Contacts
            //$file_type = $request->file('file')->getClientOriginalExtension();


            $new_rows = 0;

            DB::beginTransaction();
            
            $previous_rows = Lead::where('company_id',company_id())->count();

            $data = array();
            $data['lead_status_id'] = $request->lead_status_id;
            $data['lead_source_id'] = $request->lead_source_id;
            $data['assigned_user_id'] = 0;
//print_r($data); die;
            $import = Excel::import(new LeadsImport($data), request()->file('file'));

            $current_rows = Lead::where('company_id',company_id())->count();

            $new_rows = $current_rows - $previous_rows;

            DB::commit();

            return back()->with('success',$new_rows.' '._lang('Rows Imported Sucessfully'));
        }           
        
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
      public function fetchState(Request $request)
    {
        $data['states'] = StateZoneList::where("zone_id",$request->zone_id)->get(["name", "id"]);
        return response()->json($data);
    }


    public function assignleads(Request $request)
    {
       // return $request->leasids;
        DB::beginTransaction();

        $company_id = company_id();
        foreach ($request->leasids as $id) {
          //  print_r($id); die('d');
            $lead = Lead::where('id', $id)
                ->where('company_id', $company_id)
                ->first();

            if (isset($request->assigned_user_id)) {
                if ($lead->assigned_user_id != $request->assigned_user_id) {

                    $lead->assigned_date = date('Y-m-d');
                    $assigned_user_id = $request->input('assigned_user_id');
                    create_log('leads', $lead->id, _lang('Assign to') . ' ' . $lead->assigned_user->name);
                } elseif ($lead->getOriginal('assigned_user_id') == $request->input('assigned_user_id')) {
                    $assigned_user_id = $request->input('assigned_user_id');
                }
            }
            $lead->assigned_user_id =$assigned_user_id;
            $lead->save();

        }
        DB::commit();

            return response()->json(['result'=>'success']);


        /// $data['states'] = StateZoneList::where("zone_id",$request->zone_id)->get(["name", "id"]);
       // return response()->json($data);
    }

    public function create(Request $request)
    {
        if( ! $request->ajax()){
            $timezones=TimeZoneList::all();
           return view('backend.accounting.lead.create',compact('timezones'));
        }else{
           return view('backend.accounting.lead.modal.create');
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $validator = Validator::make($request->all(), [
        //  'name' => 'required|max:50',
          'company_name' => 'required|max:50',
          'email' => [
              'nullable',
              'email',
          ],
          'phone' => 'required|max:20',Rule::unique('leads')->where('company_id',company_id())
        ]);

        if ($validator->fails()) {
            if($request->ajax()){ 
                return response()->json(['result'=>'error','message'=>$validator->errors()->all()]);
            }else{
                return redirect()->route('leads.create')
                	             ->withErrors($validator)
                	             ->withInput();
            }			
        }


            $leadcheck = Lead::where('phone', $request->input('phone'))->first();
        if($leadcheck){
            return redirect()->route('leads.create')
                ->withErrors($validator)
                ->withInput()->with('error', _lang('Phone Already added'));
        }

        $lead = new Lead();
        $lead->name = $request->input('name');
        $lead->company_name = $request->input('company_name');
    		$lead->email = $request->input('email');
    		if($request->input('assigned_user_id') != '') {
    		    $lead->assigned_user_id = 0;
    		}
    		
    		$lead->created_user_id = Auth::id();
    		$lead->lead_type = $request->input('lead_type');
    		$lead->contact_date = $request->input('contact_date');
    		$lead->phone = $request->input('phone');
    		$lead->website = $request->input('website');
    		$lead->country = $request->input('country');
    		$lead->time_zone = $request->input('time_zone');
    		$lead->zone_state = $request->input('zone_state');
    		
    		$lead->currency = $request->input('currency');
    		$lead->vat_id = $request->input('vat_id');
    		$lead->reg_no = $request->input('reg_no');
    		$lead->linkedin = $request->input('linkedin');
    		$lead->project_type = $request->input('project_type');
    		$lead->city = $request->input('city');
    		$lead->state = $request->input('state');
    		$lead->zip = $request->input('zip');
    		$lead->address = $request->input('address');
    		$lead->custom_fields = $request->input('custom_fields');
    		$lead->company_id = company_id();

        $lead->save();

        create_log('leads', $lead->id, _lang('Created Lead'));
        

        // send notifications email
        if($request->input('assigned_user_id') != '') {
            $lead->assigned_date = date('Y-m-d');
            create_log('leads', $lead->id, _lang('Assign to').' '.$lead->assigned_user->name);

            sendAssignContactEmail("Lead assigned to you", User::find($request->input('assigned_user_id')), $lead);
        }

        if(! $request->ajax()){
           return redirect()->route('leads.create')->with('success', _lang('Saved Sucessfully'));
        }else{
           return response()->json(['result'=>'success','action'=>'store','message'=>_lang('Saved Sucessfully'),'data'=>$lead]);
        }
        
   }
	

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request,$id)
    {
        $company_id = company_id();

        $reminder = Reminder::where('lead_id', $id)->get();

        if($reminder){
          Reminder::where('lead_id', $id)->update(['active' => 0]);
        }

        $data['lead'] = Lead::find($id);

        $data['quotations'] = \App\Quotation::where('related_id',$id)
                                            ->where('related_to', 'leads')
                                            ->where('company_id', $company_id)
                                            ->orderBy('id','desc')
                                            ->get();

        $data['projectfiles'] = \App\ProjectFile::where('related_id',$id)
                                                ->where('related_to', 'leads')
                                                ->where('company_id', $company_id)
                                                ->orderBy('id','desc')
                                                ->get();

        $data['notes'] = \App\Note::where('related_id',$id)
                                  ->where('related_to', 'leads')
                                  ->where('company_id', $company_id)
                                  ->orderBy('id','desc')
                                  ->get();

        $data['card'] = \App\CardDetail::where('lead_id',$id)
                                            ->where('company_id', $company_id)
                                            ->get()->toArray();


        if(! $request->ajax()){
            return view('backend.accounting.lead.view', $data);
        }else{
            return view('backend.accounting.lead.modal.view', $data);
        } 
        
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request,$id)
    {

        $lead = Lead::where('id', $id)
                    ->where('company_id', company_id())
                    ->first();
                    $timezones=TimeZoneList::all();
                    
$statezone=StateZoneList::where('name',$lead->zone_state)->first();
        if(! $request->ajax()){
            return view('backend.accounting.lead.edit',compact('lead','id','timezones','statezone'));
        }else{
            return view('backend.accounting.lead.modal.edit',compact('lead','id'));
        }  
        
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        DB::beginTransaction();

        $company_id = company_id();


        $lead = Lead::where('id', $id)
                    ->where('company_id', $company_id)
                    ->first();

    	$validator = Validator::make($request->all(), [
    		//'name' => 'required|max:50',
    		'company_name' => 'required|max:50',
			'email' => [
            'nullable',
            'email',
          ],
			// 'lead_status_id' => 'required',
			// 'lead_source_id' => 'required',
			// 'assigned_user_id' => 'required',
			'phone' => 'required|max:20',Rule::unique('leads')->where('company_id', $company_id)->ignore($lead->id)
		]);

		if ($validator->fails()) {
			if($request->ajax()){ 
				return response()->json(['result'=>'error','message'=>$validator->errors()->all()]);
			}else{
				return redirect()->route('leads.edit', $id)
							->withErrors($validator)
							->withInput();
			}			
		}
        $leadnew = Lead::where('phone', $request->input('phone'))->first();
        if(!empty($leadnew)) {

            $leadcheck = Lead::where('id', $id)->first();
            if ($leadnew->id!= $leadcheck->id) {
                return redirect()->route('leads.create')
                    ->withErrors($validator)
                    ->withInput()->with('error', _lang('Phone Already added'));
            }
        }
if($lead->getOriginal('name') != $request->input('name')){
  $activity = "Name has been changed from ".$lead->getOriginal('name')." to ".$request->input('name');
  create_log('leads', $lead->id, $activity);
}

if($lead->getOriginal('company_name') != $request->input('company_name')){
  $activity = "Company name has been changed from ".$lead->getOriginal('company_name')." to ".$request->input('company_name');
  create_log('leads', $lead->id, $activity);
}

if($lead->getOriginal('email') != $request->input('email')){
  $activity = "Email has been changed from ".$lead->getOriginal('email')." to ".$request->input('email');
  create_log('leads', $lead->id, $activity);
}
$c = 0;
if($lead->getOriginal('lead_status_id') != $request->input('lead_status_id') && $request->input('lead_status_id') == 25){

  if ($lead->getOriginal('assign_count') == '' || $lead->getOriginal('assign_count') == 0) {
    $c = 1;
    $assigned_user_id = 0;
  } else {
    $c = $lead->getOriginal('assign_count') + 1;
    print_r($c);exit;
    $assigned_user_id = 0;
  }
  

  $activity = "Status has been changed from ".get_lead_curent_status($lead->getOriginal('lead_status_id'))." to ".get_lead_curent_status($request->input('lead_status_id'));
  create_log('leads', $lead->id, $activity);
}elseif ($lead->getOriginal('lead_status_id') != $request->input('lead_status_id') && $request->input('lead_status_id') != 15) {
  $activity = "Status has been changed from ".get_lead_curent_status($lead->getOriginal('lead_status_id'))." to ".get_lead_curent_status($request->input('lead_status_id'));
  create_log('leads', $lead->id, $activity);
  $c = 0;
}

if($lead->getOriginal('lead_source_id') != $request->input('lead_source_id')){
  $activity = "Source has been changed from ".$lead->getOriginal('lead_source_id')." to ".$request->input('lead_source_id');
  create_log('leads', $lead->id, $activity);
}

if($lead->getOriginal('contact_date') != $request->input('contact_date')){
  $activity = "Contact Date has been changed from ".$lead->getOriginal('contact_date')." to ".$request->input('contact_date');
  create_log('leads', $lead->id, $activity);
}

if($lead->getOriginal('phone') != $request->input('phone')){
  $activity = "Phone has been changed from ".$lead->getOriginal('phone')." to ".$request->input('phone');
  create_log('leads', $lead->id, $activity);
}


		$lead->name = $request->input('name');
		$lead->company_name = $request->input('company_name');
		$lead->email = $request->input('email');
		
    		
		if($request->input('lead_status_id') != '') {
		    $lead->lead_status_id = $request->input('lead_status_id');
		}else{
		    $lead->lead_status_id = 25;
		}
    		
		
		$lead->lead_source_id = $request->input('lead_source_id');
		
		if(isset($request->assigned_user_id)){
		    if($lead->assigned_user_id != $request->assigned_user_id){
		        
                $lead->assigned_date = date('Y-m-d');
                $assigned_user_id = $request->input('assigned_user_id');
                create_log('leads', $lead->id, _lang('Assign to').' '.$lead->assigned_user->name);
            }elseif($lead->getOriginal('assigned_user_id') == $request->input('assigned_user_id')){
              $assigned_user_id = $request->input('assigned_user_id');
            }
		}
            
        
    		
    		$lead->contact_date = $request->input('contact_date');
    		$lead->phone = $request->input('phone');
    		$lead->website = $request->input('website');
    		$lead->country = $request->input('country');
    		$lead->currency = $request->input('currency');
    		$lead->time_zone = $request->input('time_zone');
    		    		$lead->zone_state = $request->input('zone_state');

    		$lead->vat_id = $request->input('vat_id');
    		$lead->lead_type = $request->input('lead_type');
    		$lead->reg_no = $request->input('reg_no');
    		$lead->city = $request->input('city');
    		$lead->state = $request->input('state');
    		$lead->status_date = $request->input('status_date');
    		$lead->not_interested = $request->input('not_interested');
    		$lead->zip = $request->input('zip');
    		$lead->project_type = $request->input('project_type');
            $lead->hot = $request->input('hot');
            if($request->input('assigned_user_id') != ""){
                $lead->assigned_user_id = $assigned_user_id;
            }
            
            $lead->assign_count = $c;
    		$lead->address = $request->input('address');
    		$lead->sales_team = $request->input('sales_team');
    		$lead->custom_fields = $request->input('custom_fields');
    		$lead->company_id = $company_id;
    	
        $lead->save();

        if($lead->getOriginal('website') != $request->input('website')){
          $activity = "Website has been changed from ".$lead->getOriginal('website')." to ".$request->input('website');
          create_log('leads', $lead->id, $activity);
        }

        if($lead->getOriginal('country') != $request->input('country')){
          $activity = "Country has been changed from ".$lead->getOriginal('country')." to ".$request->input('country');
          create_log('leads', $lead->id, $activity);
        }

        if($lead->getOriginal('city') != $request->input('city')){
          $activity = "City has been changed from ".$lead->getOriginal('city')." to ".$request->input('city');
          create_log('leads', $lead->id, $activity);
        }

        if($lead->getOriginal('state') != $request->input('state')){
          $activity = "State has been changed from ".$lead->getOriginal('state')." to ".$request->input('state');
          create_log('leads', $lead->id, $activity);
        }

        if($lead->getOriginal('zip') != $request->input('zip')){
          $activity = "Zip has been changed from ".$lead->getOriginal('zip')." to ".$request->input('zip');
          create_log('leads', $lead->id, $activity);
        }

        if($lead->getOriginal('address') != $request->input('address')){
          $activity = "Address has been changed from ".$lead->getOriginal('address')." to ".$request->input('address');
          create_log('leads', $lead->id, $activity);
        }

        DB::commit();
    		
    		if(! $request->ajax()){
               return redirect()->route('leads.index')->with('success', _lang('Updated Sucessfully'));
            }else{
    		   return response()->json(['result'=>'success','action'=>'update', 'message'=>_lang('Updated Sucessfully'),'data'=>$lead]);
    		}
	    
    }
	
	  public function get_lead_info( $id = '' ){
  		$lead = Lead::where("id",$id)
  					      ->where("company_id",company_id())->first();
  		echo json_encode($lead);				  	
	  }

     /**
     * Store File to Lead.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function upload_file(Request $request)
    { 

        $max_size = get_option('file_manager_max_upload_size',2) * 1024;
        $supported_file_types = get_option('file_manager_file_type_supported','png,jpg,jpeg');
         
        $validator = Validator::make($request->all(), [
          'related_id' => 'required',
          'file' => "required|file|max:$max_size|mimes:$supported_file_types",
        ]);

        if ($validator->fails()) {
            if($request->ajax()){ 
                return response()->json(['result'=>'error','message'=>$validator->errors()->all()]);
            }else{
                return back()->withErrors($validator)
                             ->withInput();
            }            
        }
    
        $file_path = '';
        if($request->hasfile('file'))
        {
            $file = $request->file('file');
            $file_path = time().$file->getClientOriginalName();
            $file->move(public_path()."/uploads/project_files/", $file_path);
        }

        $projectfile = new \App\ProjectFile();
        $projectfile->related_to = 'leads';
        $projectfile->related_id = $request->input('related_id');
        $projectfile->file = $file_path;
        $projectfile->user_id = Auth::id();
        $projectfile->company_id = company_id();

        $projectfile->save();

        create_log('leads', $projectfile->related_id, _lang('Uploaded File'));

        //Prefix output
        $projectfile->file = '<a href="'. url('leads/download_file/'.$projectfile->file) .'">'.$projectfile->file .'</a>';
        $projectfile->user_id = '<a href="'. action('StaffController@show', $projectfile->user->id) .'" data-title="'. _lang('View Staf Information') .'"class="ajax-modal-2">'. $projectfile->user->name .'</a>';
        $projectfile->remove = '<a class="ajax-get-remove" href="'. url('leads/delete_file/'.$projectfile->id) .'">'. _lang('Remove') .'</a>';

        if(! $request->ajax()){
           return back()->with('success', _lang('File Uploaded Sucessfully'));
        }else{
           return response()->json(['result'=>'success','action'=>'store','message'=>_lang('File Uploaded Sucessfully'),'data'=>$projectfile, 'table' => '#files_table']);
        }
        
   }

   /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function delete_file(Request $request, $id)
    {
        if(Auth::user()->user_type == 'admin'){
            $projectfile = \App\ProjectFile::where($id)
                                           ->where('company_id',$company_id());
            unlink(public_path('uploads/project_files/'.$projectfile->file));
            $projectfile->delete();

            create_log('leads', $id, _lang('File Removed'));
        }

        if(Auth::user()->user_type != 'admin'){
            $projectfile = \App\ProjectFile::where('id',$id)
                                           ->where('user_id',Auth::id())
                                           ->first();
            if(!$projectfile){
                if(! $request->ajax()){
                   return back()->with('error',_lang('Sorry only admin or creator can remove this file !'));
                }else{
                   return response()->json(['result'=>'error','message'=>_lang('Sorry only admin or creator can remove this file !')]);
                }

            }                              
            unlink(public_path('uploads/project_files/'.$projectfile->file));
            $projectfile->delete();

            create_log('leads', $id, _lang('File Removed'));
        }

        if(! $request->ajax()){
           return back()->with('success',_lang('Removed Sucessfully'));
        }else{
           return response()->json(['result'=>'success','action'=>'delete','message'=>_lang('Removed Sucessfully'),'id'=>$id, 'table' => '#files_table']);
        }
        
    }

    public function download_file(Request $request, $file){
        $file = 'public/uploads/project_files/'.$file;
        return response()->download($file);
    }

    /**
     * Store note.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function create_note(Request $request)
    {    
        $validator = Validator::make($request->all(), [
            'related_id' => 'required',
            'note' => 'required',
        ]);

        if ($validator->fails()) {
            if($request->ajax()){ 
                return response()->json(['result'=>'error','message'=>$validator->errors()->all()]);
            }else{
                return redirect()->back()
                                 ->withErrors($validator)
                                 ->withInput();
            }            
        }
        
        $lead = Lead::find($request->input('related_id'));
        if ($lead->getOriginal('lead_status_id') != $request->input('lead_status_id')) {
          $activity = "Status has been changed from ".get_lead_curent_status($lead->getOriginal('lead_status_id'))." to ".get_lead_curent_status($request->input('lead_status_id'));
          create_log('leads', $lead->id, $activity);
        }
        $lead->lead_status_id = $request->lead_status_id;
        $lead->not_interested = $request->not_interested;
        $lead->status_date = $request->status_date;
        $lead->status_time = $request->status_time;
        $lead->save();
        
        $note = new \App\Note();
        $note->related_to ='leads';
        $note->related_id = $request->input('related_id');
        $note->note = $request->input('note');
        $note->user_id = Auth::id();
        $note->company_id = company_id();

        $note->save();
        
        if(isset($request->members)){
            $to = $request->input('members');
            $subject = "You have new notification for a lead ID: ".$request->input('related_id');
            
            $htmlContent = '
            <html>
            <body>
                <p>'.$request->input('note').'</p>
            </body>
            </html>';
            
            // Set content-type header for sending HTML email
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            
            // Additional headers
            $headers .= 'From: CRM<crm@digitalhubsolution.com>' . "\r\n";
            /*$headers .= 'Cc: welcome@example.com' . "\r\n";
            $headers .= 'Bcc: welcome2@example.com' . "\r\n";*/
            
            // Send email
        /*    if(mail($to,$subject,$htmlContent,$headers)):
                create_log('leads', $note->related_id, _lang('Added Note and Email has sent successfully.'));
            else:
                create_log('leads', $note->related_id, _lang('Added Note and Email sending fail.'));
            endif;*/
            create_log('leads', $note->related_id, _lang('Added Note and Email has sent successfully.'));
        }else{
            create_log('leads', $note->related_id, _lang('Added Note'));
        }

        //Prefix Output
        $note->created = '<small><a href="'. action('StaffController@show', $note->user->id) .'" data-title="'. _lang('View Staf Information') .'" class="ajax-modal-2">'.$note->user->name.'</a>('.$note->created_at.')<br>'.$note->note.'</small>';
        $note->action = '<a href="'. url('leads/delete_note/'.$note->id) .'" class="ajax-get-remove"><i class="far fa-trash-alt text-danger"></i></a>';

        if(! $request->ajax()){
           return back()->with('success', _lang('Saved Sucessfully'));
        }else{
           return response()->json(['result'=>'success','action'=>'store','message'=>_lang('Saved Sucessfully'),'data'=>$note, 'table' => '#notes_table']);
        }
        
   }
   function gauravRoute(Request $request,$id){
        $lead = Lead::find($id);
        if($lead->getOriginal('company_name') != $request->input('company_name')){
            $activity = $request->field." has been changed from ".$lead->getOriginal($request->field)." to ".$request->value;
            create_log('leads', $lead->id, $activity);
        }
        $lead->update([$request->field=>$request->value]);
   }

   /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function delete_note(Request $request, $id)
    {
        if(Auth::user()->user_type == 'admin'){
            $note = \App\Note::where('id', $id)
                             ->where('company_id', company_id());
            $note->delete();
            create_log('leads', $id, _lang('Removed Note'));
        }

        if(Auth::user()->user_type != 'admin'){
            $note = \App\Note::where('id',$id)
                             ->where('user_id',Auth::id())
                             ->first();
            if(!$note){
                if(! $request->ajax()){
                   return back()->with('error',_lang('Sorry only admin or creator can remove this file !'));
                }else{
                   return response()->json(['result'=>'error','message'=>_lang('Sorry only admin or creator can remove this file !')]);
                }

            }                              
            $note->delete();
            create_log('leads', $id, _lang('Removed Note'));
        }

        if(! $request->ajax()){
           return back()->with('success',_lang('Removed Sucessfully'));
        }else{
           return response()->json(['result'=>'success','action'=>'delete','message'=>_lang('Removed Sucessfully'),'id'=>$id, 'table' => '#notes_table']);
        }
        
    }


    public function convert_to_customer(Request $request, $lead_id){

        if($request->isMethod('get')){
            
            $data = array();
            $lead = Lead::where('id',$lead_id)
                                ->where('company_id', company_id())
                                ->first();
            return view('backend.accounting.lead.convert_to_customer')->with('lead', $lead);
        }else{
            $validator = Validator::make($request->all(), [
                'profile_type'  => 'required|max:20',
                'company_name'  => 'required|max:50',
              //  'contact_name'  => 'required|max:50',
                'contact_email' => [
                    'nullable',
                    'email',
                ],
                'contact_phone' => 'required|max:20',Rule::unique('contacts')->where('company_id',company_id()),
                'country'       => 'nullable|max:50',
                'currency'      => 'required|max:3',
                'city'          => 'nullable|max:50',
                'state'         => 'nullable|max:50',
                'zip'           => 'nullable|max:20',
                'contact_image' => 'nullable|image||max:5120',
                'group_id'      => 'required',
                'lead_id'      => 'required',
            ],[
                'group_id.required' => 'The group field is required.' 
            ]);
            
            if ($validator->fails()) {
                if($request->ajax()){ 
                    return response()->json(['result'=>'error','message'=>$validator->errors()->all()]);
                }else{
                    return back()->withErrors($validator)
                                 ->withInput();
                }           
            }
            $contactcheck = Contact::where('contact_phone',$request->input('contact_phone'))
                ->where('company_id', company_id())
                ->first();
            if($contactcheck){
                return back()->withErrors($validator)
                    ->withInput()->with('error','Already Present');
            }
            
            $contact_image ="avatar.png";       
            if($request->hasfile('contact_image'))
            {
                 $file = $request->file('contact_image');
                 $contact_image = "contact_image".time().'.'.$file->getClientOriginalExtension();
                 $file->move(public_path()."/uploads/contacts/", $contact_image);
            }

            
            DB::beginTransaction();

            //Check if lead ID is valid
            $lead = Lead::where('id',$request->lead_id)
                        ->where('company_id',company_id())
                        ->first();

            if( ! $lead ){
                if($request->ajax()){ 
                    return response()->json(['result'=>'error','message'=>'Invalid Lead !']);
                }else{
                    return back()->with('error', _lang('Invalid Lead !'))->withInput();
                }  
            }            

            //Check client has already an account
            $other = User::where('email',$request->contact_email)
                         ->where('user_type','!=','client')->first();

            if( $other ){
                if($request->ajax()){ 
                    return response()->json(['result'=>'error','message'=>'Sorry, This email already registered with an company admin or staff !']);
                }else{
                    return back()->with('error', _lang('Sorry, This email already registered with an company admin or staff !'))->withInput();
                }   
            }

            $client = User::where('email',$request->contact_email)
                          ->where('user_type','client')->first();
            
            $cusis=Contact::max('customer_id');
            
            if(!empty($cusis)){
$maxv= (int)(explode("DHS",$cusis))[1];
}else{
   $maxv=0; 
}
//print_r($maxv);die;
$newvalue=$maxv +1;
          if($newvalue<=9){
            $fvalue="DHS000".$newvalue; 
          }elseif($newvalue>=10 && $newvalue<=99){
           $fvalue="DHS00".$newvalue;    
          }elseif($newvalue>=100 && $newvalue<=999){
            $fvalue="DHS0".$newvalue;  
          }else{
           $fvalue="DHS".$newvalue;   
          }
          

            $contact = new Contact();
            $contact->profile_type = $request->input('profile_type');
              $contact->customer_id =$fvalue ;
            $contact->company_name = $request->input('company_name');
            $contact->contact_name = $request->input('contact_name');
            $contact->contact_email = $request->input('contact_email');
            $contact->contact_phone = $request->input('contact_phone');
            $contact->vat_id = $request->input('vat_id');
            $contact->reg_no = $request->input('reg_no');
            $contact->country = $request->input('country');
            $contact->currency = $request->input('currency');
            $contact->amount = $request->input('amount');
            $contact->subscription_type = $request->input('subscription_type');
            $contact->time_zone = $request->input('time_zone');
                		    		$contact->zone_state = $request->input('zone_state');

            $contact->city = $request->input('city');
            $contact->state = $request->input('state');
            $contact->zip = $request->input('zip');
            $contact->address = $request->input('address');
            $contact->facebook = $request->input('facebook');
            $contact->twitter = $request->input('twitter');
            $contact->linkedin = $request->input('linkedin');
            $contact->remarks = $request->input('remarks');
            if($client){
                $contact->user_id = $client->id;
            }
            $contact->group_id = $request->input('group_id');
            $contact->company_id = company_id();
          //  $contact->converted_by_user_id = Auth::user()->id;
            $contact->converted_by_user_id = $lead->assigned_user_id;
            $contact->contact_image = $contact_image;
        
            $contact->save();

            //Update Lead 
            $lead->converted_lead = 1;
            $lead->lead_status_id = 27;
            $lead->save();
            
            //Update Package limit
            update_package_limit('contacts_limit');
            
            create_log('leads', $lead_id, _lang('Converted Lead to Customer'));

            DB::commit();
            

            if(! $request->ajax()){
               //return redirect('contacts/'.$contact->id)->with('success', _lang('Lead converted sucessfully'));
               return redirect('contacts')->with('success', _lang('Lead converted sucessfully'));
            }else{
               return response()->json(['result'=>'success','action'=>'store','message'=>_lang('Lead converted sucessfully'),'data' => $contact]);
            }
        }   
       
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        DB::beginTransaction();

        $company_id = company_id();

        $lead = Lead::where('id',$id)
                    ->where('company_id',$company_id);
        $lead->delete();

        $quotations = \App\Quotation::where('related_to','leads')
                                    ->where('related_id', $id)
                                    ->where('company_id', $company_id);
        $quotations->delete();


        $projectfiles = \App\ProjectFile::where('related_id', $id)
                                        ->where('related_to', 'leads')
                                        ->where('company_id', $company_id);
        $projectfiles->delete();


        $notes = \App\Note::where('related_id', $id)
                          ->where('related_to', 'leads')
                          ->where('company_id', $company_id);     
        $notes->delete();

        return redirect()->route('leads.index')->with('success',_lang('Deleted Sucessfully'));
    }

    /**
     * Assigned the not assigned leads in bulk.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function not_assigned_leads(Request $request)
    {
        $user_type = Auth::user()->user_type;

        $leads = Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->select('leads.*')
                     ->where("leads.company_id",company_id())
                     ->where('assigned_user_id', '=', 0)
                     ->orderBy("leads.id","desc");

        return Datatables::eloquent($leads)
                        
                        ->addColumn('check', function ($lead) {
                            return '<input type="checkbox" class="checkBoxClass" name="lead_assigned_id[]" value="'. $lead->id.'">';
                        })
                        ->editColumn('name', function ($lead) {
                            return '<a href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="ajax-modal">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('lead_status.title', function ($lead) {
                            $status_color = $lead->lead_status->color;
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$lead->lead_status->title}</span>";
                        })
                        ->addColumn('action', function ($lead) {
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['check','action','lead_status.title','name'])
                        ->make(true);
    }

    public function not_assign(Request $request)
    {
      if ($request->lead_assigned_id != '') {
        foreach ($request->lead_assigned_id as $key => $value) {
            $contact = Lead::find($value);
            $contact->assigned_user_id = $request->assigned_user_id;
            $contact->save();
        }
        return redirect()->route('leads.not-assigned-leads');
      } else {
          $users = User::where('company_id', company_id())->where('role_id', 8)->get();
          $leads = Lead::where('company_id', company_id())->where('assigned_user_id', 0)->get();
      return view('backend.accounting.lead.not-assigned-leads')->with('users', $users)->with('leads', $leads);
    }
  }

  public function previous_data(Request $request)
    {

            // $validator = Validator::make($request->all(), [
            //     'lead_status_id'    => 'required',
            //     'lead_source_id'    => 'required',
            //     'assigned_user_id'  => 'required',
            //     'file'              => 'required|mimes:xlsx',
            // ]);
            $validator = Validator::make($request->all(), [
                'file'              => 'required',
            ]);
            if ($validator->fails()) {
              return redirect('/dashboard')->withErrors($validator)->withInput();          
            }
                
            $fileName = $_FILES["file"]["tmp_name"];

            $pre_data = PreviousData::where('year', '=', $request->year);

            $pre_data->delete();
    
        if ($_FILES["file"]["size"] > 0) {
        $i = 0;
        
        $file = fopen($fileName, "r");
        
        while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {

                if($i != 0){
                    $contact = new PreviousData();            
                    $contact->company_id = company_id();
                    $contact->year = $request->year;
                    
                    $months = "";
                    if (isset($column[0])) {
                        $months = $column[0];
                        $contact->month = $months;
                    }
                    $leads = "";
                    if (isset($column[1])) {
                        $leads =  $column[1];
                        $contact->leads = $leads;
                    }
                    $amount = "";
                    if (isset($column[2])) {
                        $amount = $column[2];
                        $contact->amount = $amount;
                    }
                    $contact->save();

                }
                
                $i++;
            }
  }
  return redirect('/dashboard');
}

public function compare_graph($year)
  {
    $next_year = $year + 1;
    $company_id = company_id();
    $graph1 = PreviousData::where('company_id', '=',$company_id)->where('year', '=',$year)->get()->toArray();
    $graph2 = PreviousData::where('company_id', '=',$company_id)->where('year', '=',$next_year)->get()->toArray();
    $f1 = '';
    foreach ($graph1 as $key => $value) {
      $f1 .= '<div class="layer" data-html="true" data-toggle="tooltip" data-placement="top" title="Converted Lead: '.$value['leads'].'<br/> Total Amount: '.$value["amount"].'">'.$value["month"].'</div>';
    }
    $f1 .= '<div class="innerCircle"><div class="content"><b>'.$year.'</b></div></div>'; 

    $f2 = '';
    foreach ($graph2 as $key => $value) {
      $f2 .= '<div class="layer"  data-html="true" data-toggle="tooltip" data-placement="top" title="Converted Lead: '.$value["leads"].'<br/> Total Amount: '.$value["amount"].'">'.$value["month"].'</div>';
    }
    $f2 .= '<div class="innerCircle"><div class="content"><b>'.$next_year.'</b></div></div>';

    echo json_encode(array('f1' => $f1, 'f2' => $f2));
    exit;
  }

  public function set_reminder(Request $request)
  {
    $user_id = Auth::user()->id;
        $reminder = Reminder::where('user_id', '=', $user_id)->where('lead_id', '=', $request->lead_id)->get();
        if (count($reminder)>0) {
            Reminder::where('lead_id', $request->lead_id)->update(['date' => $request->date,'description' => $request->description, 'active' => 1]);
            return redirect('/leads')->with('success', _lang('Reminder updated successfully'));
        } else {
            $DdSalePhone = new Reminder();
            $DdSalePhone->lead_id = $request->lead_id;
            $DdSalePhone->user_id = $user_id;
            $DdSalePhone->date = $request->date;
            $DdSalePhone->description = $request->description;
            $DdSalePhone->save();
            return redirect('/leads')->with('success', _lang('Remainder saved Sucessfully'));
        }
  }

  public function reminders($value='')
  {
    $today = Carbon::now();
    $td = $today->format('Y-m-d');
    $count = \DB::table('reminders')
    ->whereDate('date', '=', $td)
    ->where('active', '=', 1)
    ->get();

    $re = '';
    foreach ($count as $key => $value) {
      $re .= '<a href="'.url('/').'/leads/'.$value->lead_id.'"><div class="notify-text">
                <p><b>'.client_name($value->lead_id).'</p><br><b>Note:</b> <span> '.$value->description.'</span><br>
                              <span><b>Time:</b> '.$td.'</span>
              </div></a>';
    }
    echo json_encode(array('re' => $re, 'f2' => count($count), 'reminder' => $count));
    exit;
  }

  public function save_card(Request $request)
  {
    $user_id = Auth::user();
        $card = CardDetail::where('company_id', '=', company_id())->where('lead_id', '=', $request->lead_id)->get()->toArray();
        if (count($card)>0) {

            if($card[0]['c_number'] != $request->input('c_number')){
                  $activity = 'Card number changed from '.$card[0]['c_number']." to ".$request->input('c_number');
                  create_log('leads', $request->lead_id, $activity);
                }

                if($card[0]['c_exp_month'] != $request->input('c_exp_month')){
                  $activity = 'Card Exp Month changed from '.$card[0]['c_exp_month']." to ".$request->input('c_exp_month');
                  create_log('leads', $request->lead_id, $activity);
                }

                if($card[0]['c_exp_year'] != $request->input('c_exp_year')){
                  $activity = 'Card Exp Date changed from '.$card[0]['c_exp_year']." to ".$request->input('c_exp_year');
                  create_log('leads', $request->lead_id, $activity);
                }

                if($card[0]['c_cvv'] != $request->input('c_cvv')){
                  $activity = 'Card CVV number changed from '.$card[0]['c_cvv']." to ".$request->input('c_cvv');
                  create_log('leads', $request->lead_id, $activity);
                }

                if($card[0]['c_name'] != $request->input('c_name')){
                  $activity = 'Name on card changed from '.$card[0]['c_name']." to ".$request->input('c_name');
                  create_log('leads', $request->lead_id, $activity);
                }
            
            CardDetail::where('lead_id', $request->lead_id)->update(['c_number' => $request->c_number,'c_exp_month' => $request->c_exp_month, 'c_name' => $request->c_name, 'c_exp_year' => $request->c_exp_year, 'c_cvv' => $request->c_cvv]);
            return redirect('/leads')->with('success', _lang('Details updated successfully'));
        } else {
                $card = new CardDetail();
                $card->lead_id = $request->lead_id;
                $card->company_id = company_id();
                $card->c_number = $request->c_number;
                $card->c_exp_month = $request->c_exp_month;
                $card->c_name = $request->c_name;
                $card->c_exp_year = $request->c_exp_year;
                $card->c_cvv = $request->c_cvv;
                $card->save();

                  $activity = "Added the card details.";
                  create_log('leads', $request->lead_id, $activity);

                return redirect('/leads')->with('success', _lang('Details saved Sucessfully'));
            }
    
  }
  
  public function total_converted(Request $request){
      return view('backend.accounting.lead.total-converted');
  }
  
  public function today_assigned(Request $request){
      return view('backend.accounting.lead.today_assigned');
  }
  
  public function get_assigned_table_data(Request $request){
        
        $user_type = Auth::user()->user_type;
        //Sales Person
        if(Auth::user()->role_id == 8){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.assigned_date",date('Y-m-d'))
                     ->Where('assigned_user_id',  Auth::user()->id);
        }
        
        //Sales Head
        if(Auth::user()->role_id == 17){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.assigned_date",date('Y-m-d'));
        }
        
        //Admin
        if(Auth::user()->user_type == 'user'){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.assigned_date",date('Y-m-d'));
        }
        $leads=$leads ->orderBy("leads.id","desc");

        

        return Datatables::eloquent($leads)
                        
                        ->editColumn('name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name', 'created_at', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }
  
  public function get_converted_table_data(Request $request){
        
        $user_type = Auth::user()->user_type;
        
        //Sales Person
        if(Auth::user()->role_id == 8){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.converted_lead",1)
                     ->Where('assigned_user_id',  Auth::user()->id);
        }
        
        //Sales Head
        if(Auth::user()->role_id == 17){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.converted_lead",1);
        }
        
        //Admin
        if(Auth::user()->user_type == 'user'){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.converted_lead",1);
        }

        $leads=$leads ->orderBy("leads.id","desc");

        

        return Datatables::eloquent($leads)
                        
                        ->editColumn('name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name', 'created_at', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }
    
    public function today_followup_post(Request $request, $week="anuj"){
       
        $user_type = Auth::user()->user_type;
        //Sales Person
        if(Auth::user()->role_id == 8){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",26)
                     
                     
                     
                     ->Where('assigned_user_id',  Auth::user()->id);
        }
        
        //Sales Head
        if(Auth::user()->role_id == 17){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",26);
        }
        
        //Admin
        if(Auth::user()->user_type == 'user'){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",26);
        }
        if($week=="anuj"){
            $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            //$leads=$leads->where("leads.status_date",date('Y-m-d'));
        }else{
            
            //$leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            $leads=$leads;
        }
        $leads=$leads ->orderBy("leads.id","desc");

        

        return Datatables::eloquent($leads)
                        
                        ->editColumn('name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name', 'created_at', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }
    
    public function dead(Request $request, $week="anuj"){
       
        $user_type = Auth::user()->user_type;
        //Sales Person
        if(Auth::user()->role_id == 8){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",28)
                     
                     
                     
                     ->Where('assigned_user_id',  Auth::user()->id);
        }
        
        //Sales Head
        if(Auth::user()->role_id == 17){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",28);
        }
        
        //Admin
        if(Auth::user()->user_type == 'user'){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",28);
        }
        if($week=="anuj"){
            $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            //$leads=$leads->where("leads.status_date",date('Y-m-d'));
        }else{
            
            //$leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            $leads=$leads;
        }
        $leads=$leads ->orderBy("leads.id","desc");

        

        return Datatables::eloquent($leads)
                        
                        ->editColumn('name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name', 'created_at', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }
    
    public function intro_shared(Request $request, $week="anuj"){
       
        $user_type = Auth::user()->user_type;
        //Sales Person
        if(Auth::user()->role_id == 8){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",30)
                     
                     
                     
                     ->Where('assigned_user_id',  Auth::user()->id);
        }
        
        //Sales Head
        if(Auth::user()->role_id == 17){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",30);
        }
        
        //Admin
        if(Auth::user()->user_type == 'user'){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",30);
        }
        if($week=="anuj"){
            $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            //$leads=$leads->where("leads.status_date",date('Y-m-d'));
        }else{
            
           // $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
           $leads=$leads;
        }
        $leads=$leads ->orderBy("leads.id","desc");

        

        return Datatables::eloquent($leads)
                        
                        ->editColumn('name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name', 'created_at', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }
    
    
    public function indiscussion(Request $request, $week="anuj"){
       
        $user_type = Auth::user()->user_type;
        //Sales Person
        if(Auth::user()->role_id == 8){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",31)
                     
                     
                     
                     ->Where('assigned_user_id',  Auth::user()->id);
        }
        
        //Sales Head
        if(Auth::user()->role_id == 17){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",31);
        }
        
        //Admin
        if(Auth::user()->user_type == 'user'){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",31);
        }
        if($week=="anuj"){
            $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            //$leads=$leads->where("leads.status_date",date('Y-m-d'));
        }else{
            
           // $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
           $leads=$leads;
        }
        $leads=$leads ->orderBy("leads.id","desc");

        

        return Datatables::eloquent($leads)
                        
                        ->editColumn('name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name', 'created_at', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }
    
    public function hot_clients(Request $request, $week="anuj"){
       
        $user_type = Auth::user()->user_type;
        //Sales Person
        if(Auth::user()->role_id == 8){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",29)
                     
                     
                     
                     ->Where('assigned_user_id',  Auth::user()->id);
        }
        
        //Sales Head
        if(Auth::user()->role_id == 17){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",29);
        }
        
        //Admin
        if(Auth::user()->user_type == 'user'){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",29);
        }
        if($week=="anuj"){
            $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            //$leads=$leads->where("leads.status_date",date('Y-m-d'));
        }else{
            
           // $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
           $leads=$leads;
        }
        $leads=$leads ->orderBy("leads.id","desc");

        

        return Datatables::eloquent($leads)
                        
                        ->editColumn('name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name', 'created_at', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }
    
    public function not_interested(Request $request, $week="anuj"){
       
        $user_type = Auth::user()->user_type;
        //Sales Person
        if(Auth::user()->role_id == 8){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",33)
                     
                     
                     
                     ->Where('assigned_user_id',  Auth::user()->id);
        }
        
        //Sales Head
        if(Auth::user()->role_id == 17){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",33);
        }
        
        //Admin
        if(Auth::user()->user_type == 'user'){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",33);
        }
        if($week=="anuj"){
            $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            //$leads=$leads->where("leads.status_date",date('Y-m-d'));
        }else{
            
            //$leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            $leads=$leads;
        }
        $leads=$leads ->orderBy("leads.id","desc");

        

        return Datatables::eloquent($leads)
                        
                        ->editColumn('name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name', 'created_at', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }
    
    public function contact(Request $request, $week="anuj"){
       
        $user_type = Auth::user()->user_type;
        //Sales Person
        if(Auth::user()->role_id == 8){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",28)
                     
                     
                     
                     ->Where('assigned_user_id',  Auth::user()->id);
        }
        
        //Sales Head
        if(Auth::user()->role_id == 17){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",28);
        }
        
        //Admin
        if(Auth::user()->user_type == 'user'){
            $leads=Lead::with('lead_status')
                     ->with('lead_source')
                     ->with('assigned_user')
                     ->with('zonename')
                     ->select('leads.*')
                     ->where("leads.lead_status_id",28);
        }
        if($week=="anuj"){
            $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
            //$leads=$leads->where("leads.status_date",date('Y-m-d'));
        }else{
            
           // $leads=$leads->whereBetween("leads.status_date",[date('Y-m-01'),date('Y-m-31')]);
           $leads=$leads;
        }
        $leads=$leads ->orderBy("leads.id","desc");

        

        return Datatables::eloquent($leads)
                        
                        ->editColumn('name', function ($lead) {
                            return '<a target="_blank" href="'.action('LeadController@show', $lead->id).'" data-title="'. _lang('View Lead Details') .'" class="">'.$lead->name.'</a>';
                        })
                        ->editColumn('contact_date', function ($lead) {
                            $date_format = get_company_option('date_format','Y-m-d');
                            return date($date_format, strtotime($lead->contact_date));
                        })
                        ->editColumn('assigned_user.name', function ($lead) {
                            

                            if ($lead->assigned_user->name != '') {
                              $status = $lead->assigned_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        ->editColumn('marketing_user.name', function ($lead) {
                            

                            if ($lead->created_user->name != '') {
                              $status = $lead->created_user->name;
                            } else {
                              $status = 'NA';
                            }
                            
                            return $status;
                        })
                        
                        
                        ->editColumn('lead_status.title', function ($lead) {
                            

                            if ($lead->lead_status->title != '') {
                              $status = $lead->lead_status->title;
                              $status_color = $lead->lead_status->color;
                            } else {
                              $status = 'Open';
                              $status_color = '#1f5cf5';
                            }
                            
                            return "<span class='badge badge-primary' style='background:{$status_color}'>{$status}</span>";
                        })
                        ->editColumn('created_at', function ($lead) {
                            return  date('Y-m-d', strtotime($lead->created_at));
                        })
                        ->addColumn('action', function ($lead) {
                            if($lead['assigned_user_id'] == 0){
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }elseif($lead['assigned_user_id'] == Auth::user()->id){
                                return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .'<a target="_blank" href="'.action('LeadController@edit', $lead['id']).'" data-title="'. _lang('Update Lead') .'" class="btn btn-warning btn-xs"><i class="ti-pencil"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>';
                            }else{
                               return '<form action="'.action('LeadController@destroy', $lead['id']).'" class="text-center" method="post">'
                                .'<a target="_blank" href="'.action('LeadController@show', $lead['id']).'" data-title="'. _lang('View Lead Details') .'" class="btn btn-primary btn-xs"><i class="ti-eye"></i></a>&nbsp;'
                                .csrf_field()
                                .'</form>'; 
                            }
                                
                        })
                        ->setRowId(function ($lead) {
                            return "row_".$lead->id;
                        })
                        ->rawColumns(['action', 'lead_status.title','name', 'created_at', 'assigned_user.name', 'marketing_user.name'])
                        ->make(true);                                
    }


}