<?php

namespace Gisplus\Package\Crm\Models;

use Auth;
use Gisplus\Package\Crm\Models\CrmUser;
use Gisplus\Package\Crm\Models\ReferralHistory;
use Gisplus\Package\Crm\Models\BusinessReferral;
use Gisplus\Package\Crm\Models\TrackingHistory;
use Gisplus\Package\Crm\Models\LeadTransfer;
use Gisplus\Package\Crm\Models\LeadStatusHistory;
use DB;
use Illuminate\Database\Eloquent\Model;


class Lead extends CrmUser
{
    protected $table = 'leads';

    private $generic_condition;

    public function __construct()
    {
        $condition = [];

        if(\Auth::user()->id != 1)
        {
            $condition += ['sales_person_id' => \Auth::user()->id];
        }

       $this->setCondition($condition);
    }

    public function setCondition($condition = [])
    {
        $this->generic_condition = $condition;
    }
    


    public function getCondition()
    {
        return $this->generic_condition;
    }

    public function getLeadList()
    {
        return Lead::whereHas('activeTransferLead' , function($query){

            $query->where($this->getCondition());


        })->orderBy('id', 'desc')->get();

    }

    public function getLeadByCondition($sales_person_id,$search_condition = [])
    {
        return Lead::where($search_condition)->whereHas('activeTransferLead' , function($query) use ($sales_person_id) {

               if(Auth::user()->id == 1)
                {
                    if($sales_person_id > 0)
                    {
                     
                 $query->where('sales_person_id',$sales_person_id);
            }


                }
                else{
                   
                    $query->where($this->getCondition());

                }


        })->orderBy('id', 'desc')->get();

    }

    // public function getLeadListByCondition($object)
    // {
    //     $condition = $this->getCondition();

    //     return Lead::where($condition)->where('status', $object['status'])->where('lead_no', $object['lead_no'])->where('title', $object['title'])->where('sales_person', $object['sales_person'])->orderBy('id', 'desc')->get();

    // }
    public function getLeadListCount()
   {
        return Lead::all()->count();

   }

   public function getLeadCountByStatus($status=[])
   {
    return Lead::wherein('status' , $status)->count();

   }
   public function getLatestLeads()
   {
    return Lead::orderBy('id' , 'desc')->limit(20)->get();

   }

    public function getLeadById($id)
    {
    return Lead::where(['id' => $id])->with(['leadTasks','leadVisits', 'leadReferrals','activeTransferLead','transferLead','leadStatuses'])->first();

    }

    public function getChartLead(){

        $lead_list_chart = array();
        $leads[0] = 'data1';
        $count = 0;
        $month_list = ['Jan', 'Feb', 'March', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    ];
        $year = date('Y');
        foreach ($month_list as $key=>$month)
        {
            $first_date = date('Y-m-d',strtotime('first day of '.$month.' '.$year));
    
            $last_date = date('Y-m-d',strtotime('last day of '.$month.' '.$year));
    
            $lead_list_chart[$count] = $month;
            $leads[$count+1] = Lead::whereDate('created_at','>=' , $first_date)->whereDate('created_at','<=',$last_date)->count();
            $count++;
    
        }
        return ['leads' => $leads, 'lead_list_chart' => $lead_list_chart];

       }


