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/CustomerController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use DB;
use App\Models\User;
use App\Library\ExternalDataBase;
use App\Models\Customer;
use App\Models\BeatPlanCustomer;
use App\Models\CustomerFile;
use App\Models\CustomerType;
use App\Models\Contact;
use App\Models\Order;
use App\Models\Collection;
use App\Models\Visit;
use App\Models\Countries;
use App\Models\States;
use Illuminate\Routing\Controller as BaseController;
use App\Library\UserLib;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;


class CustomerController extends Controller
{
    protected $userLib;
    protected $externalDataBase;
    public function __construct(UserLib $userLib,ExternalDataBase $externalDataBase)
    {
        $this->userLib = $userLib;
        $this->externalDataBase = $externalDataBase;
    }

    public function addCustomer()
    {

        $countries_data = Countries::orderBy('country_name', 'asc')->get();
        $data = array();
        $data['countries'] = $countries_data;
        return view('admin.add-customer', $data);
    }

    public function getStates(Request $request)
    {
        $country_id = $request->post('country_id');

        $state_data = States::where('country_id', $country_id)->orderBy('state_name', 'asc')->get();
        echo "<option value=''>Please select state</option>";
        foreach ($state_data as $state) {
            $state_name = $state->state_name;
            echo "<option value='" . $state_name . "'>" . $state_name . "</option>";
        }
    }


