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

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Customer;
use App\Models\Countries;
use App\Models\PriceBookEntry;
use App\Models\CompanyProfile;
use App\Models\CompanyBankDetail;
use DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use App\Library\UserLib;
use Barryvdh\DomPDF\Facade\Pdf;

use DateTime;

class OrderController extends Controller
{

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

    #### All Order
    public function allOrder()
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $Order = Order::select('tbl_order.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerName as FullFilledBy', 'tbl_order_status.OrderStatusTitle as OrderStatusId', 'tbl_admin.FirstName as AdminCreated_by', 'tbl_user.FirstName as Updated_by', 'tbl_user.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_order.Updated_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            //->leftJoin('tbl_customer', 'tbl_order.FullFilledBy', '=', 'tbl_customer.CustomerId')
            ->where('tbl_order.IsDeleted', '=', '0')
            ->where('tbl_order.IsReturn', '=', '0')
            ->orderBy('id', 'desc')
            ->get();
        // ->toSql();

        // dd($Order);

        $TrashOrder = 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')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->where('tbl_order.IsDeleted', '=', '1')
            ->where('tbl_order.IsReturn', '=', '0')
            ->orderBy('id', 'desc')
            ->get();
        $ReturnOrder = 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')
            ->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.IsReturn', '=', '1')
            ->where('tbl_order.IsDeleted', '=', '0')
            ->orderBy('id', 'desc')
            ->get();
        $OrderItems = OrderItem::all()
            ->where('OrderId', '=', 'tbl_order.OrderId');
        // $OrderCount = OrderItem::all()
        //     ->where('tbl_order', 'tbl_order_item.OrderId', '=', 'tbl_order.OrderId');
        return view('admin.all-order', ['Order' => $Order, 'TrashOrder' => $TrashOrder, 'ReturnOrder' => $ReturnOrder, 'OrderItems' => $OrderItems]);
    }

    #Trash Order
    public function trashOrder()
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $Order = 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')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->where('tbl_order.IsDeleted', '=', '0')
            ->where('tbl_order.IsReturn', '=', '0')
            ->orderBy('id', 'desc')
            ->get();
        $TrashOrder = Order::select('tbl_order.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerName as FullFilledBy', 'tbl_order_status.OrderStatusTitle as OrderStatusId', 'tbl_admin.FirstName as AdminCreated_by', 'tbl_user.FirstName as Updated_by', 'tbl_user.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_order.Updated_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->where('tbl_order.IsDeleted', '=', '1')
            ->where('tbl_order.IsReturn', '=', '0')
            ->orderBy('id', 'desc')
            ->get();
        $ReturnOrder = 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')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->where('tbl_order.IsReturn', '=', '1')
            ->orderBy('id', 'desc')
            ->get();
        $OrderItems = OrderItem::all()
            ->where('OrderId', '=', 'tbl_order.OrderId');
        return view('admin.trash-order', ['Order' => $Order, 'TrashOrder' => $TrashOrder, 'ReturnOrder' => $ReturnOrder, 'OrderItems' => $OrderItems]);
    }


    ### Return Orders
    public function returnOrder()
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $Order = Order::select('tbl_order.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerName as FullFilledBy', 'tbl_order_status.OrderStatusTitle as OrderStatus', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->where('tbl_order.IsDeleted', '=', '0')
            ->where('tbl_order.IsReturn', '=', '0')
            ->orderBy('id', 'desc')
            ->get();
        $TrashOrder = 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')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->where('tbl_order.IsDeleted', '=', '1')
            ->where('tbl_order.IsReturn', '=', '0')
            ->orderBy('id', 'desc')
            ->get();
        $ReturnOrder = Order::select('tbl_order.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerName as FullFilledBy', 'tbl_order_status.OrderStatusTitle as OrderStatusId', 'tbl_admin.FirstName as AdminCreated_by', 'tbl_user.FirstName as Updated_by', 'tbl_user.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_order.Updated_by', '=', 'tbl_user.UserId')
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->where('tbl_order.IsReturn', '=', '1')
            ->orderBy('id', 'desc')
            ->get();
        $OrderItems = OrderItem::all()
            ->where('OrderId', '=', 'tbl_order.OrderId');
        return view('admin.return-order', ['Order' => $Order, 'TrashOrder' => $TrashOrder, 'ReturnOrder' => $ReturnOrder, 'OrderItems' => $OrderItems]);
    }


    ### View Record
    public function viewOrder($OrderId)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        //$ViewOrder = Order::find($OrderId);
        $ViewOrder = Order::select('tbl_order.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerName as FullFilledBy', 'tbl_payment_terms.Name as PaymentTerms', 'tbl_order_status.OrderStatusTitle as OrderStatusId', 'tbl_countries.country_name as BillingCountry', 'tbl_admin.FirstName as AdminCreated_by', 'tbl_user.FirstName as Updated_by', 'tbl_user.FirstName as Created_by')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->leftJoin('tbl_user', 'tbl_order.Updated_by', '=', 'tbl_user.UserId')
            ->where('OrderId', '=', $OrderId)
            ->leftJoin('tbl_order_status', 'tbl_order.OrderStatusId', '=', 'tbl_order_status.OrderStatusId')
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->leftJoin('tbl_payment_terms', 'tbl_order.PaymentTerms', '=', 'tbl_payment_terms.PaymentTermId')
            //->leftJoin('tbl_customer', 'tbl_order.FullFilledBy', '=', 'tbl_customer.CustomerId')
            ->leftJoin('tbl_countries', 'tbl_order.BillingCountry', '=', 'tbl_countries.id')
            ->get()->first();

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

        $OrderCount = OrderItem::all()
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0');

        $ListOrderItem = OrderItem::select('tbl_order_item.*', 'tbl_products.ProductName as ProductName', 'tbl_products.ProductCode as ProductCode', 'tbl_admin.FirstName as Updated_by',  'tbl_admin.FirstName as Created_by')
            ->where('OrderId', '=', $OrderId)
            ->where('ProductName', '!=', '')
            ->where('Quantity', '!=', '0')
            ->where('tbl_order_item.IsDeleted', '=', '0')
            ->leftJoin('tbl_products', 'tbl_products.ProductId', '=', 'tbl_order_item.ProductId')
            ->leftJoin('tbl_admin', 'tbl_order_item.Updated_by', '=', 'tbl_admin.UserId')
            ->get();