    public function storeLead($object)
    {
        return DB::transaction(function() use ($object){


            $lead = new Lead;

            if(isset($object['customer']))
            {
                $lead->user_id      = $object['customer'];
                $lead->name         =  $object['name'];
                $lead->email        = $object['email'];
                $lead->contact      = $object['contact'];
                $lead->title        = $object['title'];
                $lead->description  = $object['description'];
                $lead->date         = $object['date'];
                $lead->added_by     = Auth::user()->id;
                // $lead->sales_person_id = $object['sales_person'];
                // $lead->status       = $object['status'];
          
            }
            else{
                $lead->name             =  $object['name'];
                $lead->email            = $object['email'];
                $lead->contact          = $object['contact'];
                $lead->title            = $object['title'];
                $lead->description      = $object['description'];
                $lead->date             = $object['date'];
                $lead->added_by         = Auth::user()->id;

            
                // $lead->sales_person_id  = $object['sales_person'];
                // $lead->status       = $object['status'];
          
            }

            $lead->lead_no = $this->generateLeadNo();
        //    dd($lead);

            $lead->save();
            
            $leadstatus_history = new LeadStatusHistory;
            $lead_status['lead']          = $lead->id;
            $lead_status['status']        = $lead->status;
            $leadstatus_history           =  $leadstatus_history->storeLeadStatusHistory($lead_status);



            $transfer_lead = new LeadTransfer;

            $transfer_info['lead']          = $lead->id;
            if($object['sales_person']>0)
            {
                $transfer_info['sales_person']  = $object['sales_person'];

            }
            else{
                $transfer_info['sales_person']  = Auth::user()->id;

            }
            $transfer_lead    =  $transfer_lead->storeLeadTransfer($transfer_info);

            // $transfer_lead->save();


            $business_referral_id = 0;

            if(isset($object['is_business_referral']))
            {

                if(isset($object['business_referral']))
                {
                    $business_referral_id      = $object['business_referral'];
                    $object['lead']   = $lead->id ;
                    $referral_history = new ReferralHistory;
                    $referral_history = $referral_history->storeReferralHistory($object);


                    // $referral_history->lead_id                   = $lead->id;
                    // $referral_history->business_referral_id      = $business_referral_id;
                    // $referral_history->added_by                  = Auth::user()->id;

                    // $referral_history->save();

        
                }
                else{
                
                    $business_referral = new BusinessReferral;
                    
                    $object['lead']             = $lead->id;
                    $business_referral         = $business_referral->storeBusinessReferral($object);
                    $business_referral_id      = $business_referral->id;

                }
            }

            

            // $tracking_history     = new TrackingHistory;

            // $track_info['color']      = 'success';
            // $track_info['icon']       = 'fa fa-plus';
            // $track_info['lead']        = $lead->id;
            // $track_info['description'] = 'Lead has created against lead no. '.strtolower($lead->lead_no);
            // $track_info['added_by']     = $lead->added_by;
            // $track_info['created_at']   = $lead->created_at;
            

            // $tracking_history     = $tracking_history->storeTrackingHistory($track_info);

            return with($lead);
        });

    }

    public function updateLead($object)
    {
        return DB::transaction(function() use ($object){

         $lead = Lead::find($object['lead']);
        if(isset($lead->id))
        {
            if(isset($object['user']))
            {
                $lead->user_id      = $object['user'];
               
            }
            $lead->name         =  $object['name'];
            $lead->email        = $object['email'];
            $lead->contact      = $object['contact'];
            $lead->title        = $object['title'];
            $lead->description  = $object['description'];
            $lead->date         = $object['date'];
            $lead->status       = $object['status'];
            // $lead->sales_person_id  = $object['sales_person'];

          
            $lead->update();

            $leadstatus_history = new LeadStatusHistory;

            $lead_status['lead']          = $lead->id;
            $lead_status['status']        = $lead->status;
            
            $leadstatus_history           =  $leadstatus_history->updateLeadStatusHistory($lead_status);

            return with($lead);
        }

        });
  
    }

    public function removeLead($id)
    {
        return DB::transaction(function() use ($id){
            
            $lead = Lead::find($id);
           
            
            if(isset($lead->id))
            {
                $lead->delete();

                $task = new Task;
                // $task = Task::where(['lead_id' => $id])->delete();
                $task = $task->removeTask($lead->id);

                $visit = new Visit;
                $visit = $visit->removeVisit($lead->id);
            }
            return with($lead);

        });

    }

    public function generateLeadNo()
    {
        $count = Lead::count();
        return  'LD-'.str_pad(($count+1), 5, '0', STR_PAD_LEFT);
    }

    public function customer()
    {
        return $this->belongsTo(CrmUser::class, 'user_id')->withDefault();

    }

   

    public function leadTasks()
    {
        return $this->hasMany(Task::class, 'lead_id');
    }
    public function leadVisits()
    {
        return $this->hasMany(Visit::class, 'lead_id');
    }
    public function leadReferrals()
    {
        return $this->hasMany(ReferralHistory::class, 'lead_id');
    }

    public function leadStatuses()
    {
        return $this->hasMany(LeadStatusHistory::class, 'lead_id');
    }

    public function activeTransferLead()
    {
        return $this->hasOne(LeadTransfer::class, 'lead_id')->where('status' , "Active")->withDefault();
    }


    public function transferLead()
    {
        return $this->hasMany(LeadTransfer::class, 'lead_id');
    }



}