    ### All Customer
    public function allCustomer()
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }

        $Customer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_admin.FirstName as AdminUpdated_by', 'tbl_admin.FirstName as AdminCreated_by', 'tbl_user.FirstName as Updated_by', 'tbl_user.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_customer.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_customer.Updated_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_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        foreach ($Customer as $key => $CustomerValue) {
            $ParentCustomerId = $CustomerValue->ParentCustomerId;
            $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;
        }

        $ActiveCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.Status', '=', '1')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();


        foreach ($ActiveCustomer as $key => $CustomerValue) {
            $ParentCustomerId = $CustomerValue->ParentCustomerId;
            $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;
        }

        $InActiveCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.Status', '=', '0')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();


        foreach ($InActiveCustomer as $key => $CustomerValue) {
            $ParentCustomerId = $CustomerValue->ParentCustomerId;
            $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;
        }

        $TrashCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '1')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        foreach ($TrashCustomer as $key => $CustomerValue) {
            $ParentCustomerId = $CustomerValue->ParentCustomerId;
            $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;
        }


        return view('admin.all-customer', ['Customer' => $Customer, 'ActiveCustomer' => $ActiveCustomer, 'InActiveCustomer' => $InActiveCustomer, 'TrashCustomer' => $TrashCustomer]);
    }

    ### Active
    public function activeCustomer()
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $Customer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        $ActiveCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_admin.FirstName as AdminUpdated_by', 'tbl_admin.FirstName as AdminCreated_by', 'tbl_user.FirstName as Updated_by', 'tbl_user.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_customer.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_customer.Updated_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_customer_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.Status', '=', '1')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        $InActiveCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.Status', '=', '0')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        $TrashCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '1')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();
        return view('admin.active-customer', ['Customer' => $Customer, 'ActiveCustomer' => $ActiveCustomer, 'InActiveCustomer' => $InActiveCustomer, 'TrashCustomer' => $TrashCustomer]);
    }

    ### Inactive
    public function inactiveCustomer()
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $Customer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        $ActiveCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.Status', '=', '1')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        $InActiveCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_admin.FirstName as AdminUpdated_by', 'tbl_admin.FirstName as AdminCreated_by', 'tbl_user.FirstName as Updated_by', 'tbl_user.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_customer.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_customer.Updated_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_customer_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.Status', '=', '0')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        $TrashCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '1')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();
        return view('admin.inactive-customer', ['Customer' => $Customer, 'ActiveCustomer' => $ActiveCustomer, 'InActiveCustomer' => $InActiveCustomer, 'TrashCustomer' => $TrashCustomer]);
    }

    ### Trash
    public function trashCustomer()
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $Customer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        $ActiveCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.Status', '=', '1')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        $InActiveCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', '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_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.Status', '=', '0')
            ->where('tbl_customer.IsDeleted', '=', '0')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();

        $TrashCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_admin.FirstName as AdminUpdated_by', 'tbl_admin.FirstName as AdminCreated_by', 'tbl_user.FirstName as Updated_by', 'tbl_user.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_customer.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_customer.Updated_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_customer_type', 'tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->leftJoin('tbl_price_book', 'tbl_customer.PriceBookId', '=', 'tbl_price_book.PriceBookId')
            ->leftJoin('tbl_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->where('tbl_customer.IsDeleted', '=', '1')
            ->orderBy('tbl_customer.id', 'desc')
            ->get();
        return view('admin.trash-customer', ['Customer' => $Customer, 'ActiveCustomer' => $ActiveCustomer, 'InActiveCustomer' => $InActiveCustomer, 'TrashCustomer' => $TrashCustomer]);
    }

    ### View Record
    public function viewCustomer($CustomerId)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }

        $ViewCustomer = Customer::select('tbl_customer.*', 'tbl_price_book.PriceBookName', 'tbl_customer_type.Name as CustomerType', 'tbl_sales_area.Name as SalesArea', 'tbl_payment_terms.Name as PaymentTermName', 'tbl_beat_plan.BeatPlanName as BeatPlanName', 'tbl_countries.country_name as BillingCountry', 'tbl_admin.FirstName as AdminUpdated_by', 'tbl_admin.FirstName as AdminCreated_by', 'tbl_user.FirstName as Updated_by', 'tbl_user.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_customer.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_customer.Updated_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_countries', 'tbl_customer.BillingCountry', '=', 'tbl_countries.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_payment_terms', 'tbl_customer.PaymentTermId', '=', 'tbl_payment_terms.PaymentTermId')
            ->leftJoin('tbl_sales_area', 'tbl_customer.SalesArea', '=', 'tbl_sales_area.SalesAreaId')
            ->leftJoin('tbl_beat_plan', 'tbl_customer.BeatPlan', '=', 'tbl_beat_plan.BeatPlanId')
            ->where('tbl_customer.CustomerId', '=', $CustomerId)
            ->get()->first();

        $ViewCustomer->UserName = '';
        if ($ViewCustomer->AssignTo) {
            $UserDetail = User::select('tbl_user.*')
                ->where('UserId', $ViewCustomer->AssignTo)
                ->orderBy('tbl_user.id', 'desc')
                ->get()->first();
            $ViewCustomer->UserName = $UserDetail->FirstName.' '.$UserDetail->LastName;
        }
        // print_r($ViewCustomer->UserName);exit;

        $ViewCustomer->ShippingCountryName = '';
        if ($ViewCustomer->ShippingCountry) {
            $CountryName = Countries::select('country_name')
                ->where('id', $ViewCustomer->ShippingCountry)
                ->orderBy('tbl_countries.id', 'desc')
                ->get()->first();
            $ViewCustomer->ShippingCountryName = $CountryName->country_name;
        }

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

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

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


        // echo response()->json($ViewCustomer);
        // exit;

        $CustomerContact = Contact::select('tbl_contact.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerCode as CustomerCode', 'tbl_customer.CustomerId as CustomerId', 'tbl_countries.country_name as Country', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')->where('tbl_contact.CustomerId', '=', $CustomerId)
            ->leftJoin('tbl_admin', 'tbl_contact.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_customer', 'tbl_contact.CustomerId', '=', 'tbl_customer.CustomerId')
            ->leftJoin('tbl_countries', 'tbl_contact.Country', '=', 'tbl_countries.id')
            ->where('tbl_contact.IsDeleted', '=', '0')
            ->orderBy('tbl_contact.id', 'desc')
            ->get();


        $CustomerOrder = Order::select('tbl_order.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerName as FullFilledBy', 'tbl_order_status.OrderStatusTitle as OrderStatusId', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')->where('tbl_order.CustomerId', '=', $CustomerId)
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->where('tbl_order.IsDeleted', '=', '0')
            ->where('tbl_order.IsReturn', '=', '0')
            ->orderBy('id', 'desc')
            ->get();
        $CustomerCollection = Collection::select('tbl_collection.*', 'tbl_payment_type.PaymentTypeName as PaymentType', 'tbl_customer.CustomerName as CustomerId', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_collection.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_customer', 'tbl_collection.CustomerId', '=', 'tbl_customer.CustomerId')
            ->leftJoin('tbl_payment_type', 'tbl_collection.PaymentType', '=', 'tbl_payment_type.PaymentTypeId')
            ->where('tbl_collection.IsDeleted', '=', '0')
            ->where('tbl_collection.CustomerId', '=', $CustomerId)
            ->orderBy('tbl_collection.id', 'desc')
            ->get();
        $CustomerVisit = Visit::select('tbl_visits.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerCode as CustomerCode', 'tbl_user.FirstName as FirstName', 'tbl_user.LastName as LastName', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_visits.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_visits.UserId', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_customer', 'tbl_visits.CustomerId', '=', 'tbl_customer.CustomerId')
            ->where('tbl_visits.IsDeleted', '=', '0')
            ->where('tbl_visits.CustomerId', '=', $CustomerId)
            ->orderBy('tbl_visits.id', 'desc')
            ->get();
        $CustomerFile = CustomerFile::select('tbl_customer_file.*', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_customer_file.Created_by', '=', 'tbl_admin.UserId')
            ->where('tbl_customer_file.CustomerId', '=', $CustomerId)
            ->where('tbl_customer_file.IsDeleted', '=', '0')
            ->get();
        return view('admin.view-customer', ['ViewCustomer' => $ViewCustomer, 'CustomerContact' => $CustomerContact, 'CustomerOrder' => $CustomerOrder, 'CustomerCollection' => $CustomerCollection, 'CustomerVisit' => $CustomerVisit, 'CustomerFile' => $CustomerFile, 'CustomerId' => $CustomerId]);
    }


    function ajaxGetCustomerContactList($CustomerId='')
    {
        $CustomerContact = Contact::select('tbl_contact.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerCode as CustomerCode', 'tbl_customer.CustomerId as CustomerId', 'tbl_countries.country_name as Country', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')->where('tbl_contact.CustomerId', '=', $CustomerId)
        ->leftJoin('tbl_admin', 'tbl_contact.Updated_by', '=', 'tbl_admin.UserId')
        ->leftJoin('tbl_customer', 'tbl_contact.CustomerId', '=', 'tbl_customer.CustomerId')
        ->leftJoin('tbl_countries', 'tbl_contact.Country', '=', 'tbl_countries.id')
        ->where('tbl_contact.IsDeleted', '=', '0')
        ->orderBy('tbl_contact.id', 'desc')
        ->get();

        $k = 1;
        if($CustomerContact->count() > 0){
            foreach ($CustomerContact as $key => $CCValue)
            {
                //$CustomerId = $CCValue->CustomerId;
                $Contact = $CCValue;
                ?>
                <tr>
                    <td><?php echo  $k ?></td>
                    <td><a href="<?php echo url('view-contact', $Contact->ContactId); ?>" target="_blank"><?php echo $Contact->FirstName ." ". $Contact->LastName; ?></a></td>
                    <td><?php echo  $Contact->StreetAddress .', '. $Contact->City .', '. $Contact->State .', '. $Contact->Country ?></td>
                    <td><?php echo  $Contact->Mobile ?></td>
                    <td>
                        <?php if ($Contact->IsPrimary=='1') { ?>
                        <span class="badge badge-primary">Yes</span>
                        <?php  } else { ?>
                        <span class="badge badge-warning">No</span>
                        <?php } ?>
                    </td>
                    <td>
                        <?php if ($Contact->Status=='1') { ?>
                        <a href="{{ url('/status-update-contact',$Contact->id) }}"
                        class="btn btn-success bg-success btn-xs" data-toggle="tooltip" data-placement="top"
                        title="Click to De-activate" data-id="{{ $Contact->id }}">Active</a>
                        <?php  } else { ?>
                        <a href="{{ url('/status-update-contact',$Contact->id) }}" class="btn btn-danger btn-xs"
                        data-toggle="tooltip" data-placement="top" title="Click to Activate">InActive</a>
                        <?php } ?>
                    </td>
                    <td><?php echo  $Contact->Created_by .", ". date('d-M-y h:i:s a', strtotime($Contact->Created_at)); ?>
                    </td>
                    <td>
                        <div class="btn-group">
                        <button type="button" class="btn btn-default btn-sm dropdown-toggle dropdown-icon"
                            data-toggle="dropdown" aria-expanded="false">
                        </button>
                        <div class="dropdown-menu dropdown-menu-right" role="menu">
                            <button type="button" class="dropdown-item btn btn-default" id="<?php echo $Contact->id ?>"
                            onclick="editRecordContact('<?php echo $Contact->id ?>')">Edit</button>
                            <button type="button" class="dropdown-item btn btn-default"
                            data-id="<?php echo $Contact->id ?>"
                            onclick="deleteCustomerContact('<?php echo $Contact->id ?>');">Delete</button>
                        </div>
                        </div>
                    </td>
                    </tr>
                <?php
                $k++;
            }
        }
        else
        {
            ?>
            <tr class="tblloading text-center"><td class="tblloading" colspan="8">Data not found.</td></tr>
            <?php
        }
    }

    ## Get Customer Files
    public function getCustomerFile($CustomerId)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $CustomerFile = CustomerFile::select('tbl_customer_file.*', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_customer_file.Created_by', '=', 'tbl_admin.UserId')
            ->where('tbl_customer_file.CustomerId', '=', $CustomerId)
            ->where('tbl_customer_file.IsDeleted', '=', '0')
            ->orderBy('tbl_customer_file.id', 'DESC')
            ->get();
        return response()->json([
            'CustomerFile' => $CustomerFile,
        ]);
    }


    ### Customer Details
    public function CustomerDetails(Request $request)
    {
        $CustomerId = $request->post('CustomerId');
        $Customer = Customer::where('CustomerId', '=', $CustomerId)->get()->first();
        return response()->json([
            'status' => 200,
            'Customer' => $Customer,
        ]);
    }

    ### Store New Records
    public function storeCustomer(Request $request)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }

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

        // Contact details
        $title = $request->input('addTitle');
        $firstName = $request->input('firstName');

        $lastName = '';
        if ($request->input('lastName')) {
            $lastName = $request->input('lastName');
        }

        $mobile = $request->input('mobile');
        $email = '';
        if ($request->input('email')) {
            $email = $request->input('email');
        }

        $StreetAddress = $request->input('BillingAddress');
        $City = $request->input('BillingAddress');
        $Country = $request->input('BillingCountry');
        $State = $request->input('BillingState');
        $PostalCode = $request->input('BillingPinCode');

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

        // $imageName = $this->userLib->useridGenrator();
        // if ($request->hasFile('customerImage'))
        // {
        //     $path = '';
        //     $file = $request->file('customerImage');
        //     $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('customerImage')) {
            $path = '';
            $file = $request->file('customerImage');
            $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;
        }

        $g_CustomerId = $this->userLib->useridGenrator();
        $data['CustomerId'] =  $g_CustomerId;
        $data['CustomerCode'] =  $CustomerCode;
        $data['IsDeleted'] = 0;
        $data['Status'] = 1;
        $data['Created_by'] = session('UserId');
        $data['Created_at'] = date('Y-m-d H:i:s', time());
        $data['Updated_by'] = session('UserId');
        $data['Updated_at'] = date('Y-m-d H:i:s', time());

        unset($data['_token']);
        unset($data['customerImage']);

        unset($data['addTitle']);
        unset($data['firstName']);
        unset($data['lastName']);
        unset($data['mobile']);
        unset($data['email']);

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

        if ($insert_customer) {
            $latestCustomer = Customer::orderBy('Created_at', 'DESC')->first();

            $CustomerId = $latestCustomer->CustomerId;
            // Insert Contact detail into tbl_contact table
            if ($request->input('mobile')) {

                $g_ContactId = $this->userLib->useridGenrator();
                $contact['ContactId'] = $g_ContactId;
                $contact['CustomerId'] = $CustomerId;
                $contact['Title'] = $title;
                $contact['FirstName'] = $firstName;
                $contact['LastName'] = $lastName;
                $contact['Mobile'] = $mobile;
                $contact['Email'] = $email;
                $contact['StreetAddress'] = $StreetAddress;
                $contact['City'] = $City;
                $contact['Country'] = $Country;
                $contact['State'] = $State;
                $contact['PostalCode'] = $PostalCode;
                $contact['Created_by'] = session('UserId');
                $contact['Created_at'] = date('Y-m-d H:i:s', time());
                $contact['Updated_by'] = session('UserId');
                $contact['Updated_at'] = date('Y-m-d H:i:s', time());
                $contact['IsDeleted'] = 0;
                $contact['Status'] = 1;
                $contact['IsPrimary'] = 1;

                $CustomerContact = Contact::insert($contact);

                ### SalesForce Insert Customer details
                // $CustomerId =  $g_CustomerId;
                // $customerName_sf = $request->input('CustomerName');
                // if ($customerName_sf) {
                //     $customerName_sf = strtoupper($customerName_sf);
                //     $CustomerCode_sf = substr($customerName_sf, 0, 4) . $g_CustomerId;
                // }
                // $CustomerCode =  $CustomerCode_sf;
                // $customerTypeId_sf = $request->input('CustomerTypeId');
                // $description_sf = '';
                // if ($request->input('Description')) {
                //     $description_sf = $request->input('Description');
                // }
                // $PriceBookId_sf = $request->input('PriceBookId');
                // $title_sf= $request->input('addTitle');
                // $firstName_sf = $request->input('firstName');

                // $lastName_sf = '';
                // if ($request->input('lastName')) {
                //     $lastName_sf = $request->input('lastName');
                // }
                // $mobile_sf ='';
                // if ($request->input('mobile')) {
                //    $mobile_sf = $request->input('mobile');
                // }


                // $email_sf = '';
                // if ($request->input('email')) {
                //     $email_sf = $request->input('email');
                // }

                // $StreetAddress_sf = $request->input('BillingAddress');
                // $City_sf = $request->input('BillingCity');
                // $CountryPrimaryId = $request->input('BillingCountry');
                // $Country_sf = '';
                // if($CountryPrimaryId){
                //     $customer_details = Countries::select('tbl_countries.country_name')
                //     ->where('tbl_countries.id', $CountryPrimaryId)
                //     ->get()->first();
                //     $Country_sf = $customer_details->country_name;
                // }
                // $State_sf = $request->input('BillingState');
                // $PostalCode_sf = $request->input('BillingPinCode');
                // $StreetAddress_Shipping_sf = $request->input('ShippingAddress');
                // $City_Shipping_sf = $request->input('ShippingCity');
                // $ShippingCountryId_sf = $request->input('ShippingCountry');
                // $Country_Shipping_sf = '';
                // if($ShippingCountryId_sf){
                //     $customer_details = Countries::select('tbl_countries.country_name')
                //     ->where('tbl_countries.id', $ShippingCountryId_sf)
                //     ->get()->first();
                //     $Country_Shipping_sf = $customer_details->country_name;
                // }
                // $State_Shipping_sf = $request->input('ShippingState');
                // $PostalCode_Shipping_sf = $request->input('ShippingPinCode');
                // $CustomerPAN = $request->input('CustomerPAN');
                // $CustomerGST = $request->input('CustomerGST');
                ###Image Insert
                // $imageName_sf = $this->userLib->useridGenrator();
                // $path = '';
                // if ($request->hasFile('customerImage')) {
                //     $file = $request->file('customerImage');
                //     $extension = $file->getClientOriginalExtension();
                //     $newFileName_sf = $imageName_sf . '-' . time() . '.' . $extension;

                //     Storage::putFileAs(
                //         'public/customer',
                //         $file,
                //         $newFileName_sf
                //     );
                //     $path = Storage::url('customer/' . $newFileName_sf);
                // }
                // $CustomerProfileImage = $path;

                // $IsDeleted = 0;
                // $Status = 1;

                // $insert_customer_sf =  DB::connection('pgsql')->insert("insert into salesforce.Account (Customer_Id__c,Name,Customer_Type_Id__c,Customer_Code__c,Description,Title__c,First_Name__c,Last_Name__c,Mobile__c,Email__c,BillingStreet,BillingCity,BillingCountry,BillingState,BillingPostalCode,ShippingStreet,ShippingCity,ShippingCountry,ShippingState,ShippingPostalCode,Customer_PAN__c,Customer_GST__c,IsDeleted,Status__c,Price_Book_Id__c) values ('$CustomerId','$customerName_sf','$customerTypeId_sf','$CustomerCode','$description_sf','$title_sf','$firstName_sf','$lastName_sf','$mobile_sf','$email_sf','$StreetAddress_sf','$City_sf','$Country_sf','$State_sf','$PostalCode_sf','$StreetAddress_Shipping_sf','$City_Shipping_sf','$Country_Shipping_sf','$State_Shipping_sf','$PostalCode_Shipping_sf','$CustomerPAN','$CustomerGST','$IsDeleted','$Status','$PriceBookId_sf')");

               // $insert_customer_sf=$this->externalDataBase->createCustomer($CustomerId);
                // if ($insert_customer_sf > 0) {

                   ### Insert Contact detail into tbl_contact table

                //     if ($mobile_sf > 0) {

                //         $IsDeleted = 0;
                //         $Status = 1;

                //         $CustomerContactDetail =  DB::connection('pgsql')->insert("insert into salesforce.contact (Contact_ID__c,Title,FirstName,LastName,Phone,Email,External_Account_Id__c,MailingStreet,MailingCity,MailingCountry,MailingState,MailingPostalCode,IsDeleted,Status__c) values ('$g_ContactId','$title_sf','$firstName_sf','$lastName_sf','$mobile_sf','$email_sf','$CustomerId','$StreetAddress_sf','$City_sf','$Country_sf','$State_sf','$PostalCode_sf','$IsDeleted','$Status')");

                //         if ($CustomerContactDetail) {
                //             return response()->json('status_success');
                //         } else {
                //             return response()->json('status_failed');
                //         }

                //     }
                // }
                if ($CustomerContact) {
                    return response()->json('status_success');
                } else {
                    return response()->json('status_failed');
                }

            }
        }
    }

    #### Change Status
    public function statusUpdateCustomer($id)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $data = Customer::find($id);
        if ($data->Status == '1') {
            $Status = '0';
        } else {
            $Status = '1';
        }

        $values = array('Status' => $Status);
        Customer::find($id)->update($values);
        return redirect()->back();
    }


    #### Delete Temporary
    public function deleteCustomer($id)
    {

        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }

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

        $data = array();
        $data['Updated_at'] = $CreatedDate;
        $data['Status'] = '0';
        $data['IsDeleted'] = '1';

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

        // DB::connection('pgsql')->update("update salesforce.Account set IsDeleted='1',Status__c='0' where customer_id__c = '$id'");

        if ($customer_update) {
            echo '1';
        } else {
            echo '0';
        }
    }

    #### Delete Selected Customer
    public function deleteSelectedCustomer(Request $request)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }

        $id = $request->input('SelectedCustomer');
        if ($id) {
            foreach ($id as $custmer) {
                $checkData = Customer::find($custmer);
                if ($checkData->IsDeleted == '0') {
                    $CreatedDate = date(
                        'Y-m-d H:i:s',
                        time()
                    );
                    $data = array();
                    $data['Updated_at'] = $CreatedDate;
                    $data['IsDeleted'] = '1';
                    $data['Status'] = '0';

                    $selected_custmer = Customer::where('id', $custmer)->update($data);
                    if ($selected_custmer) {
                        echo '1';
                    } else {
                        echo '0';
                    }
                } else {
                    $selected_custmer = Customer::find($custmer);
                    $selected_custmer->delete();
                }
            }
        }

        return redirect()->back()->with('status_success');
    }

    #### Restore
    public function restoreCustomer($CustomerId)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $CreatedDate = date('Y-m-d H:i:s', time());

        $data = array();
        $data['Updated_at'] = $CreatedDate;
        $data['IsDeleted'] = '0';

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

        // DB::connection('pgsql')->update("update salesforce.Account set IsDeleted='0',Status__c='1' where customer_id__c = '$CustomerId'");

        if ($customer_update) {
            echo '1';
        } else {
            echo '0';
        }
    }

    #### Delete Permanent
    public function destroyCustomer($id)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $destroyData = Customer::find($id);
        $destroyData->delete();
    }

    ### Edit Records
    public function editCustomer($id)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        // $Customer = Customer::select('tbl_customer.*')
        //     ->where('CustomerId', $id)
        //     ->get()->first();
        // return response()->json([
        //     'status' => 200,
        //     'Customer' => $Customer,
        // ]);

        $Customer = Customer::select('tbl_customer.*', 'tbl_beat_plan_customers.BeatPlanCustomerId as BeatPlanCustomerId','tbl_customer_type.Name as CustomerTypeName')
            ->leftJoin('tbl_beat_plan_customers', 'tbl_customer.BeatPlan', '=', 'tbl_beat_plan_customers.BeatPlanId')
            ->leftJoin('tbl_customer_type','tbl_customer.CustomerTypeId', '=', 'tbl_customer_type.CustomerTypeId')
            ->where('tbl_customer.CustomerId', $id)
            ->get()->first();
        return response()->json([
            'status' => 200,
            'Customer' => $Customer,
        ]);
    }

    ### Update Records
    public function updateCustomer(Request $request)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $customer_id =  $request->input('CustomerId');

        $data['CustomerName'] = $request->input('customerName');
        $data['Description'] = $request->input('customerDescription');
        $data['BillingAddress'] = $request->input('billingStreetAddress');
        $data['BillingCountry'] = $request->input('billingCountry');
        $data['BillingState'] = $request->input('billingState');
        $data['BillingCity'] = $request->input('billingCity');
        $data['BillingPinCode'] = $request->input('billingPostalCode');
        $data['ShippingAddress'] = $request->input('shippingStreetAddress');
        $data['ShippingCountry'] = $request->input('shippingCountry');
        $data['ShippingState'] = $request->input('ShippingState');
        $data['ShippingCity'] = $request->input('shippingCity');
        $data['ShippingPinCode'] = $request->input('shippingPostalCode');
        $data['CustomerTypeId'] = $request->input('customerType');
        $CustomerTypeId = $request->input('customerType');
        $CustomerTypeName = '';
        if($CustomerTypeId){
            $customer_type_details = CustomerType::select('tbl_customer_type.*')
            ->where('tbl_customer_type.CustomerTypeId', $CustomerTypeId)
            ->where('Status', '=', '1')
            ->get()->first();
            $CustomerTypeName = $customer_type_details->Name;
        }
        $data['Type'] = $CustomerTypeName;
        $data['DistributorId'] = $request->input('distributorName');
        $data['WholeSellerId'] = $request->input('wholeSellerName');
        $data['ParentCustomerId'] = $request->input('parentCustomer');
        $data['PaymentTermId'] = $request->input('paymentTerm');
        $data['PriceBookId'] = $request->input('priceBook');
        $data['BeatPlan'] = $request->input('beatPlan');
        $data['SalesArea'] = $request->input('salesArea');
        $data['CustomerPAN'] = $request->input('panNumber');
        $data['CustomerGST'] = $request->input('gstNumber');
        $data['Updated_by'] = session('UserId');
        $data['AssignTo'] = $request->input('AssignTo');

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

        //     Storage::putFileAs(
        //         'public/customer',
        //         $file,
        //         $newFileName
        //     );

        //     $path = Storage::url('customer/' . $newFileName);
        //     $data['CustomerProfileImage'] = $path;
        // }

        // $imageName = $this->userLib->useridGenrator();
        // if ($request->hasFile('customerImage'))
        // {
        //     $path = '';
        //     $file = $request->file('customerImage');
        //     $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('customerImage')) {
            $path = '';
            $file = $request->file('customerImage');
            $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;
        }

        if ($request->has('editStatus')) {
            $data['Status'] = '1';
        } else {
            $data['Status'] = '0';
        }

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

        $customerId_sf =  $request->input('CustomerId');

        $CustomerName = $request->input('customerName');
        $Description = $request->input('customerDescription');
        $BillingAddress = $request->input('billingStreetAddress');
        $CountryPrimaryId = $request->input('billingCountry');
        $BillingCountry = '';
        if($CountryPrimaryId){
            $customer_details = Countries::select('tbl_countries.country_name')
            ->where('tbl_countries.id', $CountryPrimaryId)
            ->get()->first();
            $BillingCountry = $customer_details->country_name;
        }
        $BillingState = $request->input('billingState');
        $BillingCity = $request->input('billingCity');
        $BillingPinCode = $request->input('billingPostalCode');
        $StreetAddress_Shipping_sf = $request->input('shippingStreetAddress');
        $City_Shipping_sf = $request->input('shippingCity');
        $ShippingCountryId_sf = $request->input('shippingCountry');
        $Country_Shipping_sf = '';
        if($ShippingCountryId_sf){
            $customer_details = Countries::select('tbl_countries.country_name')
            ->where('tbl_countries.id', $ShippingCountryId_sf)
            ->get()->first();
            $Country_Shipping_sf = $customer_details->country_name;
        }
        $State_Shipping_sf = $request->input('ShippingState');
        $PostalCode_Shipping_sf = $request->input('shippingPostalCode');
        $CustomerTypeId = $request->input('customerType');
        $DistributorId = $request->input('distributorName');
        $PriceBookId = $request->input('priceBook');
        $CustomerPAN = $request->input('panNumber');
        $CustomerGST = $request->input('gstNumber');
        $AssignTo = $request->input('AssignTo');

        // DB::connection('pgsql')->update("update salesforce.Account set Name='$CustomerName',Description='$Description',BillingStreet='$BillingAddress',BillingCountry='$BillingCountry',BillingState='$BillingState',BillingCity='$BillingCity',BillingPostalCode='$BillingPinCode',ShippingStreet='$StreetAddress_Shipping_sf',ShippingCity='$City_Shipping_sf',ShippingCountry='$Country_Shipping_sf',ShippingState='$State_Shipping_sf',ShippingPostalCode='$PostalCode_Shipping_sf',Customer_Type_Id__c='$CustomerTypeId',Distributor_Id__c='$DistributorId',Customer_PAN__c='$CustomerPAN',Customer_GST__c='$CustomerGST',Assign_To__c='$AssignTo',Price_Book_Id__c='$PriceBookId' where customer_id__c='$customerId_sf'");

        // if($customer_update){
        //     return redirect()->back()->with('status_success');
        // }
        // else {
        //     return response()->json('status_failed');
        // }
        if ($customer_update) {

            $CustomerTypeId = $request->input('customerType');
            $BeatPlanCustomerId = $request->input('BeatPlanCustomerId');

            $CustomerType = '';
            if ($CustomerTypeId == '7zbZseyyTqvA6n7n5Bk01RvCm30KpPQa8M8k7') { // Retailer Id
                $CustomerType = 'Retailer';
            } elseif ($CustomerTypeId == '4zZVseyyTqvA6n7n5Bk01RvCm30KpPQa8M8k2') { // Distributor Id
                $CustomerType = 'Distributor';
            } else {
                $CustomerType = 'WholeSeller';
            }

            if ($request->input('beatPlan')) {

                $bpc['BeatPlanId'] = $request->input('beatPlan');
                $bpc['CustomerType'] = $CustomerType;
                $bpc['Updated_by'] = session('UserId');
                $bpc['Updated_at'] = date('Y-m-d H:i:s', time());

                $BeatPlanCustomer = BeatPlanCustomer::where('BeatPlanCustomerId', $BeatPlanCustomerId)->update($bpc);
                // if ($BeatPlanCustomer) {
                //     return response()->json('status_success');
                // } else {
                //     return response()->json('status_failed');
                // }
            }
        }
        return redirect()->back()->with('status_success');
    }

    ### Store Customer Files
    public function uploadCustomerFile(Request $request)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $FileId = $this->userLib->useridGenrator();
        $CustomerFile = new CustomerFile;
        $CustomerFile->CustomerId = $request->input('CustomerId');
        $CustomerFile->FileId = $FileId;
        $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;
            }
            $CustomerFile->CustomerFile = $ThumbnailUrl;
        }
        // $fileName = $this->userLib->useridGenrator();

        // if ($request->hasFile('uploadFile')) {
        //     $file = $request->file('uploadFile');
        //     $extension = $file->getClientOriginalExtension();
        //     $OriginalName = $file->getClientOriginalName();
        //     $newFileName = $fileName . '-' . time() . '.' . $extension;

        //     Storage::putFileAs(
        //         'public/customer',
        //         $file,
        //         $newFileName
        //     );

        //     $path = Storage::url('customer/' . $newFileName);
        //     $CustomerFile->CustomerFile = $path;
        //     $CustomerFile->FileName = $OriginalName;
        // }

        $CustomerFile->Created_by = session('UserId');
        $CustomerFile->Updated_by = session('UserId');
        $CustomerFile->IsDeleted = '0';
        $CustomerFile->Status = '1';

        $CustomerFile->save();

        //return redirect()->back()->with('status_success');
        return response()->json('Image uploaded successfully');
    }

    #### Delete File Temporary
    public function deleteCustomerFile($FileId)
    {


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

        $data = array();
        $data['Updated_at'] = $CreatedDate;
        $data['IsDeleted'] = '1';

        $file_update = CustomerFile::where('FileId', $FileId)->update($data);
        if ($file_update) {
            echo '1';
        } else {
            echo '0';
        }
    }
}