        return view('admin.view-order', ['Order' => $ViewOrder, 'OrderCount' => $OrderCount, 'ListOrderItem' => $ListOrderItem]);
    }

    // Order Invoice

    public function OrderInvoice($OrderId)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }

        $OrderInvoice = Order::select('tbl_order.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerName as FullFilledBy', 'tbl_customer.CustomerGST as CustomerGST', 'tbl_payment_terms.Name as PaymentTerms', 'tbl_payment_terms.Description as PaymentDue', 'tbl_admin.FirstName as Updated_by',  'tbl_admin.FirstName as Created_by')
            ->where('OrderId', '=', $OrderId)
            ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
            ->leftJoin('tbl_payment_terms', 'tbl_order.PaymentTerms', '=', 'tbl_payment_terms.PaymentTermId')
            //->leftJoin('tbl_customer', 'tbl_order.FullFilledBy', '=', 'tbl_customer.CustomerId')
            ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
            ->get()->first();

        $OrderInvoiceDate = OrderItem::select('tbl_order_item.*')
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0')
            ->orderBy('Updated_at', 'desc')
            ->get()->first();

        $PaymentDue = $OrderInvoice->PaymentTerms;
        // $DueDate = $PaymentDue;

        $DueDays = (int) filter_var($PaymentDue, FILTER_SANITIZE_NUMBER_INT);

        $OrderDate = $OrderInvoiceDate->Updated_at;

        $DueDate = '';
        if ($DueDays > 0) {
            $DueDate = date('Y-m-d', strtotime($OrderDate . ' + ' . $DueDays . ' days'));
        } else {
            $DueDate = 'No Dues ('. $OrderInvoice->PaymentDue .')';
        }

        // $CompanyProfile = CompanyProfile::select('tbl_company_profile.*', 'tbl_countries.country_name as country_name')
        //     ->leftJoin('tbl_countries', 'tbl_company_profile.Country', '=', 'tbl_countries.id')
        //     ->get()->first();

        $CompanyProfile = CompanyProfile::select('tbl_company_profile.*')
            ->get()->first();

        $country_id = $CompanyProfile->Country;

        $GetCountryName = Countries::select('*')
            ->where('id', $country_id)
            ->get()
            ->first();

        $CountryName = $GetCountryName->country_name;

        if ($CompanyProfile) {
            $CompanyProfile = $CompanyProfile;
        } else {
            $CompanyProfile = '';
        }
        $BankDetails = CompanyBankDetail::select('tbl_company_bank_detail.*')
            ->where('tbl_company_bank_detail.Status', '=', '1')
            ->get()->first();

        $OrderCount = OrderItem::all()
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0');

        $ListOrderItem = OrderItem::select('tbl_order_item.*', 'tbl_products.ProductName as ProductName', 'tbl_products.ProductCode as ProductCode', 'tbl_admin.FirstName as Updated_by',  'tbl_admin.FirstName as Created_by')
            ->where('OrderId', '=', $OrderId)
            ->where('ProductName', '!=', '')
            ->where('Quantity', '!=', '0')
            ->where('tbl_order_item.IsDeleted', '=', '0')
            ->leftJoin('tbl_products', 'tbl_products.ProductId', '=', 'tbl_order_item.ProductId')
            ->leftJoin('tbl_admin', 'tbl_order_item.Updated_by', '=', 'tbl_admin.UserId')
            ->get();
        $GrandTotal = OrderItem::all()
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0')
            ->sum("AmountWithGST");
        $SubTotal = OrderItem::all()
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0')
            ->sum("TotalPrice");
        $TaxAmount = OrderItem::all()
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0')
            ->sum("GSTInRupees");

        /// Convert In words
        $GrandTotal = round($GrandTotal);
        $GrandTotalInWords = $this->userLib->amountInWords($GrandTotal);

        //$GrandTotalInWords = $this->userLib->amountInWords('1001.25');

        return view('admin.order-invoice', ['Invoice' => $OrderInvoice, 'CompanyProfile' => $CompanyProfile, 'BankDetails' => $BankDetails, 'OrderCount' => $OrderCount, 'ListOrderItem' => $ListOrderItem, 'GrandTotal' => $GrandTotal, 'SubTotal' => $SubTotal, 'TaxAmount' => $TaxAmount, 'GrandTotalInWords' => $GrandTotalInWords, 'OrderInvoiceDate' => $OrderInvoiceDate, 'DueDate' => $DueDate, 'CountryName' => $CountryName, 'DueDays' => $DueDays]);
    }

    public function DownloadOrderPDF(Request $request,$OrderId='')
    {
        $invoice_url = url("order-invoice-mobile/").'/'.$OrderId;
        // echo $invoice_url;exit;
        $curl = curl_init();

        curl_setopt_array($curl, array(
                                CURLOPT_URL => "https://api.pdfshift.io/v3/convert/pdf",
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_POST => true,
                                CURLOPT_POSTFIELDS => json_encode(array("source" => 'http://45.79.125.34:7878/order-invoice-mobile/bFc9vImQZtx2BfDmB1StM7HR7n5CdLFl7AoLQ', "landscape" => false, "use_print" => true)),
                                CURLOPT_HTTPHEADER => array('Content-Type:application/json'),
                                CURLOPT_USERPWD => 'api:2971bbb159f44c919a10cca268e28fc6'
                            ));

        $response = curl_exec($curl);
        file_put_contents('text9.pdf', $response);
    }

    ### Download Invoice
    public function DownloadOrderInvoice($OrderId='')

    {


        return Pdf::loadFile('http://fieldsblaze.herokuapp.com/public/order-invoice-mobile/HP8LrBRLkHM6UIi58kuPivaHwZcTqFdRej4Yj')->save('my_stored_file.pdf')->stream('download.pdf');
    }

    #### Order invoice for Mobile App
    public function OrderInvoiceMobileApp($OrderId)
    {

        $OrderInvoice = Order::select('tbl_order.*', 'tbl_customer.CustomerName as CustomerName', 'tbl_customer.CustomerName as FullFilledBy', 'tbl_customer.CustomerGST as CustomerGST', 'tbl_payment_terms.Name as PaymentTerms', 'tbl_payment_terms.Description as PaymentDue', 'tbl_admin.FirstName as Updated_by',  'tbl_admin.FirstName as Created_by')
        ->where('OrderId', '=', $OrderId)
        ->leftJoin('tbl_customer', 'tbl_order.CustomerId', '=', 'tbl_customer.CustomerId')
        ->leftJoin('tbl_payment_terms', 'tbl_order.PaymentTerms', '=', 'tbl_payment_terms.PaymentTermId')
        //->leftJoin('tbl_customer', 'tbl_order.FullFilledBy', '=', 'tbl_customer.CustomerId')
        ->leftJoin('tbl_admin', 'tbl_order.Updated_by', '=', 'tbl_admin.UserId')
        ->get()->first();

        $OrderInvoiceDate = OrderItem::select('tbl_order_item.*')
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0')
            ->orderBy('Updated_at', 'desc')
            ->get()->first();

        $PaymentDue = $OrderInvoice->PaymentTerms;
        // $DueDate = $PaymentDue;

        $DueDays = (int) filter_var($PaymentDue, FILTER_SANITIZE_NUMBER_INT);

        $OrderDate = $OrderInvoiceDate->Updated_at;

        $DueDate = '';
        if ($DueDays > 0) {
            $DueDate = date('Y-m-d', strtotime($OrderDate . ' + ' . $DueDays . ' days'));
        } else {
            $DueDate = 'No Dues ('. $OrderInvoice->PaymentDue .')';
        }

        // $CompanyProfile = CompanyProfile::select('tbl_company_profile.*', 'tbl_countries.country_name as country_name')
        //     ->leftJoin('tbl_countries', 'tbl_company_profile.Country', '=', 'tbl_countries.id')
        //     ->get()->first();

        $CompanyProfile = CompanyProfile::select('tbl_company_profile.*')
            ->get()->first();

        $country_id = $CompanyProfile->Country;

        $GetCountryName = Countries::select('*')
            ->where('id', $country_id)
            ->get()
            ->first();

        $CountryName = $GetCountryName->country_name;

        if ($CompanyProfile) {
            $CompanyProfile = $CompanyProfile;
        } else {
            $CompanyProfile = '';
        }
        $BankDetails = CompanyBankDetail::select('tbl_company_bank_detail.*')
            ->where('tbl_company_bank_detail.Status', '=', '1')
            ->get()->first();

        $OrderCount = OrderItem::all()
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0');

        $ListOrderItem = OrderItem::select('tbl_order_item.*', 'tbl_products.ProductName as ProductName', 'tbl_products.ProductCode as ProductCode', 'tbl_admin.FirstName as Updated_by',  'tbl_admin.FirstName as Created_by')
            ->where('OrderId', '=', $OrderId)
            ->where('ProductName', '!=', '')
            ->where('Quantity', '!=', '0')
            ->where('tbl_order_item.IsDeleted', '=', '0')
            ->leftJoin('tbl_products', 'tbl_products.ProductId', '=', 'tbl_order_item.ProductId')
            ->leftJoin('tbl_admin', 'tbl_order_item.Updated_by', '=', 'tbl_admin.UserId')
            ->get();
        $GrandTotal = OrderItem::all()
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0')
            ->sum("AmountWithGST");
        $SubTotal = OrderItem::all()
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0')
            ->sum("TotalPrice");
        $TaxAmount = OrderItem::all()
            ->where('OrderId', '=', $OrderId)
            ->where('Quantity', '!=', '0')
            ->where('IsDeleted', '=', '0')
            ->sum("GSTInRupees");

        /// Convert In words
        $GrandTotal = round($GrandTotal);
        $GrandTotalInWords = $this->userLib->amountInWords($GrandTotal);

        //$GrandTotalInWords = $this->userLib->amountInWords('1001.25');
        // echo json_decode($OrderInvoice); exit;

        return view('admin.order-invoice-mobile', ['Invoice' => $OrderInvoice, 'CompanyProfile' => $CompanyProfile, 'BankDetails' => $BankDetails, 'OrderCount' => $OrderCount, 'ListOrderItem' => $ListOrderItem, 'GrandTotal' => $GrandTotal, 'SubTotal' => $SubTotal, 'TaxAmount' => $TaxAmount, 'GrandTotalInWords' => $GrandTotalInWords, 'OrderInvoiceDate' => $OrderInvoiceDate, 'DueDate' => $DueDate, 'CountryName' => $CountryName, 'DueDays' => $DueDays]);

    }


    // Order Invoice Print
    public function OrderInvoicePrint()
    {
        return view('admin.invoice-print');
    }

    ### Store New Record
    public function storeOrder(Request $request)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $Order = new Order;
        $Order->OrderId = $this->userLib->useridGenrator();
        $CustomerId = $request->input('CustomerId');
        $AssignTo = '';
        if ($CustomerId) {
            $Customer = Customer::where('CustomerId', '=', $CustomerId)->get()->first();
            $CustomerCode = $Customer->CustomerCode;
            $CustomerName = $Customer->CustomerName;
            $AssignTo = $Customer->AssignTo;

            $customerName = strtoupper($CustomerName);
            // $OrderNo = 'ODR-'.substr($customerName, 0, 4).$this->userLib->otpGenrator();;
            $OrderNo = 'ODR-' . $CustomerCode . '-' . time();
            $Order->OrderNo = $OrderNo;
        }
        $Order->CustomerId = $request->input('CustomerId');
        $Order->AssignTo = $AssignTo;
        $Order->OrderStatusId = $request->input('OrderStatus');
        //$Order->FullFilledBy = $request->input('FullFilledBy');
        $Order->PaymentTerms = $request->input('PaymentTerms');
        //$Order->DeliveryMethod = $request->input('DeliveryMethod');
        //$Order->Supplier = $request->input('Supplier');
        // Order Book Date
        $OrderBookDate = '';
        if ($request->input('OrderBookDate')) {
            $OrderBookDate = str_replace('/', '-', $request->input('OrderBookDate'));
        }
        $Order->OrderBookDate = date('Y-m-d h:m:s', strtotime($OrderBookDate));

        // Order Delivery Date
        $OrderDeliveryDate = '';
        if ($request->input('OrderDeliveryDate')) {
            $OrderDeliveryDate = str_replace('/', '-', $request->input('OrderDeliveryDate'));
        }
        $Order->OrderDeliveryDate = date('Y-m-d', strtotime($OrderDeliveryDate));

        $Order->BillingStreetAddress = $request->input('BillingStreetAddress');
        $Order->BillingCity = $request->input('BillingCity');
        $Order->BillingCountry = $request->input('BillingCountry');
        $Order->BillingState = $request->input('BillingState');
        $Order->BillingPostalCode = $request->input('BillingPostalCode');
        $Order->ShippingStreetAddress = $request->input('ShippingStreetAddress');
        $Order->ShippingCity = $request->input('ShippingCity');
        $Order->ShippingCountry = $request->input('shippingCountry');
        $Order->ShippingState = $request->input('ShippingState');
        $Order->ShippingPostalCode = $request->input('ShippingPostalCode');
        $Order->OrderNotes = $request->input('OrderNotes');
        $Order->Created_by = session('UserId');
        $Order->Updated_at = date('Y-m-d h:m:s');
        $Order->Created_at = date('Y-m-d h:m:s');
        $Order->Updated_by = session('UserId');
        $Order->IsDeleted = '0';
        $Order->IsReturn = '0';
        $Order->Status = '1';

        $Order->save();

        $OrderId = $Order->OrderId;
        $OrderNo = $Order->OrderNo;
        $Customer_Id = $Order->CustomerId;
        $OrderStatusId = $request->input('OrderStatus');
        $PaymentTerms = $request->input('PaymentTerms');
        $Order_Book = '';
        $Order_Start = '';
        if ($request->input('OrderBookDate')) {
            $Order_Book = str_replace('/', '-', $request->input('OrderBookDate'));
            $Order_Start = str_replace('/', '-', $request->input('OrderBookDate'));
        }
        $Order_Book_Date = date('m-d-Y h:m:s', strtotime($Order_Book));
        $Order_Start_Date = date('m-d-Y', strtotime($Order_Start));
        $Order_Delivery = '';
        if ($request->input('OrderDeliveryDate')) {
            $Order_Delivery = str_replace('/', '-', $request->input('OrderDeliveryDate'));
        }
        $Order_Delivery_Date = date('m-d-Y', strtotime($Order_Delivery));

        $BillingStreetAddress = $request->input('BillingStreetAddress');
        $BillingCity = $request->input('BillingCity');
        $BillingCountry = $request->input('BillingCountry');
        $BillingState = $request->input('BillingState');
        $BillingPostalCode = $request->input('BillingPostalCode');
        $ShippingStreetAddress = $request->input('ShippingStreetAddress');
        $ShippingCity = $request->input('ShippingCity');
        $ShippingCountry = $request->input('shippingCountry');
        $ShippingState = $request->input('ShippingState');
        $ShippingPostalCode = $request->input('ShippingPostalCode');
        $OrderNotes = $request->input('OrderNotes');
        $IsDeleted = '0';
        $IsReturn = '0';
        $Status = '1';
        DB::connection('pgsql')->insert("insert into salesforce.Order (Order_Id__c,Customer_Id__c,Order_Status_Id__c,Payment_Terms__c,Order_Book_Date__c,EffectiveDate,Order_Delivery_Date__c,BillingStreet,BillingCity,BillingCountry,BillingState,BillingPostalCode,ShippingStreet,ShippingCity,ShippingCountry,ShippingState,ShippingPostalCode,Order_Notes__c,IsDeleted,Is_Return__c,Status,Name,Assign_To__c) values ('$OrderId','$Customer_Id','$OrderStatusId','$PaymentTerms','$Order_Book_Date','$Order_Start_Date','$Order_Delivery_Date','$BillingStreetAddress','$BillingCity','$BillingCountry','$BillingState','$BillingPostalCode','$ShippingStreetAddress','$ShippingCity','$ShippingCountry','$ShippingState','$ShippingPostalCode','$OrderNotes','$IsDeleted','$IsReturn','$Status','$OrderNo','$AssignTo')");
        return response()->json('status_success');
    }

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

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

    // Take Return
    public function takeReturnOrder(Request $request)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $order_id =  $request->input('returnId');
        $UpdatedDate = date('Y-m-d H:i:s', time());

        $value = array();
        if ($request->input('ReturnReasonComment')) {
            $value['ReturnReasonComment'] = $request->input('ReturnReasonComment');
        }
        $value['ReturnReason'] = $request->input('ReturnReason');
        $value['OrderStatusId'] = 'OrdtFg673F4sd2'; // Retrun Order
        $value['Updated_at'] = $UpdatedDate;
        $value['IsReturn'] = '1';
        $order_returned = Order::where('id', $order_id)->update($value);
        if ($order_returned) {
            return redirect()->back();
        } else {
            return response()->json('status_failed');
        }
    }

    #### Cancel Return

    public function cancelReturnOrder($id)
    {

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

        $CreatedDate = date('Y-m-d H:i:s', time());
        $value = array();
        $value['Updated_at'] = $CreatedDate;
        $value['IsReturn'] = '0';
        $value['ReturnReason'] = '';
        $value['OrderStatusId'] = 'AUEFg65834sd2'; // Draft
        Order::where('OrderId', $id)->update($value);
        return response()->json('status_success');
    }

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

        $value = array();
        $value['Updated_at'] = $CreatedDate;
        $value['IsDeleted'] = '1';
        Order::where('OrderId', $id)->update($value);

        $Order = Order::find($id);
        $OrderId = $Contact->OrderId;

        DB::connection('pgsql')->update("update salesforce.Order set IsDeleted='1',Status__c='0' where Order_Id__c = '$OrderId'");
    }

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

        $value = array();
        $value['Updated_at'] = $CreatedDate;
        $value['IsDeleted'] = '0';
        Order::where('OrderId', $id)->update($value);

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

    #### Delete Permanent
    public function destroyOrder($id)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        Order::where('OrderId', $id)->delete();
    }

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

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

                    $selected_entry = Order::where('id', $OrderId)->update($data);
                    if ($selected_entry) {
                        echo '1';
                    } else {
                        echo '0';
                    }
                } else {
                    $selected_entry = Order::find($OrderId);
                    $selected_entry->delete();
                }
            }
        }

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

    ### Edit Records
    public function editOrder($id)
    {
        $Order = Order::find($id);
        return response()->json([
            'status' => 200,
            'Order' => $Order,
        ]);
    }

    ### Update Records
    public function updateOrder(Request $request)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        // print_r($_POST);exit;
        //$user_id = Auth::id();
        $CustomerId = $request->input('CustomerId');
        $AssignTo = '';
        if ($CustomerId) {
            $Customer = Customer::where('CustomerId', '=', $CustomerId)->get()->first();
            $AssignTo = $Customer->AssignTo;
        }

        $order_id =  $request->input('id');
        $Order = Order::find($order_id);



        //$Order->FullFilledBy = $request->input('FullFilledBy');

        //$Order->DeliveryMethod = $request->input('DeliveryMethod');
        //$Order->Supplier = $request->input('Supplier');
        // Order Book Date
        $OrderBookDate = '';
        if ($request->input('OrderBookDate')) {
            $OrderBookDate = str_replace('/', '-', $request->input('OrderBookDate'));
        }
        $Order->OrderBookDate = date('Y-m-d h:m:s', strtotime($OrderBookDate));

        // Order Delivery Date
        $OrderDeliveryDate = '';
        if ($request->input('OrderDeliveryDate')) {
            $OrderDeliveryDate = str_replace('/', '-', $request->input('OrderDeliveryDate'));
        }
        $Order->OrderDeliveryDate = date('Y-m-d', strtotime($OrderDeliveryDate));

        if ($request->input('OrderStatus') == 'OrdtFg673F4sd2') {
            $Order->IsReturn = '1';
        } else {
            $Order->IsReturn = '0';
        }

        if ($request->input('ReturnReason')) {
            $Order->ReturnReason = $request->input('ReturnReason');
        }
        if ($request->input('ReturnReasonComment')) {
            $Order->ReturnReasonComment = $request->input('ReturnReasonComment');
        }

        $Order->PaymentTerms = $request->input('PaymentTerms');
        $Order->OrderStatusId = $request->input('OrderStatus');
        $Order->CustomerId = $CustomerId;
        $Order->AssignTo = $AssignTo;
        $Order->BillingStreetAddress = $request->input('BillingStreetAddress');
        $Order->BillingCity = $request->input('BillingCity');
        $Order->BillingCountry = $request->input('BillingCountry');
        $Order->BillingState = $request->input('BillingState');
        $Order->BillingPostalCode = $request->input('BillingPostalCode');
        $Order->ShippingStreetAddress = $request->input('ShippingStreetAddress');
        $Order->ShippingCity = $request->input('ShippingCity');
        $Order->ShippingCountry = $request->input('ShippingCountry');
        $Order->ShippingState = $request->input('ShippingState');
        $Order->ShippingPostalCode = $request->input('ShippingPostalCode');
        $Order->OrderNotes = $request->input('OrderNotes');
        $Order->Updated_by = session('UserId');

        $Order->update();

        $OrderId = $request->input('OrderId');;
        $Customer_Id = $request->input('CustomerId');
        $OrderStatusId = $request->input('OrderStatus');
        $PaymentTerms = $request->input('PaymentTerms');
        $Order_Book = '';
        if ($request->input('OrderBookDate')) {
            $Order_Book = str_replace('/', '-', $request->input('OrderBookDate'));
        }
        $Order_Book_Date = date('m-d-Y h:m:s', strtotime($Order_Book));

        $Order_Delivery = '';
        if ($request->input('OrderDeliveryDate')) {
            $Order_Delivery = str_replace('/', '-', $request->input('OrderDeliveryDate'));
        }
        $Order_Delivery_Date = date('m-d-Y', strtotime($Order_Delivery));

        $BillingStreetAddress = $request->input('BillingStreetAddress');
        $BillingCity = $request->input('BillingCity');
        $BillingCountry = $request->input('BillingCountry');
        $BillingState = $request->input('BillingState');
        $BillingPostalCode = $request->input('BillingPostalCode');
        $ShippingStreetAddress = $request->input('ShippingStreetAddress');
        $ShippingCity = $request->input('ShippingCity');
        $ShippingCountry = $request->input('ShippingCountry');
        $ShippingState = $request->input('ShippingState');
        $ShippingPostalCode = $request->input('ShippingPostalCode');
        $OrderNotes = $request->input('OrderNotes');

        DB::connection('pgsql')->update("update salesforce.Order set Customer_Id__c='$Customer_Id',Order_Status_Id__c='$OrderStatusId',Payment_Terms__c='$PaymentTerms',Order_Book_Date__c='$Order_Book_Date',Order_Delivery_Date__c='$Order_Delivery_Date',BillingStreet='$BillingStreetAddress',BillingCity='$BillingCity',BillingCountry='$BillingCountry',BillingState='$BillingState',BillingPostalCode='$BillingPostalCode',ShippingStreet='$ShippingStreetAddress',ShippingCity='$ShippingCity',ShippingCountry='$ShippingCountry',ShippingState='$ShippingState',ShippingPostalCode='$ShippingPostalCode',Order_Notes__c='$OrderNotes',Assign_To__c='$AssignTo' where Order_Id__c='$OrderId'");
        return redirect()->back()->with('status_success');
    }


    #Get Products List

    public function getCustomerOrderProduct($CustomerId = '', $OrderId = '')
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }

        // $ActiveProduct = Product::select('tbl_products.*','tbl_product_family.Name as Family', 'tbl_unit_of_measurement.MeasurementName as Unit','tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
        // ->leftJoin('tbl_admin', 'tbl_products.Updated_by', '=', 'tbl_admin.UserId')
        // ->leftJoin('tbl_product_family', 'tbl_products.Family', '=', 'tbl_product_family.id')
        // ->leftJoin('tbl_unit_of_measurement', 'tbl_products.Unit', '=', 'tbl_unit_of_measurement.id')
        // ->where('tbl_products.Status', '=', '1')
        // ->get();


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

        if ($Customer->count() == 0) {
            $response = [
                'success' => false,
                'error_message' => "Customer not found",
                'error_code' => "202",
                'ApiVersion' => env('APP_VERSION'),
            ];
            echo json_encode($response);
        } else {
            $Customer = $Customer->first();
            $PriceBookId = $Customer->PriceBookId;
            if (!$PriceBookId) {
                $response = [
                    'success' => false,
                    'error_message' => "Price book has not linked",
                    'error_code' => "206",
                    'ApiVersion' => env('APP_VERSION'),
                ];
                echo json_encode($response);
            } else {

                // Get existing order item from Order Item table
                $GetExistOrderItem = OrderItem::select('tbl_order_item.ProductId')
                    ->where('OrderId', $OrderId)
                    ->where('Quantity', '!=', '0')
                    ->get();

                /* if ($GetExistOrderItem->count() > 0) {
                    foreach ($GetExistOrderItem as $key => $GetOrderItem) {
                        $GetProductId = $GetOrderItem->ProductId;
                        echo $GetProductId . '<br/>';
                    }
                }
                exit; */
         
                
                $PriceBookEntry = PriceBookEntry::select('tbl_price_book_entry.*', 'tbl_price_book.PriceBookName', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by', 'tbl_products.*')
                    ->whereNotIn('tbl_price_book_entry.ProductId', $GetExistOrderItem)
                    ->leftJoin('tbl_admin', 'tbl_price_book_entry.Created_by', '=', 'tbl_admin.UserId')
                    ->leftJoin('tbl_price_book', 'tbl_price_book_entry.PriceBookId', '=', 'tbl_price_book.PriceBookId')
                    ->leftJoin('tbl_products', 'tbl_price_book_entry.ProductId', '=', 'tbl_products.ProductId')
                    // ->leftJoin('tbl_product_family', 'tbl_products.Family', '=', 'tbl_product_family.id')
                    ->where('tbl_price_book_entry.IsDeleted', '=', '0')
                    ->where('tbl_price_book_entry.Status', '=', '1')
                    ->where('tbl_products.IsDeleted', '=', '0')
                    ->where('tbl_products.Status', '=', '1')
                    ->where('tbl_price_book.Status', '=', '1')
                    ->where('tbl_price_book.IsDeleted', '=', '0')
                    ->where('tbl_price_book_entry.PriceBookId', '=', $PriceBookId)
                    ->get();

                if ($PriceBookEntry->count() > 0) {
                    foreach ($PriceBookEntry as $key => $ProductValue) {
                        $ProductValue['CustomerId'] = $CustomerId;
                    }

                    if ($PriceBookEntry->count() > 0) {
                        $s = 1;
                        $data = array();
                        foreach ($PriceBookEntry as $key => $ProductValue) {
                            $ProductId = $ProductValue['ProductId'];
                            $ProductCode = $ProductValue['ProductCode'];
                            $ProductName = $ProductValue['ProductName'];
                            $PriceBookId = $ProductValue['PriceBookId'];

                            // $data[] = array('Sno'=>$s,'ProductId'=>$ProductId,'ProductCode'=>$ProductCode, 'ProductName'=>$ProductName);

                            echo "<tr>
                                <td><input type='checkbox' class='chk_productid' name='ProductId' id='ProductId' value = '" . $ProductId . "' data-pricebookid='" . $PriceBookId . "'/></td>
                                <td>$s</td>
                                <td><input type='text' name='ProductCode' id='ProductCode' style='border:none' value='" . $ProductCode . "' readonly ></td>
                                <td><input type='text' name='ProductCode' id='ProductCode' style='border:none'  value='" . $ProductName . "' readonly ></td>
                            </tr>";
                            $s++;
                        }
                    }
                } else {
                    echo "Price Book Not Found ";
                }
            }
        }
    }

    public function getCustomerOrderProduct333($CustomerId = '', $OrderId = '')
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }

        // $ActiveProduct = Product::select('tbl_products.*','tbl_product_family.Name as Family', 'tbl_unit_of_measurement.MeasurementName as Unit','tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
        // ->leftJoin('tbl_admin', 'tbl_products.Updated_by', '=', 'tbl_admin.UserId')
        // ->leftJoin('tbl_product_family', 'tbl_products.Family', '=', 'tbl_product_family.id')
        // ->leftJoin('tbl_unit_of_measurement', 'tbl_products.Unit', '=', 'tbl_unit_of_measurement.id')
        // ->where('tbl_products.Status', '=', '1')
        // ->get();


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

        if ($Customer->count() == 0) {
            $response = [
                'success' => false,
                'error_message' => "Customer not found",
                'error_code' => "202",
                'ApiVersion' => env('APP_VERSION'),
            ];
            echo json_encode($response);
        } else {
            $Customer = $Customer->first();
            $PriceBookId = $Customer->PriceBookId;
            if (!$PriceBookId) {
                $response = [
                    'success' => false,
                    'error_message' => "Price book has not linked",
                    'error_code' => "206",
                    'ApiVersion' => env('APP_VERSION'),
                ];
                echo json_encode($response);
            } else {

                if ($OrderId) {
                    $ActiveProduct = Product::select('tbl_products.*', 'tbl_product_family.Name as Family', 'tbl_unit_of_measurement.MeasurementName as Unit', 'tbl_gst_slab.Name as GST', 'tbl_price_book_entry.ListPrice as ListPrice', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
                        ->leftJoin('tbl_admin', 'tbl_products.Updated_by', '=', 'tbl_admin.UserId')
                        ->leftJoin('tbl_product_family', 'tbl_products.Family', '=', 'tbl_product_family.id')
                        ->leftJoin('tbl_gst_slab', 'tbl_products.GstSlabId', '=', 'tbl_gst_slab.GstSlabId')
                        ->leftJoin('tbl_price_book_entry', 'tbl_products.ProductId', '=', 'tbl_price_book_entry.ProductId')
                        ->leftJoin('tbl_unit_of_measurement', 'tbl_products.Unit', '=', 'tbl_unit_of_measurement.id')
                        ->leftJoin('tbl_order_item', 'tbl_products.ProductId', '=', 'tbl_order_item.ProductId')
                        ->where('tbl_products.Status', '=', '1')
                        ->where('tbl_order_item.OrderId', '=', $OrderId)
                        ->get();

                    if ($ActiveProduct->count() > 0) {
                        foreach ($ActiveProduct as $key => $ProductValue) {
                            $ProductValue['CustomerId'] = $CustomerId;
                        }

                        if ($ActiveProduct->count() > 0) {
                            $s = 1;
                            $data = array();
                            foreach ($ActiveProduct as $key => $ProductValue) {
                                $ProductId = $ProductValue['ProductId'];
                                $ProductCode = $ProductValue['ProductCode'];
                                $ProductName = $ProductValue['ProductName'];
                                $ProductGST = $ProductValue['GST'];
                                $ProductName = $ProductValue['ProductName'];
                                $ListPrice = '';
                                if ($ProductId) {
                                    $PriceBookProduct = PriceBookEntry::select('ListPrice')
                                        ->where('Status', '=', '1')
                                        ->where('ProductId', '=', $ProductId)
                                        ->get()->first();
                                    if ($PriceBookProduct->count() > 0) {
                                        $PriceBookProduct = $PriceBookProduct->first();
                                        $ListPrice =  $PriceBookProduct->ListPrice;
                                    }
                                }

                                // $data[] = array('Sno'=>$s,'ProductId'=>$ProductId, 'ProductCode'=>$ProductCode, 'ProductName'=>$ProductName);

                                echo "<tr>

                                            <td>$s</td>
                                            <td>$ProductCode</td>
                                            <td>$ProductName</td>
                                            <td><input class='form-control form-control-sm'
                                                                                        id='quantity0' type='number' min='1'
                                                                                        name='quantity[]' maxlength='4' required></td>
                                                                                <td><input class='form-control form-control-sm'
                                                                                        id='price0' type='text' value='" . $ListPrice . "' name='price[]'
                                                                                        style='width:100%; border:none;' readonly></td>
                                                                                <td><input class='form-control form-control-sm'
                                                                                        id='salePrice0' type='text'
                                                                                        name='salePrice[]'
                                                                                        style='width:100%;' maxlength='8' required>
                                                                                </td>
                                                                                <td>
                                                                                    <div class='form-check form-check-inline'>
                                                                                        <input class='form-check-input' type='radio'
                                                                                            name='discountType' id='discountType'
                                                                                            value='flat' required>
                                                                                        <label class='form-check-label'
                                                                                            for='flat'>Flat</label>
                                                                                    </div>
                                                                                    <div class='form-check form-check-inline'>
                                                                                        <input class='form-check-input' type='radio'
                                                                                            name='discountType' id='discountType'
                                                                                            value='percentage' required>
                                                                                        <label class='form-check-label'
                                                                                            for='percentage'>Percentage</label>
                                                                                    </div>
                                                                                </td>
                                                                                <td><input class='form-control form-control-sm'
                                                                                        id='discount' type='text' name='discount[]'
                                                                                        style='width:100%;' required></td>
                                                                                <td><input class='form-control form-control-sm'
                                                                                        id='gst' type='text' value=' " . $ProductGST . "' name='gst[]'
                                                                                        style='width:100%;border:none;' readonly>
                                                                                </td>
                                                                                <td><input class='form-control form-control-sm'
                                                                                        id='grossTotal' type='text'
                                                                                        name='grossTotal[]'
                                                                                        style='width:100%; border:none;' readonly>
                                                                                </td>
                                        </tr>";
                                $s++;
                            }
                        }
                    } else {
                        echo "Product Detail Not Found ";
                    }
                } else {
                    $PriceBookEntry = PriceBookEntry::select('tbl_price_book_entry.*', 'tbl_price_book.PriceBookName', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by', 'tbl_products.*', 'tbl_product_family.Name as FamilyName')
                        ->leftJoin('tbl_admin', 'tbl_price_book_entry.Created_by', '=', 'tbl_admin.UserId')
                        ->leftJoin('tbl_price_book', 'tbl_price_book_entry.PriceBookId', '=', 'tbl_price_book.PriceBookId')
                        ->leftJoin('tbl_products', 'tbl_price_book_entry.ProductId', '=', 'tbl_products.ProductId')
                        ->leftJoin('tbl_product_family', 'tbl_products.Family', '=', 'tbl_product_family.id')
                        ->where('tbl_price_book_entry.IsDeleted', '=', '0')
                        ->where('tbl_price_book_entry.PriceBookId', '=', $PriceBookId)
                        ->get();

                    if ($PriceBookEntry->count() > 0) {
                        foreach ($PriceBookEntry as $key => $ProductValue) {
                            $ProductValue['CustomerId'] = $CustomerId;
                        }

                        if ($PriceBookEntry->count() > 0) {
                            $s = 1;
                            $data = array();
                            foreach ($PriceBookEntry as $key => $ProductValue) {
                                $ProductId = $ProductValue['ProductId'];
                                $ProductCode = $ProductValue['ProductCode'];
                                $ProductName = $ProductValue['ProductName'];

                                // $data[] = array('Sno'=>$s,'ProductId'=>$ProductId, 'ProductCode'=>$ProductCode, 'ProductName'=>$ProductName);

                                echo "<tr>
                                    <td><input type='checkbox' name='ProductId' id='ProductId' value = '" . $ProductId . " /></td>
                                    <td>$s</td>
                                    <td><input type='text' name='ProductCode' id='ProductCode' style='border:none' value='" . $ProductCode . "' readonly ></td>
                                    <td><input type='text' name='ProductCode' id='ProductCode' style='border:none'  value='" . $ProductName . "' readonly ></td>
                                </tr>";
                                $s++;
                            }
                        }
                    } else {
                        echo "Price Book Not Found ";
                    }
                }
            }
        }
    }


    // Temporary Store Product to Order Item on click Next button
    public function store(Request $request)
    {

        OrderItem::create($request->all());
        return json_encode(array(
            "statusCode" => 200
        ));
    }

    // Product detail list
    public function getOrderProductDetail($CustomerId = '', $OrderId = '')
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }


        if ($OrderId) {
            $ActiveProduct = Product::select('tbl_products.*', 'tbl_product_family.Name as Family', 'tbl_unit_of_measurement.MeasurementName as Unit', 'tbl_gst_slab.Name as GST', 'tbl_price_book_entry.ListPrice as ListPrice', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
                ->leftJoin('tbl_admin', 'tbl_products.Updated_by', '=', 'tbl_admin.UserId')
                ->leftJoin('tbl_product_family', 'tbl_products.Family', '=', 'tbl_product_family.id')
                ->leftJoin('tbl_gst_slab', 'tbl_products.GstSlabId', '=', 'tbl_gst_slab.GstSlabId')
                ->leftJoin('tbl_price_book_entry', 'tbl_products.ProductId', '=', 'tbl_price_book_entry.ProductId')
                ->leftJoin('tbl_unit_of_measurement', 'tbl_products.Unit', '=', 'tbl_unit_of_measurement.id')
                ->leftJoin('tbl_order_item', 'tbl_products.ProductId', '=', 'tbl_order_item.ProductId')
                ->where('tbl_products.Status', '=', '1')
                ->where('tbl_order_item.OrderId', '=', $OrderId)
                ->get();
        } else {
            $ActiveProduct = Product::select('tbl_products.*', 'tbl_product_family.Name as Family', 'tbl_unit_of_measurement.MeasurementName as Unit', 'tbl_gst_slab.Name as GST', 'tbl_price_book_entry.ListPrice as ListPrice', 'tbl_admin.FirstName as Updated_by', 'tbl_admin.FirstName as Created_by')
                ->leftJoin('tbl_admin', 'tbl_products.Updated_by', '=', 'tbl_admin.UserId')
                ->leftJoin('tbl_product_family', 'tbl_products.Family', '=', 'tbl_product_family.id')
                ->leftJoin('tbl_gst_slab', 'tbl_products.GstSlabId', '=', 'tbl_gst_slab.GstSlabId')
                ->leftJoin('tbl_price_book_entry', 'tbl_products.ProductId', '=', 'tbl_price_book_entry.ProductId')
                ->leftJoin('tbl_unit_of_measurement', 'tbl_products.Unit', '=', 'tbl_unit_of_measurement.id')
                ->where('tbl_products.Status', '=', '1')
                ->get();
        }





        if ($ActiveProduct->count() > 0) {
            foreach ($ActiveProduct as $key => $ProductValue) {
                $ProductValue['CustomerId'] = $CustomerId;
            }

            if ($ActiveProduct->count() > 0) {
                $s = 1;
                $data = array();
                foreach ($ActiveProduct as $key => $ProductValue) {
                    $ProductId = $ProductValue['ProductId'];
                    $ProductCode = $ProductValue['ProductCode'];
                    $ProductName = $ProductValue['ProductName'];
                    $ProductGST = $ProductValue['GST'];
                    $ListPrice = $ProductValue['ListPrice'];
                    $ProductName = $ProductValue['ProductName'];

                    // $data[] = array('Sno'=>$s,'ProductId'=>$ProductId, 'ProductCode'=>$ProductCode, 'ProductName'=>$ProductName);

                    echo "<tr>

                                <td>$s</td>
                                <td>$ProductCode</td>
                                <td>$ProductName</td>
                                <td><input class='form-control form-control-sm'
                                                                            id='quantity0' type='number' min='1'
                                                                            name='quantity[]' maxlength='4' maxlength='4'  required></td>
                                                                    <td><input class='form-control form-control-sm'
                                                                            id='price0' type='text' value='" . $ListPrice . "' name='price[]'
                                                                            style='width:100%; border:none;' readonly></td>
                                                                    <td><input class='form-control form-control-sm'
                                                                            id='salePrice0' type='text'
                                                                            name='salePrice[]'
                                                                            style='width:100%;' maxlength='8' required>
                                                                    </td>
                                                                    <td>
                                                                        <div class='form-check form-check-inline'>
                                                                            <input class='form-check-input' type='radio'
                                                                                name='discountType' id='discountType'
                                                                                value='flat' required>
                                                                            <label class='form-check-label'
                                                                                for='flat'>Flat</label>
                                                                        </div>
                                                                        <div class='form-check form-check-inline'>
                                                                            <input class='form-check-input' type='radio'
                                                                                name='discountType' id='discountType'
                                                                                value='percentage' required>
                                                                            <label class='form-check-label'
                                                                                for='percentage'>Percentage</label>
                                                                        </div>
                                                                    </td>
                                                                    <td><input class='form-control form-control-sm'
                                                                            id='discount' type='text' name='discount[]'
                                                                            style='width:100%;' required></td>
                                                                    <td><input class='form-control form-control-sm'
                                                                            id='gst' type='text' value=' " . $ProductGST . "' name='gst[]'
                                                                            style='width:100%;border:none;' readonly>
                                                                    </td>
                                                                    <td><input class='form-control form-control-sm'
                                                                            id='grossTotal' type='text'
                                                                            name='grossTotal[]'
                                                                            style='width:100%; border:none;' readonly>
                                                                    </td>
                            </tr>";
                    $s++;
                }
            }
        } else {
            echo "Product Detail Not Found ";
        }
    }

    public function addOrderProduct()
    {
        return view('admin.all-order');
    }

    public function AddOrderItem(Request $request)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $ProductIds = $request->input('ProductIds');
        $OrderId = $request->input('OrderId');
        $PriceBookId = $request->input('PriceBookId');
        if (count($ProductIds) > 0) {
            $oi = 0;
            for ($i = 0; $i < count($ProductIds); $i++) {
                $ProductId = $ProductIds[$i];

                $ProductName = '';
                if ($ProductId) {
                    $Products = Product::select('ProductName')
                        ->where('ProductId', '=', $ProductId)
                        ->get();

                    if ($Products->count() > 0) {
                        $Product = $Products->first();
                        $ProductName =  $Product->ProductName;
                    }
                }

                $OrderItems = OrderItem::select('*')
                    ->where('Status', '=', '1')
                    ->where('IsDeleted', '=', '0')
                    ->where('ProductId', '=', $ProductId)
                    ->where('OrderId', '=', $OrderId)
                    ->get();
                if ($OrderItems->count() > 0) {
                    //$oi++;

                    $oidata = array();
                    $oidata['IsDeleted'] = '0';
                    $oidata['Status'] = '1';
                    $oidata['Name'] = $ProductName;
                    $oidata['OrderComingFrom'] = 'WEB';
                    $order_insert = OrderItem::where('OrderId', $OrderId)->where('ProductId', $ProductId)->update($oidata);
                    if ($order_insert) {
                        $oi++;
                    }
                } else {



                    $oidata = array();
                    $oidata['OrderItemId'] = $this->userLib->useridGenrator();
                    $oidata['OrderId'] = $OrderId;
                    $oidata['ProductId'] = $ProductId;
                    $oidata['Name'] = $ProductName;
                    $oidata['IsDeleted'] = '0';
                    $oidata['Status'] = '1';
                    $oidata['OrderComingFrom'] = 'WEB';
                    $oidata['LastModifiedDate'] = date('Y-m-d H:i:s', time());
                    $oidata['LastReferencedDate'] = date('Y-m-d H:i:s', time());
                    $oidata['LastViewedDate'] = date('Y-m-d H:i:s', time());
                    $oidata['CreatedDate'] = date('Y-m-d H:i:s', time());
                    $oidata['Updated_at'] = date('Y-m-d H:i:s', time());
                    $order_insert = OrderItem::insert($oidata);
                    if ($order_insert) {
                        $oi++;
                    }
                }
            }

            //    echo $oi ." == ". count($ProductIds);

            if ($oi == count($ProductIds)) {
                // echo "200";
                $PIds = implode(', ', $ProductIds);

                // $ActiveProduct = Product::select('tbl_products.*', 'tbl_product_family.Name as Family', 'tbl_gst_slab.Name as GST', 'tbl_price_book_entry.ListPrice as ListPrice')
                // ->leftJoin('tbl_product_family', 'tbl_products.Family', '=', 'tbl_product_family.id')
                // ->leftJoin('tbl_gst_slab', 'tbl_products.GstSlabId', '=', 'tbl_gst_slab.GstSlabId')
                // ->leftJoin('tbl_price_book_entry', 'tbl_products.ProductId', '=', 'tbl_price_book_entry.ProductId')
                // ->where('tbl_products.Status', '=', '1')
                // ->whereIn('tbl_products.ProductId', $ProductIds)
                // ->groupBy('tbl_products.ProductName')
                // ->get();

                //echo 'PriceBookID =' .$PriceBookId;

                $ActiveProduct = Product::select('tbl_products.*', 'tbl_gst_slab.Name as GST', 'tbl_price_book_entry.ListPrice as ListPrice')
                    ->leftJoin('tbl_gst_slab', 'tbl_products.GstSlabId', '=', 'tbl_gst_slab.GstSlabId')
                    ->leftJoin('tbl_price_book_entry', 'tbl_products.ProductId', '=', 'tbl_price_book_entry.ProductId')
                    ->where('tbl_products.Status', '=', '1')
                    ->where('tbl_price_book_entry.PriceBookId', $PriceBookId)
                    ->whereIn('tbl_products.ProductId', $ProductIds)
                    ->get();


                if ($ActiveProduct->count() > 0) {

                    $s = 1;
                    $data = array();
                    foreach ($ActiveProduct as $key => $ProductValue) {
                        $ProductId = $ProductValue['ProductId'];
                        $ProductCode = $ProductValue['ProductCode'];
                        $ProductName = $ProductValue['ProductName'];
                        $ProductGST = $ProductValue['GST'];
                        $ListPrice = $ProductValue['ListPrice'];

                        $gstAmount = ($ListPrice * $ProductGST)/100;
                        $grossTotal = $ListPrice + $gstAmount;
                        //$ProductName = $ProductValue['ProductName'];

                        // $data[] = array('Sno'=>$s,'ProductId'=>$ProductId, 'ProductCode'=>$ProductCode, 'ProductName'=>$ProductName);

                        echo "<tr id='" . $ProductId . "'>

                                    <td>$s</td>
                                    <td>$ProductCode</td>
                                    <td><input class='form-control form-control-sm tbl_productname'
                                    id='productname_" . $ProductId . "' data-productid='" . $ProductId . "' type='text' value='" . $ProductName . "' name='ProductName[]' style='width:100%;border:none;' readonly></td>
                                    <td><input class='form-control form-control-sm tbl_quantity' data-productid='" . $ProductId . "'
                                    id='quantity_" . $ProductId . "' type='number' onkeyup='onlyNumbers(this)' min='1' max='1000' value='1' step='1' name='Quantity' maxlength='4' required></td>
                                                                        <td><input class='form-control form-control-sm tbl_price'
                                                                        data-productid='" . $ProductId . "'
                                                                                id='price_" . $ProductId . "' type='text' value='" . $ListPrice . "' name='Price'
                                                                                style='width:100%; border:none;' readonly></td>
                                                                        <td><input class='form-control form-control-sm tbl_sale_price'
                                                                        id='sale_price_" . $ProductId . "'
                                                                        data-productid='" . $ProductId . "'
                                                                        type='text'
                                                                                name='SalePrice'
                                                                                style='width:100%;' value='" . $ListPrice . "' onkeyup='if(this.value<0){this.value= this.value * -1}' maxlength='8' required>
                                                                        </td>
                                                                        <td>
                                                                            <div class='form-check form-check-inline'>
                                                                                <input class='form-check-input tbl_discount_type' type='radio'
                                                                                     id='discount_type_flat_" . $ProductId . "'
                                                                                    data-productid='" . $ProductId . "'
                                                                                    value='flat' name='DiscountType_" . $ProductId . "' checked required>
                                                                                <label class='form-check-label'
                                                                                    for='flat'>Flat</label>&nbsp;&nbsp;
                                                                                    <input class='form-check-input tbl_discount_type' type='radio'
                                                                                     id='discount_type_percentage_" . $ProductId . "'
                                                                                    data-productid='" . $ProductId . "'
                                                                                    value='percentage' name='DiscountType_" . $ProductId . "' required>
                                                                                <label class='form-check-label'
                                                                                    for='percentage'>Percent</label>
                                                                            </div>

                                                                        </td>
                                                                        <td><input class='form-control form-control-sm tbl_discount'
                                                                        id='discount_" . $ProductId . "'
                                                                        data-productid='" . $ProductId . "'
                                                                        type='number' min='0' step='1' name='Discount'
                                                                                style='width:100%;' onkeyup='if(this.value<0){this.value= this.value * -1}' value='0' required></td>
                                                                        <td><input class='form-control form-control-sm tbl_gst'
                                                                        id='gst_" . $ProductId . "' data-productid='" . $ProductId . "' type='text' value=' " . $ProductGST . "' name='gst[]'
                                                                                style='width:100%;border:none;' readonly>
                                                                        </td>
                                                                        <td><input class='form-control form-control-sm tbl_gross_total'
                                                                        id='gross_total_" . $ProductId . "'
                                                                        data-productid='" . $ProductId . "'
                                                                        type='text' value=' " . $grossTotal . "' name='grossTotal[]' style='width:100%; border:none;' readonly>
                                                                        </td>
                                                                        <td><input class='btn btn-success btn-sm btn_item_submit' value='Add'
                                                                        data-productid='" . $ProductId . "' id='submit_" . $ProductId . "'
                                                                        type='button' onclick='btnItemSubmit(this)'>
                                                                        </td>
                                </tr>";
                        $s++;
                    }
                } else {
                    echo "Product Detail Not Found ";
                }
            } else {
                echo "201";
            }
        }
    }

    #### Store Order Item
    public function StoreOrderItem(Request $request)
    {
        // if (empty(session('UserId'))) {
        //     return redirect('/admin/logout');
        // }

        $token = $request->get('_token');

        $orderData = $request->get('orderData');
        $data = json_decode($orderData, true);
        $data = json_decode($data, true);

        $OrderId = $data['OrderId'];


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

        $data['OrderItemId'] = $g_OrderItemId;
        $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());
        $data['LastModifiedDate'] = date('Y-m-d H:i:s', time());
        $data['LastReferencedDate'] = date('Y-m-d H:i:s', time());
        $data['LastViewedDate'] = date('Y-m-d H:i:s', time());
        $data['CreatedDate'] = date('Y-m-d H:i:s', time());
        // print_r($data);exit;

        $store_order_item = OrderItem::insert($data);

        // $OrderItemId = $g_OrderItemId;
        // $OrderId = $data['OrderId'];
        // $ProductId = $data['ProductId'];
        // $ListPrice = $data['ListPrice'];
        // $SalePrice = $data['SalePrice'];
        // $Quantity = $data['Quantity'];
        // $TotalPrice = $data['TotalPrice'];
        // $DiscountType = $data['DiscountType'];
        // $Discount = $data['Discount'];
        // $DiscountInRupees = $data['DiscountInRupees'];
        // $SubTotal = $data['SubTotal'];
        // $GSTInRupees = $data['GSTInRupees'];
        // $AmountWithGST = $data['AmountWithGST'];
        // $GstSlab = $data['GstSlab'];
        // $IsDeleted = $data['IsDeleted'];
        // $Status = $data['Status'];
        // $Created_by = $data['Created_by'];
        // $Created_at = $data['Created_at'];
        // $Updated_by = $data['Updated_by'];
        // $Updated_at = $data['Updated_at'];

        // DB::connection('pgsql')->insert("insert into salesforce.OrderItem (External_Order_Item_Id__c,Order_Id__c,Product_Id__c,List_Price__c,Sale_Price__c,Quantity,Total_Price__c,Discount_Type__c,Discount__c,Discount_In_Rupees__c,Sub_Total__c,GST_In_Rupees__c,Amount_With_GST__c,Gst_Slab__c,IsDeleted,Status__c,UnitPrice) values ('$OrderItemId','$OrderId','$ProductId','$ListPrice','$SalePrice','$Quantity','$TotalPrice','$DiscountType','$Discount','$DiscountInRupees','$SubTotal','$GSTInRupees','$AmountWithGST','$GstSlab','$IsDeleted','$Status','$ListPrice')");


        if ($store_order_item) {
            // Update Total Order Item Amount in Order Table

            $OrderItem = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0');
            $OrderItemCount = $OrderItem->count();

            $TotalAmount = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("SubTotal");
            $SubTotal = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("TotalPrice");
            $DiscountInRupees = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("DiscountInRupees");
            $TaxAmount = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("GSTInRupees");
            $GrandTotal = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("AmountWithGST");

            $OrderData['TotalGST'] = $TaxAmount;
            $OrderData['SubTotal'] = $SubTotal;
            $OrderData['TotalAmount'] = $TotalAmount;
            $OrderData['TotalDiscount'] = $DiscountInRupees;
            $OrderData['GrandTotal'] = $GrandTotal;
            $OrderData['CountOrderItem'] = $OrderItemCount;
            $OrderData['Updated_by'] = session('UserId');
            $OrderData['Updated_at'] = date('Y-m-d H:i:s', time());

            $update_order = Order::where('OrderId', $OrderId)->update($OrderData);

            $Sales_TotalGST = $TaxAmount;
            $Sales_SubTotal = $SubTotal;
            $Sales_TotalAmount = $TotalAmount;
            $Sales_TotalDiscount = $DiscountInRupees;
            $Sales_GrandTotal = $GrandTotal;
            $Sales_CountOrderItem = $OrderItemCount;

            DB::connection('pgsql')->update("update salesforce.Order set Total_GST__c='$Sales_TotalGST',Sub_Total__c='$Sales_SubTotal',Total_Amount__c='$Sales_TotalAmount',Total_Discount__c='$Sales_TotalDiscount',Grand_Total__c='$Sales_GrandTotal',Count_Order_Item__c='$Sales_CountOrderItem' where order_id__c='$OrderId'");

            if ($update_order) {
                return response()->json('status_success');
            } else {
                echo '0';
            }

            //return response()->json('status_success');
            return response()->json('status_success');
        }
    }

    #### Delete Temporary Order Item
    public function deleteOrderItem($id)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $CreatedDate = date('Y-m-d H:i:s', time());

        $GetOrderId = OrderItem::select('tbl_order_item.*')
            ->where('OrderItemId', $id)
            ->get()
            ->first();
        $OrderId = $GetOrderId->OrderId;

        // $value = array();
        // $value['Updated_at'] = $CreatedDate;
        // $value['Updated_by'] = session('UserId');
        // $value['IsDeleted'] = '1';
        $delete_temp = OrderItem::where('OrderItemId', $id)->delete();

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

        if ($delete_temp) {
            // Update Total Order Item Amount in Order Table

            $OrderItem = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0');
            $OrderItemCount = $OrderItem->count();

            $TotalAmount = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("SubTotal");
            $SubTotal = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("TotalPrice");
            $DiscountInRupees = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("DiscountInRupees");
            $TaxAmount = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("GSTInRupees");
            $GrandTotal = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("AmountWithGST");

            $OrderData['TotalGST'] = $TaxAmount;
            $OrderData['SubTotal'] = $SubTotal;
            $OrderData['TotalAmount'] = $TotalAmount;
            $OrderData['TotalDiscount'] = $DiscountInRupees;
            $OrderData['GrandTotal'] = $GrandTotal;
            $OrderData['CountOrderItem'] = $OrderItemCount;
            $OrderData['Updated_by'] = session('UserId');
            $OrderData['Updated_at'] = date('Y-m-d H:i:s', time());

            $update_order = Order::where('OrderId', $OrderId)->update($OrderData);

            $Sales_TotalGST = $TaxAmount;
            $Sales_SubTotal = $SubTotal;
            $Sales_TotalAmount = $TotalAmount;
            $Sales_TotalDiscount = $DiscountInRupees;
            $Sales_GrandTotal = $GrandTotal;
            $Sales_CountOrderItem = $OrderItemCount;

            DB::connection('pgsql')->update("update salesforce.Order set Total_GST__c='$Sales_TotalGST',Sub_Total__c='$Sales_SubTotal',Total_Amount__c='$Sales_TotalAmount',Total_Discount__c='$Sales_TotalDiscount',Grand_Total__c='$Sales_GrandTotal',Count_Order_Item__c='$Sales_CountOrderItem' where order_id__c='$OrderId'");

            if ($update_order) {
                return response()->json('status_success');
            } else {
                echo '0';
            }

            return response()->json('status_success');
        }
    }

    ### Edit Order Item
    public function editOrderItem($id)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $OrderItem = OrderItem::select('tbl_order_item.*', 'tbl_products.ProductName as ProductName', 'tbl_products.ProductCode as ProductCode')
            ->where('OrderItemId', '=', $id)
            ->leftJoin('tbl_products', 'tbl_products.ProductId', '=', 'tbl_order_item.ProductId')
            ->get()
            ->first();
        return response()->json([
            'status' => 200,
            'OrderItem' => $OrderItem,
        ]);
    }

    ### Update Order Items
    public function updateOrderItem(Request $request)
    {
        if (empty(session('UserId'))) {
            return redirect('/admin/logout');
        }
        $CreatedDate = date('Y-m-d H:i:s', time());
        $item_id =  $request->input('OrderItemId');
        $OrderId =  $request->input('OrderId');
        $data['Name'] = $request->input('productName');
        $data['Quantity'] = $request->input('quantity');
        $data['SalePrice'] = $request->input('salePrice');
        $data['DiscountType'] = $request->input('discountType');
        $data['Discount'] = $request->input('discount');
        $data['DiscountInRupees'] = $request->input('discountedAmount');
        $data['TotalPrice'] = $request->input('SubTotal');
        $data['GSTInRupees'] = $request->input('TaxAmount');
        $data['AmountWithGST'] = $request->input('grossTotal');

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

        $item_update = OrderItem::where('OrderItemId', $item_id)->update($data);

        $Quantity = $request->input('quantity');
        $SalePrice = $request->input('salePrice');
        $DiscountType = $request->input('discountType');
        $Discount = $request->input('discount');
        $DiscountInRupees = $request->input('discountedAmount');
        $TotalPrice = $request->input('SubTotal');
        $GSTInRupees = $request->input('TaxAmount');
        $AmountWithGST = $request->input('grossTotal');

        DB::connection('pgsql')->update("update salesforce.OrderItem set Quantity='$Quantity',Sale_Price__c='$SalePrice',Discount_Type__c='$DiscountType',Discount__c='$Discount',Discount_In_Rupees__c='$DiscountInRupees',Total_Price__c='$TotalPrice',GST_In_Rupees__c='$GSTInRupees',Amount_With_GST__c='$AmountWithGST' where External_Order_Item_Id__c='$item_id'");

        if ($item_update) {

            // Update Total Order Item Amount in Order Table

            $OrderItem = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0');
            $OrderItemCount = $OrderItem->count();

            $TotalAmount = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("SubTotal");
            $SubTotal = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("TotalPrice");
            $DiscountInRupees = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("DiscountInRupees");
            $TaxAmount = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("GSTInRupees");
            $GrandTotal = OrderItem::all()
                ->where('OrderId', '=', $OrderId)
                ->where('Quantity', '!=', '0')
                ->where('IsDeleted', '=', '0')
                ->sum("AmountWithGST");

            $OrderData['TotalGST'] = $TaxAmount;
            $OrderData['SubTotal'] = $SubTotal;
            $OrderData['TotalAmount'] = $TotalAmount;
            $OrderData['TotalDiscount'] = $DiscountInRupees;
            $OrderData['GrandTotal'] = $GrandTotal;
            $OrderData['CountOrderItem'] = $OrderItemCount;
            $OrderData['Updated_by'] = session('UserId');
            $OrderData['Updated_at'] = date('Y-m-d H:i:s', time());

            $update_order = Order::where('OrderId', $OrderId)->update($OrderData);

            $Sales_TotalGST = $TaxAmount;
            $Sales_SubTotal = $SubTotal;
            $Sales_TotalAmount = $TotalAmount;
            $Sales_TotalDiscount = $DiscountInRupees;
            $Sales_GrandTotal = $GrandTotal;
            $Sales_CountOrderItem = $OrderItemCount;

            DB::connection('pgsql')->update("update salesforce.Order set Total_GST__c='$Sales_TotalGST',Sub_Total__c='$Sales_SubTotal',Total_Amount__c='$Sales_TotalAmount',Total_Discount__c='$Sales_TotalDiscount',Grand_Total__c='$Sales_GrandTotal',Count_Order_Item__c='$Sales_CountOrderItem' where order_id__c='$OrderId'");

            if ($update_order) {
                return response()->json('status_success');
            } else {
                echo '0';
            }

            return response()->json('status_success');
        } else {
            echo '0';
        }
    }
}