HEX
Server: Apache/2.4.46 (Ubuntu)
System: Linux localhost 5.11.0-49-generic #55-Ubuntu SMP Wed Jan 12 17:36:34 UTC 2022 x86_64
User: root (0)
PHP: 7.4.16
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/html/fieldsblaze-heroku/app/Http/Controllers/APICustomerController.php
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use DB;
use App\Library\UserLib;
use App\Http\Controllers\APICommonController;
use App\Models\User;
use App\Library\ExternalDataBase;
use App\Models\Customer;
use App\Models\CustomerFile;
use App\Models\Departments;
use App\Models\CustomerType;
use App\Models\SalesArea;
use App\Models\PriceBook;
use App\Models\BeatPlan;
use App\Models\PaymentTerm;
use App\Models\Countries;
use App\Models\Contact;
use App\Models\Visits;
use App\Models\Order;
use App\Models\Collection;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

class APICustomerController extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $userLib;
    protected $externalDataBase;
    protected $APICommonController;
    public function __construct(UserLib $userLib, ExternalDataBase $externalDataBase,APICommonController $APICommonController)
	{
		$this->userLib = $userLib;
		$this->externalDataBase = $externalDataBase;
        $this->APICommonController = $APICommonController;
	}


    //User Registration
    public function createCustomer(Request $request) {
		//TODO What is device_token
        $data = $request->json()->all();
        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');
        $CustomerId = $this->userLib->useridGenrator();
        $OtpPassword = $this->userLib->otpGenrator();

        $tblData = array();

        $CreatedDate = date('Y-m-d H:i:s',time());

		// $validator = Validator::make($data, [
		// 	'Mobile' => 'required|string|max:255',
        // ]);
        // //check validation
        // if ($validator->fails())
        // {
        //     $response = [
        //         'Success' => false,
        //         'ResponseMessage' => "Mobile is required!",
        //         'ResponseCode' => '220',
        //         'ApiVersion' => env('APP_VERSION'),
        //     ];
        //     return response()->json($response);
        // }


        unset($data['id']);
        //Check Memeber is exist or not
        $custmer = Customer::where('CustomerName', $data['CustomerName'])->get();
        if ($custmer->count() > 0)
        {   //email is not exist

            $custmer = $custmer->first();
            $CustomerId = $custmer->CustomerId;
            $response = [
                'Success' => false,
                'ResponseMessage' => "Customer name already exist!",
                'ResponseCode' => "201",
                'CustomerId' => $CustomerId,
                'Customer' => $custmer,
                'ApiUrl' => env('APP_URL'),
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);


        }
        else
        {   //get user data


            $data['CustomerId'] = $CustomerId;


            $customerName = $data['CustomerName'];
            if($customerName)
            {
                $customerName = strtoupper($customerName);
                $CustomerCode = substr($customerName, 0, 4).$this->userLib->otpGenrator();
                $data['CustomerCode'] = $CustomerCode;
            }


            ////////////////////////////

            if(count($data['Contact']) > 0)
            {
                $ContactData = $data['Contact'];
                for($k=0; $k < count($ContactData); $k++)
                {
                    $condata = $ContactData[$k];




                    $Contact = Contact::where('Mobile',$condata['Mobile'])->get();
                    if ($Contact->count() > 0)
                    {   //email is not exist

                        $custmer = $Contact->first();
                        $response = [
                            'Success' => false,
                            'ResponseMessage' => "Contact mobile already exist!",
                            'ResponseCode' => "201",
                            'Contact' => $Contact,
                            'ApiUrl' => env('APP_URL'),
                            'ApiVersion' => env('APP_VERSION'),
                        ];
                        return response()->json($response);


                    }
                    else
                    {

                        $Contact = Contact::where('CustomerId', $CustomerId)->where('IsPrimary', '1')->get();
                        if ($Contact->count() > 0)
                        {
                            // $response = [
                            //     'Success' => false,
                            //     'ResponseMessage' => "Primary number already exist!",
                            //     'ResponseCode' => "209",
                            //     'ApiUrl' => env('APP_URL'),
                            //     'ApiVersion' => env('APP_VERSION'),
                            // ];
                            // return response()->json($response);
                            if($condata['IsPrimary'] == '1')
                            {
                                $datau =  array();
                                $datau['IsPrimary'] = '0';
                                $Contact_update = Contact::where('CustomerId',$CustomerId)->update($datau);
                                if($Contact_update)
                                {
                                }
                            }
                        }


                        $ContactT = Contact::where('CustomerId', $CustomerId)->get();
                        if ($ContactT->count() == 0)
                        {
                            $condata['IsPrimary'] = '1';
                        }

                        //get user data
                        $ContactId = $this->userLib->useridGenrator();
                        $condata['ContactId'] = $ContactId;
                        $condata['Status'] = '1';
                        $condata['AssignTo'] = $UserId;
                        $condata['Created_at'] = $CreatedDate;
                        $condata['Created_by'] = $request->header('UserId');
                        $condata['AssignTo'] = $request->header('UserId');
                        $condata['CustomerId'] =$CustomerId;
                        $Contact_insert = Contact::insert($condata);
                        if($Contact_insert)
                        {
                            // $Country = isset($condata['Country']) ? $condata['Country'] : '';
                            // $City = isset($condata['City']) ? $condata['City'] : '';
                            // $Created_by = isset($condata['Created_by']) ? $condata['Created_by'] : '';
                            // $Email = isset($condata['Email']) ? $condata['Email'] : '';
                            // $FirstName = isset($condata['FirstName']) ? $condata['FirstName'] : '';
                            // $LastName = isset($condata['LastName']) ? $condata['LastName'] : '';
                            // $Mobile = isset($condata['Mobile']) ? $condata['Mobile'] : '';
                            // $PostalCode = isset($condata['PostalCode']) ? $condata['PostalCode'] : '';
                            // $State = isset($condata['State']) ? $condata['State'] : '';
                            // $StreetAddress = isset($condata['StreetAddress']) ? $condata['StreetAddress'] : '';
                            // $Updated_by = isset($condata['Updated_by']) ? $condata['Updated_by'] : '';

                            // $ContactQuery = "insert into salesforce.Contact (Contact_ID__c,Country__c,MailingCity,Created_By__c,Email,FirstName,LastName,MobilePhone,MailingPostalCode,MailingState,MailingStreet,Updated_By__c,External_Account_Id__c) values ('$ContactId','$Country','$City','$Created_by','$Email','$FirstName','$LastName','$Mobile','$PostalCode','$State','$StreetAddress','$Updated_by','$CustomerId')";

                            // DB::connection('pgsql')->insert($ContactQuery);

                        }
                        else
                        {
                            // fail


                        }
                    }
                }
            }



            ///////////////////////////

            $data['Status'] = '1';
            $data['Updated_at'] = $CreatedDate;
            $data['Created_at'] = $CreatedDate;
            $data['AssignTo'] = $UserId;
            $data['Created_by'] = $UserId;
            $data['Updated_by'] = $UserId;
            unset($data['PriceBookName']);
            unset($data['Updated_at']);
            unset($data['Contact']);

            $customer_insert = Customer::insert($data);

            if($customer_insert)
            {
            //get user details
            $BillingAddress = isset($data['BillingAddress']) ? $data['BillingAddress'] : '';
            $BillingCity = isset($data['BillingCity']) ? $data['BillingCity'] : '';
            $BillingCountryId = isset($data['BillingCountry']) ? $data['BillingCountry'] : '';
            if($BillingCountryId){
                $country_details = Countries::select('tbl_countries.country_name')
                ->where('tbl_countries.id', $BillingCountryId)
                ->get()->first();
                $BillingCountry = $country_details->country_name;
            }
            $BillingPinCode = isset($data['BillingPinCode']) ? $data['BillingPinCode'] : '';
            $BillingState = isset($data['BillingState']) ? $data['BillingState'] : '';
            $ShippingAddress = isset($data['ShippingAddress']) ? $data['ShippingAddress'] : '';
            $ShippingCity = isset($data['ShippingCity']) ? $data['ShippingCity'] : '';
            $CountryId = isset($data['ShippingCountry']) ? $data['ShippingCountry'] : '';
            if($CountryId){
                $country_details = Countries::select('tbl_countries.country_name')
                ->where('tbl_countries.id', $CountryId)
                ->get()->first();
                $ShippingCountry = $country_details->country_name;
            }
            $ShippingPinCode = isset($data['ShippingPinCode']) ? $data['ShippingPinCode'] : '';
            $ShippingState = isset($data['ShippingState']) ? $data['ShippingState'] : '';
            $CustomerGST = isset($data['CustomerGST']) ? $data['CustomerGST'] : '';
            $CustomerNameSF = isset($data['CustomerName']) ? $data['CustomerName'] : '';
            $CustomerPAN = isset($data['CustomerPAN']) ? $data['CustomerPAN'] : '';
            $CustomerTypeId = isset($data['CustomerTypeId']) ? $data['CustomerTypeId'] : '';
            $Description = isset($data['Description']) ? $data['Description'] : '';
            $Email = isset($data['Email']) ? $data['Email'] : '';
            $IsDeleted = isset($data['IsDeleted']) ? $data['IsDeleted'] : '';
            $ParentCustomerId = isset($data['ParentCustomerId']) ? $data['ParentCustomerId'] : '';
            $PriceBookId = isset($data['PriceBookId']) ? $data['PriceBookId'] : '';
            $SalesArea = isset($data['SalesArea']) ? $data['SalesArea'] : '';
            $CustomerType = isset($data['Type']) ? $data['Type'] : '';
            $Created_by = isset($data['Created_by']) ? $data['Created_by'] : '';
            $Updated_by = isset($data['Updated_by']) ? $data['Updated_by'] : '';

            // $CustomerQuery = "insert into salesforce.Account (Name,Description,Email__c,BillingStreet,BillingCity,BillingCountry,BillingState,BillingPostalCode,Shipping_Address__c,Shipping_City__c,Shipping_Country__c,Shipping_PinCode__c,Shipping_State__c,Customer_GST__c,Customer_PAN__c,Customer_Type_Id__c,IsDeleted,parent_Customer_Id__c,Price_Book_Id__c,Sales_Area__c,Type__c,Created_By__c,Updated_By__c, Customer_Id__c, Customer_Code__c) values ('$CustomerNameSF','$Description','$Email','$BillingAddress','$BillingCity','$BillingCountry','$BillingState','$BillingPinCode','$ShippingAddress','$ShippingCity','$ShippingCountry','$ShippingPinCode','$ShippingState','$CustomerGST','$CustomerPAN','$CustomerTypeId','$IsDeleted','$ParentCustomerId','$PriceBookId','$SalesArea','$CustomerType','$Created_by','$Updated_by','$CustomerId', '$CustomerCode')";

            // $SF_customer_insert = DB::connection('pgsql')->insert($CustomerQuery);

            // $SF_customer_insert = $this->externalDataBase->createCustomer($CustomerId);

            // if($SF_customer_insert){

            //     $CountryPrimaryId = isset($condata['Country']) ? $condata['Country'] : '';
            //     if($CountryPrimaryId){
            //         $country_details = Countries::select('tbl_countries.country_name')
            //         ->where('tbl_countries.id', $CountryPrimaryId)
            //         ->get()->first();
            //         $Country = $country_details->country_name;
            //     }
            //     $City = isset($condata['City']) ? $condata['City'] : '';
            //     $Created_by = isset($condata['Created_by']) ? $condata['Created_by'] : '';
            //     $Email = isset($condata['Email']) ? $condata['Email'] : '';
            //     $FirstName = isset($condata['FirstName']) ? $condata['FirstName'] : '';
            //     $LastName = isset($condata['LastName']) ? $condata['LastName'] : '';
            //     $Mobile = isset($condata['Mobile']) ? $condata['Mobile'] : '';
            //     $PostalCode = isset($condata['PostalCode']) ? $condata['PostalCode'] : '';
            //     $State = isset($condata['State']) ? $condata['State'] : '';
            //     $StreetAddress = isset($condata['StreetAddress']) ? $condata['StreetAddress'] : '';
            //     $Updated_by = isset($condata['Updated_by']) ? $condata['Updated_by'] : '';

            //     $ContactQuery = "insert into salesforce.Contact (Contact_ID__c,Country__c,MailingCity,Created_By__c,Email,FirstName,LastName,MobilePhone,MailingPostalCode,MailingState,MailingStreet,Updated_By__c,External_Account_Id__c) values ('$ContactId','$Country','$City','$Created_by','$Email','$FirstName','$LastName','$Mobile','$PostalCode','$State','$StreetAddress','$Updated_by','$CustomerId')";

            //     DB::connection('pgsql')->insert($ContactQuery);
            // }

            $custmer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_beat_plan.BeatPlanName', 'tbl_sales_area.Name as SalesAreaName', 'tbl_customer_type.Name as CustomerType', 'tbl_user.FirstName as UpdatedByName', 'tbl_user.FirstName as CreatedByName')
            ->leftJoin('tbl_user', 'tbl_customer.Created_by', '=', 'tbl_user.UserId')
            //->leftJoin('tbl_customer', 'tbl_customer.ParentCustomer', '=', 'tbl_customer.id')
            ->leftJoin('tbl_customer_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_beat_plan', 'tbl_customer.BeatPlan', '=', 'tbl_beat_plan.BeatPlanId')
            ->leftJoin('tbl_sales_area', 'tbl_customer.SalesArea', '=', 'tbl_sales_area.SalesAreaId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->where('tbl_customer.CustomerId', $data['CustomerId'])
            ->orderBy('tbl_customer.id', 'desc')
            ->get()->first();

            $Contact = Contact::where('CustomerId', $data['CustomerId'])->get();
            $custmer->Contact =  $Contact;

                $response = [
                    'Success' => true,
                    'ResponseMessage' => "Customer has been registered",
                    'ResponseCode' => "200",
                    'CustomerId' => $CustomerId,
                    'Customer' => $custmer,
                    'ApiUrl' => env('APP_URL'),
                    'ApiVersion' => env('APP_VERSION'),
                    // 'CustomerQuery' => $CustomerQuery
                ];
                return response()->json($response);
            }
            else
            {
                // fail
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "Invalid data",
                    'ResponseCode' => "202",
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }
        }
    }


    //User create first time password
    public function updateCustomer(Request $request) {
		//TODO What is device_token
        $data = $request->json()->all();

        $OtpPassword = $this->userLib->otpGenrator();

        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        $tblData = array();

        $CreatedDate = date('Y-m-d H:i:s',time());

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        //IsDeleted
        $IsDeleted = isset($data['IsDeleted']) ? $data['IsDeleted'] : '';
        if($IsDeleted == '1')
        {

            //ParentCustomerId
            $Customer = Customer::where('ParentCustomerId', $data['CustomerId'])->where('Status', '1')->where('IsDeleted', '0')->get();
            if ($Customer->count() > 0)
            {   //customer not exist
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "The customer can not be deleted, You need to delete child customer first!",
                    'ResponseCode' => '205',
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }


            //order
            $Order = Order::where('CustomerId', $data['CustomerId'])->where('Status', '1')->where('IsDeleted', '0')->get();
            if ($Order->count() > 0)
            {   //customer not exist
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "The customer can not be deleted, You need to delete order first!",
                    'ResponseCode' => '205',
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }

            //BeatPlan
            $BeatPlan = BeatPlan::where('CustomerId', $data['CustomerId'])->where('Status', '1')->where('IsDeleted', '0')->get();
            if ($BeatPlan->count() > 0)
            {   //customer not exist
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "The customer can not be deleted, You need to delete beatplan first!",
                    'ResponseCode' => '206',
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }



            //Collection
            $Collection = Collection::where('CustomerId', $data['CustomerId'])->where('Status', '1')->where('IsDeleted', '0')->get();
            if ($Collection->count() > 0)
            {   //customer not exist
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "The customer can not be deleted, You need to delete collection first!",
                    'ResponseCode' => '206',
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }

             //Visits
             $Visits = Visits::where('CustomerId', $data['CustomerId'])->where('Status', '1')->where('IsDeleted', '0')->get();
             if ($Visits->count() > 0)
             {   //customer not exist
                 $response = [
                     'Success' => false,
                     'ResponseMessage' => "The customer can not be deleted, You need to delete visit first!",
                     'ResponseCode' => '206',
                     'ApiVersion' => env('APP_VERSION'),
                 ];
                 return response()->json($response);
             }
        }

		unset($data['PriceBookName']);
        unset($data['Created_at']);
        //Check Memeber is exist or not
        $user = Customer::where('CustomerId', $data['CustomerId'])->get();
        if ($user->count() == 0)
        {   //customer not exist
            $response = [
                'Success' => false,
                'ResponseMessage' => "The customer does not exist!",
                'ResponseCode' => '201',
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        //update customer
        $CustomerId = $data['CustomerId'];
        unset($data['CustomerId']);
        unset($data['Mobile']);
        unset($data['Contact']);
        $data['Updated_at'] = $CreatedDate;

      //  return response()->json($data);

        $customer_update = Customer::where('CustomerId',$CustomerId)->update($data);
        if($customer_update)
        {
            $BillingAddress = isset($data['BillingAddress']) ? $data['BillingAddress'] : '';
            $BillingCity = isset($data['BillingCity']) ? $data['BillingCity'] : '';
            // $BillingCountry = isset($data['BillingCountry']) ? $data['BillingCountry'] : '';
            $BillingCountryId = isset($data['BillingCountry']) ? $data['BillingCountry'] : '';
            if($BillingCountryId){
                $country_details = Countries::select('tbl_countries.country_name')
                ->where('tbl_countries.id', $BillingCountryId)
                ->get()->first();
                $BillingCountry = $country_details->country_name;
            }
            $BillingPinCode = isset($data['BillingPinCode']) ? $data['BillingPinCode'] : '';
            $BillingState = isset($data['BillingState']) ? $data['BillingState'] : '';
            $ShippingAddress = isset($data['ShippingAddress']) ? $data['ShippingAddress'] : '';
            $ShippingCity = isset($data['ShippingCity']) ? $data['ShippingCity'] : '';
            // $ShippingCountry = isset($data['ShippingCountry']) ? $data['ShippingCountry'] : '';
            $CountryId = isset($data['ShippingCountry']) ? $data['ShippingCountry'] : '';
            if($CountryId){
                $country_details = Countries::select('tbl_countries.country_name')
                ->where('tbl_countries.id', $CountryId)
                ->get()->first();
                $ShippingCountry = $country_details->country_name;
            }
            $ShippingPinCode = isset($data['ShippingPinCode']) ? $data['ShippingPinCode'] : '';
            $ShippingState = isset($data['ShippingState']) ? $data['ShippingState'] : '';
            $CustomerGST = isset($data['CustomerGST']) ? $data['CustomerGST'] : '';
            $CustomerNameSF = isset($data['CustomerName']) ? $data['CustomerName'] : '';
            $CustomerPAN = isset($data['CustomerPAN']) ? $data['CustomerPAN'] : '';
            $CustomerTypeId = isset($data['CustomerTypeId']) ? $data['CustomerTypeId'] : '';
            $Description = isset($data['Description']) ? $data['Description'] : '';
            $Email = isset($data['Email']) ? $data['Email'] : '';
            $IsDeleted = isset($data['IsDeleted']) ? $data['IsDeleted'] : '';
            $ParentCustomerId = isset($data['ParentCustomerId']) ? $data['ParentCustomerId'] : '';
            $PriceBookId = isset($data['PriceBookId']) ? $data['PriceBookId'] : '';
            $SalesArea = isset($data['SalesArea']) ? $data['SalesArea'] : '';
            $CustomerType = isset($data['Type']) ? $data['Type'] : '';
            $Updated_by = isset($UserId) ? $UserId : '';


            // $CustomerQuery = "update salesforce.Account set Name='$CustomerNameSF',Description='$Description',Email__c='$Email',BillingStreet='$BillingAddress',BillingCity='$BillingCity',BillingCountry='$BillingCountry',BillingState='$BillingState',BillingPostalCode='$BillingPinCode',Shipping_Address__c='$ShippingAddress',Shipping_City__c='$ShippingCity',Shipping_Country__c='$ShippingCountry',Shipping_PinCode__c='$ShippingPinCode',Shipping_State__c='$ShippingState',Customer_GST__c='$CustomerGST',Customer_PAN__c='$CustomerPAN',Customer_Type_Id__c='$CustomerTypeId',IsDeleted='$IsDeleted',parent_Customer_Id__c='$ParentCustomerId',Price_Book_Id__c='$PriceBookId',Sales_Area__c='$SalesArea',Type__c='$CustomerType', Updated_By__c='$Updated_by' where customer_id__c = '$CustomerId'";

            // DB::connection('pgsql')->update($CustomerQuery);

            $custmer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_beat_plan.BeatPlanName', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_sales_area.Name as SalesAreaName', 'tbl_customer_type.Name as CustomerType', 'tbl_user.FirstName as UpdatedByName', 'tbl_user.FirstName as CreatedByName')
            ->leftJoin('tbl_user', 'tbl_customer.Created_by', '=', 'tbl_user.UserId')
            //->leftJoin('tbl_customer', 'tbl_customer.ParentCustomer', '=', 'tbl_customer.id')
            ->leftJoin('tbl_customer_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_beat_plan', 'tbl_customer.BeatPlan', '=', 'tbl_beat_plan.BeatPlanId')
            ->leftJoin('tbl_sales_area', 'tbl_customer.SalesArea', '=', 'tbl_sales_area.SalesAreaId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->where('tbl_customer.CustomerId', $CustomerId)
            ->orderBy('tbl_customer.id', 'desc')
            ->get()->first();
            // success
            $response = [
                'Success' => true,
                'ResponseMessage' => "Success",
                'ResponseCode' => "200",
                'CustomerId' => $CustomerId,
                'AuthToken' => $AuthToken,
                'Customer' => $custmer,
                'ApiUrl' => env('APP_URL'),
                'ApiVersion' => env('APP_VERSION'),
                // 'CustomerQuery'=>$CustomerQuery
            ];
        }
        else
        {
            // fail
            $response = [
                'Success' => false,
                'ResponseMessage' => "Invalid Auth",
                'ResponseCode' => "203",
                'ApiVersion' => env('APP_VERSION'),
            ];
        }
            return response()->json($response);
    }


    //edit profile picture

    //User edit profile
    public function editCustomerProfileImage(Request $request) {
		//TODO What is device_token
       // $data = $request->json()->all();


        $CreatedDate = date('Y-m-d H:i:s',time());

        $CustomerId = $request->input('CustomerId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        // $imageName = $this->userLib->useridGenrator();
        // if ($request->hasFile('CustomerProfileImage'))
        // {
        //     $path = '';
        //     $file = $request->file('CustomerProfileImage');
        //     $extension = $file->getClientOriginalExtension();
        //     $newFileName = $imageName . '-' . time() . '.' . $extension;

        //     Storage::putFileAs(
        //         'public/customer',
        //         $file,
        //         $newFileName
        //     );
        //     $destinationPath = 'customer';
        //     $isUploaded = $file->move($destinationPath,$newFileName);

        //     if($isUploaded)
        //     {
        //         $path = 'customer/' . $newFileName;
        //         $ThumbnailUrl = $path;
        //     }
        //     $data['CustomerProfileImage'] = $ThumbnailUrl;
        $imageName = $this->userLib->useridGenrator();
        if ($request->hasFile('CustomerProfileImage'))
        {
            $path = '';
            $file = $request->file('CustomerProfileImage');
            $extension = $file->getClientOriginalExtension();
            $newFileName = $imageName . '-' . time() . '.' . $extension;

            Storage::putFileAs(
                'public/customer/',
                $file,
                $newFileName
            );
            $destinationPath = 'customer/';
            $isUploaded = $file->move($destinationPath,$newFileName);

            $uploadedFileURL = '';
            if($isUploaded)
            {
                $path = 'customer/' . $newFileName;
                $ThumbnailUrl = $path;
            //File Upload Service as s3
            $sourceFileURL = env('APP_URL').'/'.$path;
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://172.105.42.62/s3-file-server/api-upload.php',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array('file_url' => $sourceFileURL),
            CURLOPT_HTTPHEADER => array(
                'Cookie: private_content_version=3f7abce738dd8b52d0dcb8653bfe8e93; mage-messages=%5B%7B%22type%22%3A%22error%22%2C%22text%22%3A%22Invalid%20Form%20Key.%20Please%20refresh%20the%20page.%22%7D%2C%7B%22type%22%3A%22error%22%2C%22text%22%3A%22Invalid%20Form%20Key.%20Please%20refresh%20the%20page.%22%7D%2C%7B%22type%22%3A%22error%22%2C%22text%22%3A%22Invalid%20Form%20Key.%20Please%20refresh%20the%20page.%22%7D%5D'
            ),
            ));
            $response = curl_exec($curl);
            curl_close($curl);
            $uploadedFile = json_decode($response,true);
            $uploadedFileURL = isset($uploadedFile['url']) ? $uploadedFile['url'] : '';
            }
            $data['CustomerProfileImage'] = $uploadedFileURL;

            $data['Updated_by'] = session('UserId');;
            $data['Updated_at'] = $CreatedDate;

            $customer_update = Customer::where('CustomerId',$CustomerId)->update($data);

            if($customer_update)
            {

                $customer_details = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_beat_plan.BeatPlanName', 'tbl_sales_area.Name as SalesAreaName', 'tbl_customer_type.Name as CustomerType', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_customer.Created_by', '=', 'tbl_admin.UserId')
            //->leftJoin('tbl_customer', 'tbl_customer.ParentCustomer', '=', 'tbl_customer.id')
            ->leftJoin('tbl_customer_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_beat_plan', 'tbl_customer.BeatPlan', '=', 'tbl_beat_plan.BeatPlanId')
            ->leftJoin('tbl_sales_area', 'tbl_customer.SalesArea', '=', 'tbl_sales_area.SalesAreaId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->where('tbl_customer.CustomerId', $CustomerId)
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

                $customer_data = $customer_details->first();

                $customer_data->ParentCustomerName = '';
                if($customer_data->ParentCustomerId)
                {
                    $ParentCustomer = Customer::select('CustomerName')
                    ->where('CustomerId', $customer_data->ParentCustomerId)
                    ->orderBy('tbl_customer.id', 'desc')
                    ->get()->first();
                    $customer_data->ParentCustomerName = $ParentCustomer->CustomerName;
                }

                $response = [
                    'success' => false,
                    'ResponseMessage' => "Success",
                    'ResponseCode' => "200",
                    'ApiVersion' => env('APP_VERSION'),
                    'ApiUrl' => env('APP_URL'),
                    'Customer'=>$customer_data,

                ];
                return response()->json($response);
            }
            else
            {
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "Invalid data",
                    'ResponseCode' => "202",
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }
        }

    }

    //end of edit profile



    //User edit profile
    public function editCustomerProfile(Request $request) {
		//TODO What is device_token
        $data = $request->json()->all();
        $OtpPassword = $this->userLib->otpGenrator();
        $tblData = array();
        $CreatedDate = date('Y-m-d H:i:s',time());

        $CustomerId = $request->header('CustomerId');
        $AuthToken = $request->header('AuthToken');




        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

		$validator = Validator::make($data, [
			'Mobile' => 'required|string|max:255',

        ]);
        //check validation
        if ($validator->fails())
        {
            $response = [
                'Success' => false,
                'ResponseMessage' => "Mobile is required!",
                'ResponseCode' => '220',
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        //Check Memeber is exist or not
        $user = Customer::where('Mobile', $data['Mobile'])->get();
        if ($user->count() > 0)
        {   //email is exist
            $user = $user->first();


            $data['ModifiedDate'] = $CreatedDate;

            unset($data['TempPassword']);
            unset($data['OtpPassword']);

            $customer_update = DB::table('tbl_customer')->where('CustomerId',$CustomerId)->update($data);
            if($customer_update)
            {


                $customer_details = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_beat_plan.BeatPlanName', 'tbl_sales_area.Name as SalesAreaName', 'tbl_customer_type.Name as CustomerType', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
                ->leftJoin('tbl_admin', 'tbl_customer.Created_by', '=', 'tbl_admin.UserId')
                //->leftJoin('tbl_customer', 'tbl_customer.ParentCustomer', '=', 'tbl_customer.id')
                ->leftJoin('tbl_customer_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
                ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
                ->leftJoin('tbl_beat_plan', 'tbl_customer.BeatPlan', '=', 'tbl_beat_plan.BeatPlanId')
                ->leftJoin('tbl_sales_area', 'tbl_customer.SalesArea', '=', 'tbl_sales_area.SalesAreaId')
                ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
                ->where('tbl_customer.IsDeleted', '=', '0')
                ->where('tbl_customer.Mobile', $data['Mobile'])
                ->orderBy('tbl_customer.id', 'desc')
                ->get();

                $customer_data = $customer_details->first();

                $customer_data->ParentCustomerName = '';
                if($customer_data->ParentCustomerId)
                {
                    $ParentCustomer = Customer::select('CustomerName')
                    ->where('CustomerId', $customer_data->ParentCustomerId)
                    ->orderBy('tbl_customer.id', 'desc')
                    ->get()->first();
                    $customer_data->ParentCustomerName = $ParentCustomer->CustomerName;
                }

                unset($customer_data->Password);
                unset($customer_data->ResetKey);
                //create auth token
                $response = [
                    'Success' => true,
                    'ResponseMessage' => "Success",
                    'ResponseCode' => "200",
                    'CustomerId' => $CustomerId,
                    'AuthToken' => $AuthToken,

                    'Customer' => $customer_data,
                    'ApiUrl' => env('APP_URL'),
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }
            else
            {
                // fail
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "Invalid data",
                    'ResponseCode' => "202",
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }
        }
        else
        {
            // fail
            $response = [
                'Success' => false,
                'ResponseMessage' => "User not exist",
                'ResponseCode' => "201",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);

        }
    }



    //User get profile
    public function getCustomerProfile(Request $request, $CustomerId) {
		//TODO What is device_token
        $data = $request->json()->all();
        $tblData = array();


        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }


        //check validation
        if (!$CustomerId)
        {
            $response = [
                'Success' => false,
                'ResponseMessage' => "Customer is required!",
                'ResponseCode' => '220',
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        //Check Memeber is exist or not

        $Customer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName',  'tbl_beat_plan.BeatPlanName', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_sales_area.Name as SalesAreaName', 'tbl_customer_type.Name as CustomerType', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_customer.Created_by', '=', 'tbl_admin.UserId')
            //->leftJoin('tbl_customer', 'tbl_customer.ParentCustomer', '=', 'tbl_customer.id')
            ->leftJoin('tbl_customer_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_beat_plan', 'tbl_customer.BeatPlan', '=', 'tbl_beat_plan.BeatPlanId')
            ->leftJoin('tbl_sales_area', 'tbl_customer.SalesArea', '=', 'tbl_sales_area.SalesAreaId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->where('tbl_customer.CustomerId', $CustomerId)
            ->orderBy('tbl_customer.id', 'desc')
            ->get();


        if ($Customer->count() > 0)
        {   //email is exist
            $Customer = $Customer->first();

            $Customer->ParentCustomerName = '';
            if($Customer->ParentCustomerId)
            {
                $ParentCustomer = Customer::select('CustomerName')
                ->where('CustomerId', $Customer->ParentCustomerId)
                ->orderBy('tbl_customer.id', 'desc')
                ->get()->first();
                $Customer->ParentCustomerName = $ParentCustomer->CustomerName;
            }

            $Customer->DistributorName = '';
            if($Customer->DistributorId)
            {
                $Distributor = Customer::select('CustomerName')
                ->where('CustomerId', $Customer->DistributorId)
                ->orderBy('id', 'desc')
                ->get()->first();
                $Customer->DistributorName = $Distributor->CustomerName;
            }


            $Customer->WholeSellerName = '';
            if($Customer->WholeSellerId)
            {
                $Distributor = Customer::select('CustomerName')
                ->where('CustomerId', $Customer->WholeSellerId)
                ->orderBy('id', 'desc')
                ->get()->first();
                $Customer->WholeSellerName = $Distributor->CustomerName;
            }


            $Customer->ShippingCountryName = '';
            if($Customer->ShippingCountry)
            {
                $countries = Countries::select('country_name')
                ->where('id', $Customer->ShippingCountry)
                ->get()->first();
                $Customer->ShippingCountryName = $countries->country_name;
            }


            $Customer->BillingCountryName = '';
            if($Customer->BillingCountry)
            {
                $countries = Countries::select('country_name')
                ->where('id', $Customer->BillingCountry)
                ->get()->first();
                $Customer->BillingCountryName = $countries->country_name;
            }


            unset($Customer->Password);
            unset($Customer->ResetKey);
            unset($Customer->TempPassword);
            unset($Customer->OtpPassword);

            $CustomerId = $request->header('CustomerId');
            $AuthToken = $request->header('AuthToken');
            $response = [
                'Success' => true,
                'ResponseMessage' => "Success",
                'ResponseCode' => "200",
                'CustomerId' => $CustomerId,
                'AuthToken' => $AuthToken,
                'Customer' => $Customer,
                'ApiUrl' => env('APP_URL'),
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }
        else
        {
            // fail
            $response = [
                'Success' => false,
                'ResponseMessage' => "Customer does not exist",
                'ResponseCode' => "201",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);

        }
    }

    ## Customer Visits

    public function getCustomerVisitList(Request $request, $CustomerId='') {
        $data = $request->json()->all();

        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        if(!$CustomerId)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "CustomerId empty",
                'ResponseCode' => "303",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $Visits = Visits::select('*')
        ->where('CustomerId', '=', $CustomerId)
        ->where('AssignTo', '=', $CustomerId)
        ->where('Status', '=', '1')
        ->where('IsDeleted', '=', 0)
        ->orderBy('id', 'DESC')
        ->get();



        if ($Visits->count() > 0)
        {
            if ($Visits->count() > 0)
            {
                foreach ($Visits as $key => $BPValue)
                {
                    //Distributer


                    $CreatedFormatedDate = $BPValue->Created_at;
                    $CreatedFormatedDate = date("j M Y",strtotime($CreatedFormatedDate));
                    $BPValue->CreatedFormatedDate = $CreatedFormatedDate;


                    //BeatPlanId
                    $BeatPlanId = $BPValue->BeatPlanId;
                    $BeatPlanName = '';
                    $BeatPlan = BeatPlan::where('BeatPlanId', $BeatPlanId)->get();
                    if ($BeatPlan->count() > 0)
                    {   //email is not exist

                        $BeatPlanData = $BeatPlan->first();
                        $BeatPlanName = $BeatPlanData->BeatPlanName;
                    }
                    $BPValue['BeatPlanName'] = $BeatPlanName;

                    //SalesAreaName
                    $SalesAreaId = $BPValue->SalesAreaId;
                    $SalesAreaName = '';
                    $SalesArea = SalesArea::where('SalesAreaId', $SalesAreaId)->get();
                    if ($SalesArea->count() > 0)
                    {   //email is not exist

                        $SalesAreaData = $SalesArea->first();
                        $SalesAreaName = $SalesAreaData->Name;
                    }
                    $BPValue['SalesAreaName'] = $SalesAreaName;


                    //Get Customer Name
                    $CustomerName = '';
                    $CustomerId = $BPValue->CustomerId;

                    //  $CustomerId_arr = explode (",", $CustomerId);

                    //  $cid = '';
                    //  $CustomerNames = '';
                    // if(count($CustomerId_arr) > 0)
                    // {
                    //     for($p = 0; $p < count($CustomerId_arr); $p++)
                    //     {
                    //         $CustomerId = $CustomerId_arr[$p];
                    //         $Customers = Customer::where('CustomerId', $CustomerId)->get();
                    //         if ($Customers->count() > 0)
                    //         {   //email is not exist

                    //             $CustomerData = $Customers->first();
                    //             $CustomerName = $CustomerData->CustomerName;
                    //             $CustomerNames .= $CustomerName.', ';
                    //         }
                    //     }
                    // }
                    // $CustomerNames = rtrim($CustomerNames, ', ');


                    $Customers = Customer::where('CustomerId', $CustomerId)->get();
                    if ($Customers->count() > 0)
                    {   //email is not exist

                        $CustomerData = $Customers->first();
                        $CustomerName = $CustomerData->CustomerName;
                    // $CustomerNames .= $CustomerName.', ';
                    }
                    $BPValue['CustomerName'] = $CustomerName;
                }
            }



            $response = [
                'Success' => true,
                'ResponseMessage' => "Success",
                'ResponseCode' => "200",
                'UserId' => $UserId,
                'AuthToken' => $AuthToken,
                'VisitList' => $Visits,
                'ApiUrl' => env('APP_URL'),
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }
        else
        {
            // fail
            $response = [
                'Success' => false,
                'ResponseMessage' => "visit does not exist",
                'ResponseCode' => "201",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }
    }
    ## End of Customer visits


    ### All Customer
    public function getCustomerList(Request $request, $CustomerTypeId =''){


        $data = $request->json()->all();

        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }



        if($CustomerTypeId)
        {
            $Customers = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_user.FirstName as Updated_by_name', 'tbl_user.FirstName as Created_by_name')
            ->leftJoin('tbl_user', 'tbl_customer.Created_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->where('tbl_customer.Status', '=', '1')
            ->where('tbl_customer.CustomerTypeId', '=', $CustomerTypeId)
            ->where('tbl_customer.AssignTo',$UserId)
            ->get();
        }
        else
        {
            $Customers = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_user.FirstName as Updated_by_name', 'tbl_user.FirstName as Created_by_name')
            ->leftJoin('tbl_user', 'tbl_customer.Created_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->where('tbl_customer.Status', '=', '1')
            ->where('tbl_customer.AssignTo',$UserId)
            ->get();
        }



        foreach ($Customers as $key => $CustomerValue)
        {
            $ParentCustomerId = $CustomerValue->ParentCustomerId;
            $CustomerId = $CustomerValue->CustomerId;


            $CreatedFormatedDate = $CustomerValue->Created_at;
            $CreatedFormatedDate = date("j M Y",strtotime($CreatedFormatedDate));
            $CustomerValue->CreatedFormatedDate = $CreatedFormatedDate;


            $CustomerName = '';
            $custmer = Customer::select('CustomerName')->where('CustomerId', $ParentCustomerId)->get();
            if ($custmer->count() > 0)
            {   //email is  exist
                $custmer = $custmer->first();
                $CustomerName = $custmer->CustomerName;
            }

            $CustomerValue['ParentCustomerName'] = $CustomerName;

            $CustomerValue['Contacts'] = array();
            $ContactT = Contact::where('CustomerId', $CustomerId)->get();
            if ($ContactT->count() > 0)
            {
                $CustomerValue['Contacts'] =  $ContactT;
            }


        }

        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,

            'Customers' => $Customers,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);


    }



     ### All Customer of today
     public function getCustomerListToday(Request $request, $filter =''){


        $data = $request->json()->all();

        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $today = date('Y-m-d',time());


    //DB::enableQueryLog();
    if(strtoupper($filter)==strtoupper('Today'))
    {
        $Customers = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_user.FirstName as Updated_by_name', 'tbl_user.FirstName as Created_by_name')
        ->leftJoin('tbl_user', 'tbl_customer.Created_by', '=', 'tbl_user.UserId')
        ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
        ->where('tbl_customer.IsDeleted', '=', '0')
        ->where('tbl_customer.Status', '=', '1')
        ->where('tbl_customer.Created_at', 'like', '%'.$today.'%')
        ->where('tbl_customer.AssignTo',$UserId)
        ->get();
    }
    else if(strtoupper($filter)==strtoupper('UpComing'))
    {


        $Customers = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_user.FirstName as Updated_by_name', 'tbl_user.FirstName as Created_by_name')
        ->leftJoin('tbl_user', 'tbl_customer.Created_by', '=', 'tbl_user.UserId')
        ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
        ->where('tbl_customer.IsDeleted', '=', '0')
        ->where('tbl_customer.Status', '=', '1')
        ->where('tbl_customer.Created_at', '>', $today)
        ->where('tbl_customer.AssignTo',$UserId)
        ->get();
    }
    else if(strtoupper($filter)==strtoupper('Past'))
    {


        $Customers = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_user.FirstName as Updated_by_name', 'tbl_user.FirstName as Created_by_name')
        ->leftJoin('tbl_user', 'tbl_customer.Created_by', '=', 'tbl_user.UserId')
        ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
        ->where('tbl_customer.IsDeleted', '=', '0')
        ->where('tbl_customer.Status', '=', '1')
        ->where('tbl_customer.Created_at', '<', $today)
        ->where('tbl_customer.AssignTo',$UserId)
        ->get();
    }
    else
    {
        $Customers = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_user.FirstName as Updated_by_name', 'tbl_user.FirstName as Created_by_name')
        ->leftJoin('tbl_user', 'tbl_customer.Created_by', '=', 'tbl_user.UserId')
        ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
        ->where('tbl_customer.IsDeleted', '=', '0')
        ->where('tbl_customer.Status', '=', '1')
        ->where('tbl_customer.AssignTo',$UserId)
        ->get();
    }




        foreach ($Customers as $key => $CustomerValue)
        {
            $ParentCustomerId = $CustomerValue->ParentCustomerId;
            $CustomerId = $CustomerValue->CustomerId;


            $CreatedFormatedDate = $CustomerValue->Created_at;
            $CreatedFormatedDate = date("j M Y",strtotime($CreatedFormatedDate));
            $CustomerValue->CreatedFormatedDate = $CreatedFormatedDate;


            $CustomerName = '';
            $custmer = Customer::select('CustomerName')->where('CustomerId', $ParentCustomerId)->get();
            if ($custmer->count() > 0)
            {   //email is  exist
                $custmer = $custmer->first();
                $CustomerName = $custmer->CustomerName;
            }

            $CustomerValue['ParentCustomerName'] = $CustomerName;

            $CustomerValue['Contacts'] = array();
            $ContactT = Contact::where('CustomerId', $CustomerId)->get();
            if ($ContactT->count() > 0)
            {
                $CustomerValue['Contacts'] =  $ContactT;
            }


        }

        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,

            'Customers' => $Customers,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);


    }




    //Team List
    public function getTeamCustomerList(Request $request, $CustomerTypeId =''){


        $data = $request->json()->all();

        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $TeamList = $this->APICommonController->getManagerTeamList($UserId);

       //  DB::enableQueryLog(); // Enable query log
            $Customers = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_user.FirstName as Updated_by_name', 'tbl_user.FirstName as Created_by_name')
            ->leftJoin('tbl_user', 'tbl_customer.Created_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->where('tbl_customer.Status', '=', '1')
            ->whereIn('tbl_customer.AssignTo',$TeamList)
            ->orderBy('CustomerName', 'asc')
            //->orderBy('id', 'desc')
            ->get();

       // dd(DB::getQueryLog()); // Show results of log

        foreach ($Customers as $key => $CustomerValue)
        {
            $ParentCustomerId = $CustomerValue->ParentCustomerId;
            $CustomerId = $CustomerValue->CustomerId;
            $CreatedFormatedDate = $CustomerValue->Created_at;
            $CreatedFormatedDate = date("j M Y",strtotime($CreatedFormatedDate));
            $CustomerValue->CreatedFormatedDate = $CreatedFormatedDate;
            $CustomerName = '';
            $custmer = Customer::select('CustomerName')->where('CustomerId', $ParentCustomerId)->get();
            if ($custmer->count() > 0)
            {   //email is  exist
                $custmer = $custmer->first();
                $CustomerName = $custmer->CustomerName;
            }
            $CustomerValue['ParentCustomerName'] = $CustomerName;
            $CustomerValue['Contacts'] = array();
            $ContactT = Contact::where('CustomerId', $CustomerId)->get();
            if ($ContactT->count() > 0)
            {
                $CustomerValue['Contacts'] =  $ContactT;
            }
        }
        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,

            'Customers' => $Customers,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);
    }


    ### All Customer
    public function getDepartmentList(Request $request){


        $data = $request->json()->all();

        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $Departments = Departments::select('*')->get();
        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,
            'Departments' => $Departments,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);


    }


    ### All CustomerType
    public function getCustomerTypeList(Request $request){


        $data = $request->json()->all();

        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $CustomerType = CustomerType::select('*')
        ->where('Status', '=', '1')
        ->where('IsDeleted', '=', '0')
        ->get();
        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,
            'CustomerTypes' => $CustomerType,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);


    }




     ### All Customer
     public function getSalesAreaList(Request $request){


        $data = $request->json()->all();

        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $SalesArea = SalesArea::select('tbl_sales_area.*', 'tbl_sales_territory.Name as SalesTerritoryName')
        ->leftJoin('tbl_sales_territory', 'tbl_sales_area.SalesTerritory', '=', 'tbl_sales_territory.id')
        ->where('tbl_sales_area.IsDeleted', '=', '0')
        ->where('tbl_sales_area.Status', '=', '1')
        ->get();
        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,

            'SalesArea' => $SalesArea,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);


    }




    ### All Pricebook
    public function getPriceBookList(Request $request){


        $data = $request->json()->all();

        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $PriceBook = PriceBook::select('*')
        ->where('IsDeleted', '=', '0')
        ->where('Status', '=', '1')
        ->get();
        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,

            'PriceBooks' => $PriceBook,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);


    }


    ### All Pricebook
    public function getBeatPlanList(Request $request){
        $data = $request->json()->all();
        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');
        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }
        $BeatPlan = BeatPlan::select('*')
        ->where('IsDeleted', '=', '0')
        ->where('Status', '=', '1')
        ->get();
        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,
            'BeatPlan' => $BeatPlan,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);
    }



    ### All Pricebook
    public function getPaymentTearmList(Request $request){
        $data = $request->json()->all();
        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');
        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }
        $PaymentTerm = PaymentTerm::select('*')
        ->where('IsDeleted', '=', '0')
        ->where('Status', '=', '1')
        ->get();
        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,
            'PaymentTerms' => $PaymentTerm,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);
    }



    ### All Pricebook
    public function getDistributorList(Request $request, $CustomerTypeId = ''){
        $data = $request->json()->all();
        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');
        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }


        $keyname = '';
        if($CustomerTypeId == '7zbZseyyTqvA6n7n5Bk01RvCm30KpPQa8M8k7') //Retailer
        {
            $CustomerTypeId = '4zZVseyyTqvA6n7n5Bk01RvCm30KpPQa8M8k2'; //Distributor
            $keyname = "Distributor";
        }
        else if($CustomerTypeId == '4zZVseyyTqvA6n7n5Bk01RvCm30KpPQa8M8k2') //Distributor
        {
            $CustomerTypeId = 'ozbVseyyTqvA6n7n5Bk01RvCm40KpPQa8M8k3';//Whole Seller
            $keyname = "WholeSeller";
        }
        else if($CustomerTypeId == 'ozbVseyyTqvA6n7n5Bk01RvCm40KpPQa8M8k3') //Whole Seller
        {
            $CustomerTypeId = '';
            $keyname = '';

        }


        $Distributor = Customer::select('CustomerId', 'CustomerCode', 'CustomerName', 'Type', 'CustomerTypeId', 'Status', 'IsDeleted', 'Created_at')
            ->where('CustomerTypeId', $CustomerTypeId)
            ->where('AssignTo', $UserId)
            ->where('IsDeleted', '=', '0')
        ->where('Status', '=', '1')
            ->orderBy('id', 'desc')

            ->get();


            if($Distributor->count() > 0)
            {
                $response = [
                    'Success' => true,
                    'ResponseMessage' => "Success",
                    'ResponseCode' => "200",
                    'AuthToken' => $AuthToken,
                    $keyname => $Distributor,
                    'ApiUrl' => env('APP_URL'),
                    'ApiVersion' => env('APP_VERSION'),
                ];
            }
            else
            {
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "Data not found",
                    'ResponseCode' => "201",
                    'ApiUrl' => env('APP_URL'),
                    'ApiVersion' => env('APP_VERSION'),
                ];
            }
        return response()->json($response);
    }


    //Contact

    //Create customer contact
    public function createCustomerContact(Request $request) {
		//TODO What is device_token
        $data = $request->json()->all();

        $ContactId = $this->userLib->useridGenrator();
        $tblData = array();
        $CreatedDate = date('Y-m-d H:i:s',time());
		$validator = Validator::make($data, [
			'Mobile' => 'required|string|max:255',
        ]);
        //check validation
        if ($validator->fails())
        {
            $response = [
                'Success' => false,
                'ResponseMessage' => "Mobile is required!",
                'ResponseCode' => '220',
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $CustomerId = $data['CustomerId'];
        //Check Memeber is exist or not
        $Contact = Contact::where('Mobile', $data['Mobile'])->get();
        if ($Contact->count() > 0)
        {   //email is not exist

            $custmer = $Contact->first();
            $response = [
                'Success' => false,
                'ResponseMessage' => "Contact already exist!",
                'ResponseCode' => "201",
                'Contact' => $Contact,
                'ApiUrl' => env('APP_URL'),
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);


        }
        else
        {

            $Contact = Contact::where('CustomerId', $data['CustomerId'])->where('IsPrimary', '1')->get();
            if ($Contact->count() > 0)
            {
                // $response = [
                //     'Success' => false,
                //     'ResponseMessage' => "Primary number already exist!",
                //     'ResponseCode' => "209",
                //     'ApiUrl' => env('APP_URL'),
                //     'ApiVersion' => env('APP_VERSION'),
                // ];
                // return response()->json($response);
                if($data['IsPrimary'] == '1')
                {
                    $datau =  array();
                    $datau['IsPrimary'] = '0';
                    $Contact_update = Contact::where('CustomerId',$data['CustomerId'])->update($datau);
                    if($Contact_update)
                    {
                    }
                }
            }


            $ContactT = Contact::where('CustomerId', $data['CustomerId'])->get();
            if ($ContactT->count() == 0)
            {
                $data['IsPrimary'] = '1';
            }

            $data['ContactId'] = $ContactId;
            $data['Status'] = '1';
            $data['Created_at'] = $CreatedDate;
            $data['Created_by'] = $request->header('UserId');


            $Contact_insert = Contact::insert($data);
            if($Contact_insert)
            {

                $City = isset($data['City']) ? $data['City'] : '';
                $Country = isset($data['Country']) ? $data['Country'] : '';
                $Created_by = isset($data['Created_by']) ? $data['Created_by'] : '';
                $CustomerId = isset($data['CustomerId']) ? $data['CustomerId'] : '';
                //$DateOfBirth = isset($data['DateOfBirth']) ? $data['DateOfBirth'] : '';
                $Email = isset($data['Email']) ? $data['Email'] : '';
                $Description = isset($data['Description']) ? $data['Description'] : '';
                $FirstName = isset($data['FirstName']) ? $data['FirstName'] : '';
                $LastName = isset($data['LastName']) ? $data['LastName'] : '';
                $IsPrimary = isset($data['IsPrimary']) ? $data['IsPrimary'] : '';
                $Mobile = isset($data['Mobile']) ? $data['Mobile'] : '';
                $PostalCode = isset($data['PostalCode']) ? $data['PostalCode'] : '';
                $State = isset($data['State']) ? $data['State'] : '';
                $StreetAddress = isset($data['StreetAddress']) ? $data['StreetAddress'] : '';
                $Updated_by = isset($data['Updated_by']) ? $data['Updated_by'] : '';
                //$WeddingAnniversary = isset($data['WeddingAnniversary']) ? $data['WeddingAnniversary'] : '';

                // $ContactQuery = "insert into salesforce.Contact (Contact_ID__c,OtherCity,Country__c,Created_By__c,Account_Id__c,Email,Description,FirstName,LastName,Is_Primary__c,MobilePhone,OtherPostalCode,OtherState,OtherStreet,Updated_By__c) values ('$ContactId','$City','$Country','$Created_by','$CustomerId','$Email','$Description','$FirstName','$LastName','$IsPrimary','$Mobile','$PostalCode','$State','$StreetAddress','$Updated_by')";

                // DB::connection('pgsql')->insert($ContactQuery);

                $response = [
                    'Success' => true,
                    'ResponseMessage' => "Contact has been created",
                    'ResponseCode' => "200",
                    'ApiUrl' => env('APP_URL'),
                    'ApiVersion' => env('APP_VERSION'),
                    // 'ContactQuery' => $ContactQuery,
                ];
                return response()->json($response);
            }
            else
            {
                // fail
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "Invalid data",
                    'ResponseCode' => "202",
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }
        }
    }


    //update customer contact
    public function updateCustomerContact(Request $request) {
		//TODO What is device_token
        $data = $request->json()->all();

        $ContactId = $this->userLib->useridGenrator();
        $tblData = array();
        $CreatedDate = date('Y-m-d H:i:s',time());
		$validator = Validator::make($data, [
			'Mobile' => 'required|string|max:255',
        ]);
        //check validation
        if ($validator->fails())
        {
            $response = [
                'Success' => false,
                'ResponseMessage' => "Mobile is required!",
                'ResponseCode' => '220',
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $ContactId = $data['ContactId'];
        //Check Memeber is exist or not
        $Contact = Contact::where('ContactId', $data['ContactId'])->get();
        if ($Contact->count() == 0)
        {   //email is not exist

            $custmer = $Contact->first();
            $response = [
                'Success' => false,
                'ResponseMessage' => "Contact does not found",
                'ResponseCode' => "201",
                'Contact' => $Contact,
                'ApiUrl' => env('APP_URL'),
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);


        }
        else
        {   //get user data

            // $custmer = $Contact->first();
            // $Contact = Contact::where('CustomerId', $custmer->CustomerId)->where('IsPrimary', '1')->get();
            // if ($Contact->count() > 0)
            // {
            //     $response = [
            //         'Success' => false,
            //         'ResponseMessage' => "Primary number already exist!",
            //         'ResponseCode' => "209",

            //         'ApiUrl' => env('APP_URL'),
            //         'ApiVersion' => env('APP_VERSION'),
            //     ];
            //     return response()->json($response);
            // }

            if($data['IsPrimary'])
            {
                $custmer = $Contact->first();
                $CustomerId = $custmer->CustomerId;
                $ContactT = Contact::where('CustomerId', $CustomerId)->get();
                if ($ContactT->count() > 0)
                {
                    $udata = array();
                    $udata['IsPrimary'] = 0;
                    $Contact_update = Contact::where('CustomerId', $CustomerId)->update($udata);
                }
            }


            $data['Updated_at'] = $CreatedDate;
            $data['Updated_by'] = $request->header('UserId');

            $Contact_update = Contact::where('ContactId',$ContactId)->update($data);
            if($Contact_update)
            {
                $City = isset($data['City']) ? $data['City'] : '';
                $Country = isset($data['Country']) ? $data['Country'] : '';
                $Created_by = isset($data['Created_by']) ? $data['Created_by'] : '';
                $CustomerId = isset($data['CustomerId']) ? $data['CustomerId'] : '';
               // $DateOfBirth = isset($data['DateOfBirth']) ? $data['DateOfBirth'] : '';
                $Email = isset($data['Email']) ? $data['Email'] : '';
                $Description = isset($data['Description']) ? $data['Description'] : '';
                $FirstName = isset($data['FirstName']) ? $data['FirstName'] : '';
                $LastName = isset($data['LastName']) ? $data['LastName'] : '';
                $IsPrimary = isset($data['IsPrimary']) ? $data['IsPrimary'] : '';
                $Mobile = isset($data['Mobile']) ? $data['Mobile'] : '';
                $PostalCode = isset($data['PostalCode']) ? $data['PostalCode'] : '';
                $State = isset($data['State']) ? $data['State'] : '';
                $StreetAddress = isset($data['StreetAddress']) ? $data['StreetAddress'] : '';
                $Updated_by = isset($data['Updated_by']) ? $data['Updated_by'] : '';
                //$WeddingAnniversary = isset($data['WeddingAnniversary']) ? $data['WeddingAnniversary'] : '';
                //Wedding_Anniversary__c='$WeddingAnniversary'
                //Birthdate='$DateOfBirth',
                // $ContactQuery = "update salesforce.Contact set OtherCity='$City',Country__c='$Country',Created_By__c='$Created_by',Account_Id__c='$CustomerId',Email='$Email',Description='$Description',FirstName='$FirstName',LastName='$LastName',Is_Primary__c='$IsPrimary',MobilePhone='$Mobile',OtherPostalCode='$PostalCode',OtherState='$State',OtherStreet='$StreetAddress',Updated_By__c='$Updated_by' where Contact_ID__c='$ContactId'";

                // DB::connection('pgsql')->update($ContactQuery);

                //get user details
                $Contact = Contact::select('*')
                ->where('IsDeleted', '=', '0')
                ->where('ContactId', $ContactId)
                ->orderBy('id', 'desc')
                ->get()->first();

                if ($Contact->CustomerId) {
                    $Customer = Customer::where('CustomerId', '=', $Contact->CustomerId)->get()->first();
                    $CustomerName = $Customer->CustomerName;
                    $CustomerCode = $Customer->CustomerCode;
                    $Contact->CustomerName =  $CustomerName;
                    $Contact->CustomerCode =  $CustomerCode;
                }

                $CountryName = '';
                if($Contact->Country)
                {
                    $countries = Countries::select('country_name')
                    ->where('id', $Contact->Country)
                    ->get()->first();
                    $CountryName = $countries->country_name;
                }
                $Contact->CountryName =  $CountryName;


                $response = [
                    'Success' => true,
                    'ResponseMessage' => "Contact has been updated",
                    'ResponseCode' => "200",
                    'Contact' => $Contact,
                    'ApiUrl' => env('APP_URL'),
                    'ApiVersion' => env('APP_VERSION'),
                    // 'ContactQuery' =>$ContactQuery
                ];
                return response()->json($response);
            }
            else
            {
                // fail
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "Invalid data",
                    'ResponseCode' => "202",
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }
        }
    }



    //update customer contact
    public function deleteCustomerContact(Request $request) {
		//TODO What is device_token
        $data = $request->json()->all();

        $ContactId = $this->userLib->useridGenrator();
        $tblData = array();
        $CreatedDate = date('Y-m-d H:i:s',time());


        $ContactId = $data['ContactId'];
        //Check Memeber is exist or not
        $Contact = Contact::where('ContactId', $data['ContactId'])->get();
        if ($Contact->count() == 0)
        {   //email is not exist

            $custmer = $Contact->first();
            $response = [
                'Success' => false,
                'ResponseMessage' => "Contact does not found",
                'ResponseCode' => "201",
                'Contact' => $Contact,
                'ApiUrl' => env('APP_URL'),
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);


        }
        else
        {   //get user data

            $data = array();
            $data['IsDeleted'] = '1';
            $data['Status'] = '0';
            $data['Updated_at'] = $CreatedDate;
            $data['Updated_by'] = $request->header('UserId');
            $Contact_update = Contact::where('ContactId',$ContactId)->update($data);
            if($Contact_update)
            {
                // $ContactQuery = "update salesforce.Contact set  Updated_By__c='$Updated_by',Is_Deleted__c='1' where Contact_ID__c='$ContactId'";

                // DB::connection('pgsql')->update($ContactQuery);
                $response = [
                    'Success' => true,
                    'ResponseMessage' => "Contact has been deleted",
                    'ResponseCode' => "200",
                    'ApiUrl' => env('APP_URL'),
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }
            else
            {
                // fail
                $response = [
                    'Success' => false,
                    'ResponseMessage' => "Invalid data",
                    'ResponseCode' => "202",
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }
        }
    }



    //List of contact
    public function getCustomerContactList(Request $request, $CustomerId =''){
            $data = $request->json()->all();
            $UserId = $request->header('UserId');
            $AuthToken = $request->header('AuthToken');

            //check auth token
            if($this->userLib->tokenChecker($request) == FALSE)
            {
                $response = [
                    'success' => false,
                    'ResponseMessage' => "Authentication Failed",
                    'ResponseCode' => "301",
                    'ApiVersion' => env('APP_VERSION'),
                ];
                return response()->json($response);
            }

            if($CustomerId)
            {
                $Contacts = Contact::select('*')
                ->where('IsDeleted', '=', '0')
                ->where('Status', '=', '1')
                ->where('CustomerId', '=', $CustomerId)
                ->get();
            }
            else
            {
                $Contacts = Contact::select('*')
                ->where('IsDeleted', '=', '0')
                ->where('Status', '=', '1')
                ->get();
            }
            foreach ($Contacts as $key => $CustomerValue)
            {
                $CustomerId = $CustomerValue->CustomerId;

                $CreatedFormatedDate = $CustomerValue->Created_at;
                $CreatedFormatedDate = date("j M Y",strtotime($CreatedFormatedDate));
                $CustomerValue->CreatedFormatedDate = $CreatedFormatedDate;


                $CustomerName = '';
                $custmer = Customer::select('CustomerName','CustomerCode')->where('CustomerId', $CustomerId)->get();
                if ($custmer->count() > 0)
                {   //email is  exist
                    $custmer = $custmer->first();
                    $CustomerName = $custmer->CustomerName;
                    $CustomerCode = $custmer->CustomerCode;
                }
                $Country = isset($CustomerValue->Country) ? $CustomerValue->Country : '';
                $CountryName = '';
                if($Country)
                {
                    $countries = Countries::select('country_name')
                    ->where('id', $Country)
                    ->get()->first();
                    $CountryName = $countries->country_name;
                }

                $CustomerValue['CustomerName'] = $CustomerName;
                $CustomerValue['CountryName'] = $CountryName;
            }

            $response = [
                'Success' => true,
                'ResponseMessage' => "Success",
                'ResponseCode' => "200",
                'AuthToken' => $AuthToken,
                'Contacts' => $Contacts,
                'ApiUrl' => env('APP_URL'),
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }


        //List of contact
    public function getCustomerContactDetail(Request $request, $ContactId =''){
        $data = $request->json()->all();
        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "Authentication Failed",
                'ResponseCode' => "301",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        if(!$ContactId)
        {
            $response = [
                'success' => false,
                'ResponseMessage' => "ContactId Required",
                'ResponseCode' => "202",
                'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $Contacts = Contact::select('*')
        ->where('IsDeleted', '=', '0')
        ->where('Status', '=', '1')
        ->where('ContactId', '=', $ContactId)
        ->get();



        if ($Contacts->count() > 0)
        {
            $Contacts = $Contacts->first();
            $CustomerId = $Contacts->CustomerId;
            $CustomerName = '';
            $custmer = Customer::select('CustomerName','CustomerCode')->where('CustomerId', $CustomerId)->get();
            if ($custmer->count() > 0)
            {   //email is  exist
                $custmer = $custmer->first();
                $CustomerName = $custmer->CustomerName;
                $CustomerCode = $custmer->CustomerCode;
            }
            $Contacts->CustomerName = $CustomerName;
            $Contacts->CustomerCode = $CustomerCode;
        }

        $Contacts->CountryName = '';
        $Country = isset($Contacts->Country) ? $Contacts->Country : '';
        if($Country)
        {
            $countries = Countries::select('country_name')
            ->where('id', $Country)
            ->get()->first();
            $Contacts->CountryName = $countries->country_name;
        }

        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,
            'Contacts' => $Contacts,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);
    }

    ### Store Customer Files

  public function uploadCustomerfilesNew(Request $request)
  {
    $CreatedDate = date('Y-m-d H:i:s',time());
    $UserId = $request->header('UserId');
    $AuthToken = $request->header('AuthToken');
    $FileId = $this->userLib->useridGenrator();
    $CustomerId = $request->input('CustomerId');

    $fileName = $this->userLib->useridGenrator();

    if($this->userLib->tokenChecker($request) == FALSE)
    {
      $response = [
        'success' => false,
        'ResponseMessage' => "Authentication Failed",
        'ResponseCode' => "301",
        'ApiVersion' => env('APP_VERSION'),
      ];
      return response()->json($response);
    }

    $data = array();
    $data['FileId'] = $FileId;
    $data['CustomerId'] = $CustomerId;
    $data['Updated_by'] = $UserId;
    $data['Created_by'] = $UserId;
    $data['Updated_at'] = $CreatedDate;
    $data['Created_at'] = $CreatedDate;
    $data['IsDeleted'] = '0';
    $data['Status'] = '1';
    $CustomerFile ='';
    // $imageName = $this->userLib->useridGenrator();
    // if ($request->hasFile('UploadFile'))
    // {
    //     $path = '';
    //     $file = $request->file('UploadFile');
    //     $extension = $file->getClientOriginalExtension();
    //     $newFileName = $imageName . '-' . time() . '.' . $extension;

    //     Storage::putFileAs(
    //         'public/customer/file',
    //         $file,
    //         $newFileName
    //     );
    //     $destinationPath = 'customer/file';
    //     $isUploaded = $file->move($destinationPath,$newFileName);

    //     if($isUploaded)
    //     {
    //         $path = 'customer/file/' . $newFileName;
    //         $ThumbnailUrl = $path;
    //     }
    //     $data['CustomerFile'] = $ThumbnailUrl;
    //     $data['FileName'] = $newFileName;
    //     $CustomerFile = CustomerFile::insert($data);
    // }
    $imageName = $this->userLib->useridGenrator();
    if ($request->hasFile('UploadFile'))
    {
        $path = '';
        $file = $request->file('UploadFile');
        $extension = $file->getClientOriginalExtension();
        $newFileName = $imageName . '-' . time() . '.' . $extension;

        Storage::putFileAs(
            'public/customer/',
            $file,
            $newFileName
        );
        $destinationPath = 'customer/';
        $isUploaded = $file->move($destinationPath,$newFileName);

        $uploadedFileURL = '';
        if($isUploaded)
        {
            $path = 'customer/' . $newFileName;
            $ThumbnailUrl = $path;
        //File Upload Service as s3
        $sourceFileURL = env('APP_URL').'/'.$path;
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => 'http://172.105.42.62/s3-file-server/api-upload.php',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('file_url' => $sourceFileURL),
        CURLOPT_HTTPHEADER => array(
            'Cookie: private_content_version=3f7abce738dd8b52d0dcb8653bfe8e93; mage-messages=%5B%7B%22type%22%3A%22error%22%2C%22text%22%3A%22Invalid%20Form%20Key.%20Please%20refresh%20the%20page.%22%7D%2C%7B%22type%22%3A%22error%22%2C%22text%22%3A%22Invalid%20Form%20Key.%20Please%20refresh%20the%20page.%22%7D%2C%7B%22type%22%3A%22error%22%2C%22text%22%3A%22Invalid%20Form%20Key.%20Please%20refresh%20the%20page.%22%7D%5D'
        ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $uploadedFile = json_decode($response,true);
        $uploadedFileURL = isset($uploadedFile['url']) ? $uploadedFile['url'] : '';
        }
        $data['CustomerFile'] = $uploadedFileURL;
        $data['FileName'] = $newFileName;
        $CustomerFile = CustomerFile::insert($data);
    }

    if($CustomerFile)
    {
      $CustomerFile = CustomerFile::select('*')
      ->where('CustomerId', '=', $CustomerId)
      ->where('FileId', '=', $FileId)
      ->where('IsDeleted', '=', '0')
      ->get()->first();
      $CustomerId = $CustomerFile->CustomerId;

        $CustomerName = '';
        $custmer = Customer::select('CustomerName')->where('CustomerId', $CustomerId)->get();
        if ($custmer->count() > 0)
        {
        $custmer = $custmer->first();
        $CustomerName = $custmer->CustomerName;
        }
        $CustomerFile->CustomerName = $CustomerName;

        $response = [
        'Success' => true,
        'ResponseMessage' => "Customer file has been uploaded",
        'ResponseCode' => "200",
        'CustomerFiles' => $CustomerFile,
        'ApiUrl' => env('APP_URL'), 'ApiVersion' => env('APP_VERSION'),  ];
        return response()->json($response);
        }
        else
        {
        $response = [
        'Success' => true,
        'ResponseMessage' => "Customer file has not uploaded",
        'ResponseCode' => "201",
        'CustomerFiles' => array(),
        'ApiUrl' => env('APP_URL'), 'ApiVersion' => env('APP_VERSION'), ];
        return response()->json($response);
        }
    }

    public function getCustomerFileList(Request $request, $CustomerId ='', $FileId ='')
    {

        $data = $request->json()->all();
        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');
        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
            'success' => false,
            'ResponseMessage' => "Authentication Failed",
            'ResponseCode' => "301",
            'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $CustomerFile = CustomerFile::select('*')
        ->where('CustomerId', '=', $CustomerId)
        ->where('IsDeleted', '=', '0')
        ->get();

        foreach ($CustomerFile as $key => $CustomerValue)
        {
            $CustomerId = $CustomerValue->CustomerId;
            $CustomerName = '';
            $custmer = Customer::select('CustomerName')->where('CustomerId', $CustomerId)->get();
            if ($custmer->count() > 0)
            {
            $custmer = $custmer->first();
            $CustomerName = $custmer->CustomerName;
            }
            $CustomerValue->CustomerName = $CustomerName;
        }

        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,
            'CustomerFileList' => $CustomerFile,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);

    }

    public function getCustomerFileDetails(Request $request, $CustomerId ='', $FileId ='')
    {

        $data = $request->json()->all();
        $UserId = $request->header('UserId');
        $AuthToken = $request->header('AuthToken');

        //check auth token
        if($this->userLib->tokenChecker($request) == FALSE)
        {
            $response = [
            'success' => false,
            'ResponseMessage' => "Authentication Failed",
            'ResponseCode' => "301",
            'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        if(!$FileId)
        {
            $response = [
            'success' => false,
            'ResponseMessage' => "FileId is required",
            'ResponseCode' => "302",
            'ApiVersion' => env('APP_VERSION'),
            ];
            return response()->json($response);
        }

        $CustomerFile = CustomerFile::select('*')
        ->where('CustomerId', '=', $CustomerId)
        ->where('FileId', '=', $FileId)
        ->where('IsDeleted', '=', '0')
        ->get()->first();
        $CustomerId = $CustomerFile->CustomerId;
        $CustomerName = '';
        $custmer = Customer::select('CustomerName')->where('CustomerId', $CustomerId)->get();
        if ($custmer->count() > 0)
        {
            $custmer = $custmer->first();
            $CustomerName = $custmer->CustomerName;
        }
        $CustomerFile->CustomerName = $CustomerName;

        $response = [
            'Success' => true,
            'ResponseMessage' => "Success",
            'ResponseCode' => "200",
            'AuthToken' => $AuthToken,
            'CustomerFile' => $CustomerFile,
            'ApiUrl' => env('APP_URL'),
            'ApiVersion' => env('APP_VERSION'),
        ];
        return response()->json($response);
    }


}