<?php

namespace App\Http\Controllers\Sales;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\AcReceipt;
use App\Models\EnquirySource;
use App\Models\PaymentTerm;
use App\Models\Product;
use App\Models\ProductBrand;
use App\Models\ProductCategory;
use App\Models\ProductPrice;
use App\Models\ProductTestPackage;
use App\Models\SaleInvoice;
use App\Models\SaleInvoiceBatch;
use App\Models\SaleInvoiceDetail;
use App\Models\SaleInvoiceSubDetails;
use App\Models\SpecialCase;
use App\Models\TaskStatus;

use App\Models\VoucherMaster;
use App\Models\VoucherType;
use App\Traits\BillingConceptTrait;
use App\Traits\TransactionSummeryTrait;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class IpdSalesOrdersController extends Controller
{
    use TransactionSummeryTrait,BillingConceptTrait;
    protected $mainFolder = 'sale';
    protected $subFolder  = 'ipd-sale-orders';
    protected $folderUrl ;

    public function __construct()
    {
        $this->folderUrl = $this->mainFolder . '/' . $this->subFolder;

        $company         = \Session::get('company_data');
        $company_address = $company['companies_addresses'] ?? [];
        $timezone        = $company_address['time_zone'] ?? 'Asia/Kolkata';
        date_default_timezone_set($timezone);
    }

    public function index(Request $request)
    {
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());
        $sort_by        = $request->get('sortby') ?? 10;

        $data = SaleInvoiceBatch::select('sale_invoice_batches.*','sale_invoices.id as sale_invoice_id')
        ->leftJoin('sale_invoices','sale_invoices.id','sale_invoice_batches.invoice_id')
        ->whereNull('sale_invoices.deleted_at')
        ->where('sale_invoice_batches.referrence_voucher_type','SALES')
        ->when(!in_array('Admin',\Auth()->user()->roles->pluck('name')->all()), function($query) {
            $query->where('sale_invoices.operator_id', \Auth()->id())
                ->where('sale_invoices.company_id', \Auth()->user()->company_id);
        })
        ->when(in_array('Admin',\Auth()->user()->roles->pluck('name')->all()), function($query) {
            $query->where('sale_invoices.company_id', \Auth()->user()->company_id);
        })
        ->groupBy('sale_invoice_batches.id')
        ->orderBy('sale_invoice_batches.created_at','desc');

        if ($request->ajax()) {
                
                $sort_type      = $request->get('sorttype');
                $search_query   = $request->get('query');
                $search_type    = $request->get('search_type');
                $status         = $request->get('status');
                $from_date       = isset($request->from_date) && $request->from_date!='' && $request->from_date!=null ? date('Y-m-d',strtotime($request->from_date)):'';
               
                // \DB::enableQueryLog();
                // dd( $from_date);
               

                
                if(isset($from_date) && $from_date!=''){
                    $data = $data->whereHas('getSaleInvoice', function ($query) use ($from_date) {
                        $query->whereDate('sale_invoices.invoice_date', $from_date);
                    });
                    
                }

                $data = $data->when(!empty($search_query) && !empty($search_type),function ($query) use ($search_query, $search_type) {
                        if ($search_type == 'main_invoice_no') {
                            $query->whereHas('getSaleInvoice', function ($contacts) use ($search_query) {
                                $contacts->where('main_invoice_no', 'like', '%' . $search_query . '%');
                            });
                        } else if ($search_type == 'patient_name') {
                            $query->whereHas('getSaleInvoice.getPatient', function ($contacts) use ($search_query) {
                                $contacts->where('name', 'like', '%' . $search_query . '%');
                            });
                        } else if ($search_type == 'dr_name') {
                            $query->whereHas('getSaleInvoice.getDoctor', function ($contacts) use ($search_query) {
                                $contacts->where('name', 'like', '%' . $search_query . '%');
                            });
                        } else if ($search_type == 'invoice_batch_no') {
                            $query->where('invoice_batch_no', 'like', '%' . $search_query . '%');
                        }
                    }
                );

                $data = $data->when(!empty($status),function ($query) use ($status) {
                    $query->where('batch_status', $status);

                });

                $data=$data->paginate($sort_by);

                return view($this->folderUrl.'.table', compact('data','companyDateFormate'));
            } else {
                $data=$data->paginate($sort_by);
                return view($this->folderUrl.'.index',compact('data','companyDateFormate'));
            }
    }

    public function invoice($id,$batch_id)
    {
        $sale_invoice = SaleInvoice::select('sale_invoices.*')
        ->with([
            'getSaleInvoiceDetails' => function($query) use ($batch_id) {
                $query->where('batch_id', $batch_id);
            },
            'getSaleInvoiceDelivery',
            'getPatient',
            'getPaymentTerm',
            'getCompany',
            'getBatchs'
        ])
        ->where('sale_invoices.id', $id)
        ->first();

        if (!$sale_invoice) {
            return redirect()->route('ipd-billings.index')->with('error', 'Invoice not found');
        }

        $voucher_type = VoucherType::with('voucherSeries')->where('code', 'SALES')->first();

        $transactionHistory = $this->transactionHistory($id, 'IPD_INVOICE');
        $transactionSummery = $this->TransactionSummeryBatchWise($id, 'IPD_INVOICE',$batch_id);

        return view($this->folderUrl.'.invoice', compact('sale_invoice', 'voucher_type', 'transactionSummery', 'transactionHistory'));
    }

    public function edit($id, $batch_id)
    {
        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode     = $country_code->country_code ?? 'us';
        $productCategory = ProductCategory::select(['id', 'name', 'is_default'])->where(['status' => 1])->get();
        $brands          = ProductBrand::select(['id', 'name', 'is_default'])->where(['status' => 1])->get();
        $salesInvoiceBatch = SaleInvoiceBatch::with('getSaleInvoice')
                            ->with('getSaleInvoiceDetails')
                            ->where(['invoice_id' => $id, 'id' => $batch_id])->first();
        $sale_invoice    = $salesInvoiceBatch->getSaleInvoice;
        $voucherTypeCode = $salesInvoiceBatch->referrence_voucher_type??'';
        $batchVoucherType = VoucherType::select('id')->where(['code'=>$voucherTypeCode,'status'=>1])->first();
        $data            = [];
        $patient         = $doctor = $collection_agent = $refferal_lab = '';

        if ($sale_invoice) {
            $data['patient_id']             = $sale_invoice->patient_id;
            $data['doctor_id']              = $sale_invoice->doctor_id;
            $data['refferal_id']            = $sale_invoice->refferal_lab_id;
            $data['collection_id']          = $sale_invoice->collection_agent_id;
            $data['voucher_type_id']        = $batchVoucherType->id??'';
            $data['special_discount']       = $sale_invoice->discount_amount;
            $data['amount_recieved']        = $sale_invoice->received_amount;
            $data['due_balance_amount']     = $sale_invoice->due_amount;
            $data['discount_type']          = 'FLAT';
            $data['sample_receive_time']    = $sale_invoice->sample_receive_time;
            $data['invoice_date']           = $sale_invoice->invoice_date;
            $data['sample_receive_date']    = $sale_invoice->sample_receive_date;
            $data['payment_mode_id']        = $sale_invoice->payment_mode_id;
            $data['payment_term_id']        = $sale_invoice->payment_term_id;
            $data['special_case']           = $sale_invoice->special_case_id;
            $data['sample_barcode']         = $sale_invoice->sample_barcode;
            $data['reff_no']                = $sale_invoice->reff_no;
            $data['sale_remarks']           = $sale_invoice->remarks;
            $data['remarks_for_technician'] = $sale_invoice->remarks_for_technician;
            $totalBillingAmount = 0;

            $saleVoucher = VoucherType::select(['default_price_type'])->where(['code'=>'SALES'])->first();
            if($saleVoucher->default_price_type=='MRP')
            {
                $productPrice ='product_prices.mrp as mrp';
            }
            elseif($saleVoucher->default_price_type=='Purchase Price')
            {
                $productPrice ='product_prices.purchase_price as mrp';
            }
            elseif($saleVoucher->default_price_type=='WholeSale Price')
            {
                $productPrice ='product_prices.wholesale_price as mrp';
            }
            elseif($saleVoucher->default_price_type=='Discounted/Sale Price(DP)')
            {
                $productPrice ='product_prices.sale_price as mrp';
            }
            elseif($saleVoucher->default_price_type=='Min. Sale Price')
            {
                $productPrice ='product_prices.min_sale_price as mrp';
            }
            elseif($saleVoucher->default_price_type=='Manufacturing Cost')
            {
                $productPrice ='product_prices.mfg_cost as mrp';
            }

            $productMrp    = 0;
            $ActualRateAfterTax = 0;
            $ActualRateBeforeTax = 0;
            $totalAmount = 0;

            foreach ($salesInvoiceBatch->getSaleInvoiceDetails as $key => $value) {

                $productPriceData = ProductPrice::select('exp_date',$productPrice)->find($value->product_price_id);
                if (!$productPriceData) {
                    continue;
                }

                $product_price = $productPriceData->mrp;
                $flat_discount = 0;
                $per_discount = $value->discount_percentage;

                if ($product_price > 0) {
                    if ($flat_discount != '' && $flat_discount != 0) {
                        $per_discount  = ($flat_discount / $product_price) * 100;
                        $amount        = $product_price - $flat_discount;
                        $flat_discount = $flat_discount;
                    } else if ($per_discount != '' && $per_discount != 0) {
                        $flat_discount = ($per_discount / 100) * $product_price;
                        $per_discount  = $per_discount;
                        $amount        = $product_price - $flat_discount;
                    } else {
                        $amount        = $product_price;
                    }
                }

                $product_price = $amount ?? $product_price;


                $totalAmount += $value->total_amount;
                $main_qty = $value->main_qty > 0 ? $value->main_qty : ($value->alt_qty > 0 ? $value->alt_qty : 1);
                $main_qty_amount = $main_qty * $productPriceData->mrp;

                $tax_per = $value->getProduct->getTaxMaster->name != 'Tax Free' ? preg_replace('/[^0-9]/', '', $value->getProduct->getTaxMaster->name ?? 0,) : 0;

                $tax  = (($tax_per ?? 0) / 100) * $main_qty_amount;

                /*************** Tax Calculation ***************** **/
                if ($value && $value->tax_calculation_type == 'EXCLUSIVE') {
                    $tax             = ($tax_per / 100) * $product_price; //(12/100)*1000;
                    $productMrp      = ($product_price + $tax) * $main_qty;  // 1000+
                    $basic_amount    = $productPriceData->mrp;  //1000

                    $ActualRateAfterTax = $product_price + $tax;
                    $ActualRateBeforeTax = $product_price * $main_qty;
                    $totalTax = $tax * $main_qty;
                } else {
                    $basic_amount    = $productPriceData->mrp / (($tax_per + 100) / 100);
                    $basePrice       = $product_price / (1 + ($tax_per / 100));
                    $tax             = $product_price - $basePrice;
                    $productMrp      = $product_price * $main_qty;
                    $ActualRateAfterTax = $product_price - $tax;
                    $ActualRateBeforeTax = $ActualRateAfterTax * $main_qty;
                    $totalTax = $tax * $main_qty;
                }


                $data['products'][] = array(
                    'brand_id'        => $value->getProduct->brand_id ?? '',
                    'batch'           => $value->item_batch,
                    'price_id'        => $value->product_price_id ?? '',
                    'product_id'      => $value->product_id ?? '',
                    'product'         => $value->getProduct->name ?? '',
                    'hsncode'         => $value->getProduct->hsncode ?? '',
                    'brand'           => $value->getProduct->getProductBrand->name ?? '',
                    'product_price'   => $basic_amount ?? '0',
                    'flat_discount'   => $value->discount_amount ?? '0',
                    'per_discount'    => $value->discount_percentage ?? '0',
                    'product_details' => $value->item_details ?? '',
                    'vial_code'       => '',
                    'amount'          => $productMrp ?? '0',
                    'order_qty'       => $value->main_qty ?? '0',
                    'main_qty'        => $value->main_qty ?? '0',
                    'tax_per'         => $tax_per,
                    'tax_flat'        => $totalTax ?? 0,
                    'product_mrp'     => convertDecimelPoint($ActualRateAfterTax) ?? '',
                    'product_basic'   => convertDecimelPoint($ActualRateBeforeTax) ?? '',
                    'expiry_date'     => isset($productPriceData->exp_date) ? date('M-Y', strtotime($productPriceData->exp_date)) : '',
                );
                $totalBillingAmount += $value->total_amount;
            }

            $data['amount']                 = $totalBillingAmount;
        }

        \Session::put('ipd_sale_order_billing_products_cart', $data);

        if ($sale_invoice && isset($sale_invoice->patient_id) && $sale_invoice->patient_id != '') {
            $patient = Account::getAccount([
                'account_types.type_code' => 'PATIENT',
                'accounts.id' => $sale_invoice->patient_id
            ]);
            if (isset($patient)) {
                $patient->full_name = $patient->name .
                    ($patient->code   != '' ? ', ' . $patient->code : '') .
                    ($patient->gender != '' ? ', ' . $patient->gender : '') .
                    ($patient->age    != '' ? ', ' . $patient->age . ' yrs' : '') .
                    ($patient->phone_no    != '' ? ', ' . $patient->phone_no : '');
            }
        }

        if ($sale_invoice && isset($sale_invoice->doctor_id) && $sale_invoice->doctor_id != '') {
            $doctor = Account::getAccount([
                'account_types.type_code' => 'DOCTOR',
                'accounts.id' => $sale_invoice->doctor_id
            ]);
            if (isset($doctor)) {
                $doctor->full_name = $doctor->name .
                    ($doctor->code   != '' ? ', ' . $doctor->code : '') .
                    ($doctor->gender != '' ? ', ' . $doctor->gender : '') .
                    ($doctor->age    != '' ? ', ' . $doctor->age . ' yrs' : '') .
                    ($doctor->phone_no    != '' ? ', ' . $doctor->phone_no : '');
            }
        }

        if ($sale_invoice && isset($sale_invoice->collection_id) && $sale_invoice->collection_id != '') {
            $collection_agent = Account::getAccount([
                'account_types.type_code' => 'COLLECTION_AGENT',
                'accounts.id' => $sale_invoice->collection_id
            ]);
            if (isset($collection_agent)) {
                $collection_agent->full_name = $collection_agent->name .
                    ($collection_agent->code   != '' ? ', ' . $collection_agent->code : '') .
                    ($collection_agent->gender != '' ? ', ' . $collection_agent->gender : '') .
                    ($collection_agent->age    != '' ? ', ' . $collection_agent->age . ' yrs' : '') .
                    ($collection_agent->phone_no    != '' ? ', ' . $collection_agent->phone_no : '');
            }
        }

        if ($sale_invoice && isset($sale_invoice->refferal_id) && $sale_invoice->refferal_id != '') {
            $refferal_lab = Account::getAccount([
                'account_types.type_code' => 'REFERRAL_PARTNER',
                'accounts.id' => $sale_invoice->refferal_id
            ]);
            if (isset($refferal_lab)) {
                $refferal_lab->full_name = $refferal_lab->name .
                    ($refferal_lab->code   != '' ? ', ' . $refferal_lab->code : '') .
                    ($refferal_lab->gender != '' ? ', ' . $refferal_lab->gender : '') .
                    ($refferal_lab->age    != '' ? ', ' . $refferal_lab->age . ' yrs' : '') .
                    ($refferal_lab->phone_no    != '' ? ', ' . $refferal_lab->phone_no : '');
            }
        }
        $voucher_master = VoucherMaster::with('voucherAllType')->select('id','tax_calculation')->where('voucher_code', 'SALES')->where(['status' => 1])->first();
        return view($this->folderUrl.'.edit', compact(
            'id',
            'batch_id',
            'brands',
            'doctor',
            'patient',
            'countryCode',
            'refferal_lab',
            'productCategory',
            'collection_agent',
            'voucher_master',
            'batchVoucherType'
        ));
    }


    public function cartProductRemove(Request $request)
    {
        $data = \Session::get('ipd_sale_order_billing_products_cart') ?? [];
        $id   = $request->id;

        $amount = $data['amount'];

        $data['products'] = array_filter($data['products'], function ($product) use ($id, &$data, &$amount) {
            if ($product['price_id'] == $id) {
                $amount = $data['amount'] - $product['amount'];
            }

            return $product['price_id'] != $id;
        });

        if (count($data['products']) == 0) {
            $data['amount'] = 0;
        } else {
            $data['amount'] = $amount;
        }

        if ($data['discount_type'] == 'FLAT') {
            $due_balance_amount = $data['amount'] - $data['special_discount'];
            $data['due_balance_amount'] = round($due_balance_amount - $data['amount_recieved']);
        } else {
            $flat_discount = ($data['special_discount'] / 100) * $data['amount'];
            $due_balance_amount = $data['amount'] - $flat_discount;
            $data['due_balance_amount'] = round($due_balance_amount - $data['amount_recieved']);
        }
        \Session::put('ipd_sale_order_billing_products_cart', $data);

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

    public function productAddToCart(Request $request)
    {

        $data = \Session::get('ipd_sale_order_billing_products_cart') ?? [];

        if (!isset($data['patient_id']) || $data['patient_id'] == '') {
            $data['patient_id'] = $request->patient_id;
        }
        if (!isset($data['doctor_id']) || $data['doctor_id'] == '') {
            $data['doctor_id'] = $request->doctor_id;
            //dd($request->doctor_id);
        }

        if (!isset($data['refferal_id']) || $data['refferal_id'] == '') {
            $data['refferal_id'] = $request->refferal_id ?? '';
        }

        if (!isset($data['collection_id']) || $data['collection_id'] == '') {
            $data['collection_id'] = $request->collection_id ?? '';
        }

        if (!isset($data['amount'])) {
            $data['amount'] = 0;
        }

        if (!isset($data['special_discount'])) {
            $data['special_discount'] = 0;
        }

        if (!isset($data['amount_recieved'])) {
            $data['amount_recieved'] = 0;
        }

        if (!isset($data['due_balance_amount'])) {
            $data['due_balance_amount'] = $data['amount'];
        }

        if (!isset($data['discount_type'])) {
            $data['discount_type'] = 'FLAT';
        }

        if (!isset($data['sample_receive_time'])) {
            $data['sample_receive_time'] = date('H:i:s');
        }

        if (!isset($data['invoice_date'])) {
            $data['invoice_date'] = date('Y-m-d');
        }

        if (!isset($data['sample_receive_date'])) {
            $data['sample_receive_date'] = date('Y-m-d');
        }

        if (!isset($data['voucher_type_id'])) {
            $data['voucher_type_id'] = $request->voucher_type_id??'';
        }

        $product = Product::select('products.id', 'products.name', 'products.hsncode', 'product_brands.name as brand', 'tax_masters.name as tax')
            ->leftjoin('product_brands', 'product_brands.id', 'products.brand_id')
            ->leftjoin('tax_masters', 'tax_masters.id', 'products.tax_slab_id')
            ->where('products.id', $request->search_product)
            ->first();
        // Check if the product already exists in the cart
        if (isset($data['products'])) {
            foreach ($data['products'] as $cart_product) {
                if ($cart_product['price_id'] == $request->price_id) {
                    return response()->json(['success' => true, 'data' => $data]);
                }
            }
        }

        $product_price = $request->product_price;
        $main_qty      = $request->main_qty > 0 ? $request->main_qty : 1;
        $loose_qty     = $request->loose_qty > 0 ? $request->loose_qty : 1;
        $flat_discount = $request->flat_discount ?? '0';
        $per_discount  = $request->per_discount ?? '0';
        $amount = '0';

        if ($product_price > 0) {
            if ($flat_discount != '' && $flat_discount != 0) {
                $per_discount  = $flat_discount / ($product_price * $request->main_qty) * 100;

                $flat_discount = (($per_discount / 100) * $product_price) * $request->main_qty;
                $flat_per_discount = (($per_discount / 100) * $product_price);
                $per_discount  = $per_discount;
                $amount        = $product_price - $flat_per_discount;
            } else if ($per_discount != '' && $per_discount != 0) {
                $flat_discount = (($per_discount / 100) * $product_price) * $request->main_qty;
                $flat_per_discount = (($per_discount / 100) * $product_price);
                $per_discount  = $per_discount;
                $amount        = $product_price - $flat_per_discount;
            } else {
                $amount        = $product_price;
            }
        }



        $productMrp = 0;
        $product_price = $amount ?? $product_price;

        $main_qty_amount = $main_qty * $product_price;
        $product_price  = number_format($product_price, 2, '.', '');

        $ActualRateAfterTax = 0;
        $ActualRateBeforeTax = 0;
        $totalTax            = 0;

        $tax_per = $product->tax == 'Tax Free' ? 0 : preg_replace('/[^0-9]/', '', $product->tax);


        $voucher_master = VoucherMaster::select('tax_calculation')->where('voucher_code', 'SALES')->where(['status' => 1])->first();

        if ($voucher_master && $voucher_master->tax_calculation == 'EXCLUSIVE') {
            $tax             = ($tax_per / 100) * $product_price; //(12/100)*1000;
            $productMrp      = ($product_price + $tax) * $main_qty;  // 1000+
            $basic_amount    = $request->product_price;  //1000
            $ActualRateAfterTax = $product_price + $tax;
            $ActualRateBeforeTax = $product_price * $main_qty;
            $totalTax = $tax * $main_qty;
        } else {
            $basic_amount    = $request->product_price / (($tax_per + 100) / 100);
            $basePrice       = $product_price / (1 + ($tax_per / 100));
            $tax             = $product_price - $basePrice;
            $productMrp      = $product_price * $main_qty;
            $ActualRateAfterTax = $product_price - $tax;
            $ActualRateBeforeTax = $ActualRateAfterTax * $main_qty;
            $totalTax = $tax * $main_qty;
        }



        $basic_amount      = number_format($basic_amount, 2, '.', '');
        $flat_discount     = number_format($flat_discount, 2, '.', '');
        $per_discount      = number_format($per_discount, 2, '.', '');
        $tax               = number_format($tax, 2, '.', '');
        $convertion_factor = !empty($product->convertion_factor) ? $product->convertion_factor : 1;

        $amount                     = $main_qty * $amount / $convertion_factor;
        $data_amount                = $data['amount'] ?? 0;
        $data['amount']             = $data_amount + $productMrp;
        $data['due_balance_amount'] = number_format($data['amount'], 2, '.', '');

        $data['products'][] = [
            'brand_id'        => $request->brand_id ?? '',
            'price_id'        => $request->price_id ?? '',
            'product_id'      => $request->search_product ?? '',
            'product'         => $product->name ?? '',
            'hsncode'         => $product->hsncode ?? '',
            'brand'           => $product->brand ?? '',
            'product_price'   => $basic_amount ?? '',
            'flat_discount'   => $flat_discount ?? '',
            'per_discount'    => $per_discount ?? '',
            'vial_code'       => '',
            'amount'          => $productMrp ?? '',
            'order_qty'       => $request->main_qty ?? '0',
            'main_qty'        => $request->main_qty ?? 1,
            'tax_per'         => $tax_per,
            'tax_flat'        => convertDecimelPoint($totalTax),
            'batch'           => $request->batch_name ?? '',
            'loose_qty'       => $request->main_qty > 0  ? 0 : $request->loose_qty ?? 0.00,
            'free_qty'        => $request->free_qty ?? '',
            'product_details' => $request->product_detail ?? '',
            'product_mrp'     => convertDecimelPoint($ActualRateAfterTax) ?? '',
            'product_basic'   => convertDecimelPoint($ActualRateBeforeTax) ?? '',
            'expiry_date'     => $request->expiry_date ? date('M-Y', strtotime($request->expiry_date)) : '',
        ];

       $test =  \Session::put('ipd_sale_order_billing_products_cart', $data);

       return response()->json(['success' => true, 'data' => $data]);
    }

    public function cartProductUpdate(Request $request)
    {
        $data = \Session::get('ipd_sale_order_billing_products_cart') ?? [];

        if (isset($request->type) && $request->type == 'billing') {
            if (isset($request->invoice_date)) {
                $data['invoice_date'] = date('Y-m-d', strtotime($request->invoice_date));
            }

            if (isset($request->payment_mode_id)) {
                $data['payment_mode_id'] = $request->payment_mode_id;
            }

            if (isset($request->payment_term_id)) {
                $data['payment_term_id'] = $request->payment_term_id;
            }

            if (isset($request->special_discount)) {
                $data['special_discount'] = $request->special_discount;
            }

            if (isset($request->discount_type)) {
                $data['discount_type'] = $request->discount_type;
            }

            if (isset($request->amount_recieved)) {
                $data['amount_recieved'] = $request->amount_recieved;
            }
            if (isset($request->voucher_type_id)) {
                $data['voucher_type_id'] = $request->voucher_type_id??'';
            }


            if (isset($request->special_discount) || isset($request->discount_type) || isset($request->amount_recieved)) {
                if (isset($data['discount_type']) && $data['discount_type'] == 'FLAT') {
                    $due_balance_amount = $data['amount'] - $data['special_discount'];
                    $data['due_balance_amount'] = round($due_balance_amount - $data['amount_recieved']);
                } else {
                    $flat_discount = ($data['special_discount'] / 100) * $data['amount'];
                    $due_balance_amount = $data['amount'] - $flat_discount;
                    $data['due_balance_amount'] = round($due_balance_amount - $data['amount_recieved']);
                }
            }
        } else {
            if (isset($data['products'])) {
                foreach ($data['products'] as $key => $value) {
                    $saleVoucher = VoucherType::select(['default_price_type'])->where(['code'=>'SALES'])->first();

                    if ($saleVoucher->default_price_type == 'MRP') {
                        $productPrice = 'product_prices.mrp as mrp';
                    } elseif ($saleVoucher->default_price_type == 'Purchase Price') {
                        $productPrice = 'product_prices.purchase_price as mrp';
                    } elseif ($saleVoucher->default_price_type == 'WholeSale Price') {
                        $productPrice = 'product_prices.wholesale_price as mrp';
                    } elseif ($saleVoucher->default_price_type == 'Discounted/Sale Price(DP)') {
                        $productPrice = 'product_prices.sale_price as mrp';
                    } elseif ($saleVoucher->default_price_type == 'Min. Sale Price') {
                        $productPrice = 'product_prices.min_sale_price as mrp';
                    } elseif ($saleVoucher->default_price_type == 'Manufacturing Cost') {
                        $productPrice = 'product_prices.mfg_cost as mrp';
                    }

                    $product = Product::select('products.id', 'products.name', 'products.hsncode', 'product_brands.name as brand', 'tax_masters.name as tax', 'product_prices.batch as batch', $productPrice)
                        ->leftjoin('product_brands', 'product_brands.id', 'products.brand_id')
                        ->leftjoin('tax_masters', 'tax_masters.id', 'products.tax_slab_id')
                        ->leftjoin('product_prices', 'products.id', 'product_prices.product_id')
                        ->where('product_prices.id', $value['price_id'])
                        ->where('products.id', $value['product_id'])
                        ->first();

                    $tax_per = $product->tax == 'Tax Free' ? 0 : preg_replace('/[^0-9]/', '', $product->tax);

                    $voucher_master = VoucherMaster::select('tax_calculation')
                        ->where('voucher_code', 'SALES')
                        ->where(['status' => 1])
                        ->first();
                        
                    if ($value['price_id'] == $request->id && isset($request->product_details)) {
                        $data['products'][$key]['product_details'] = $request->product_details;
                    }
                    if ($value['price_id'] == $request->id && isset($request->vial_code)) {
                        $data['products'][$key]['vial_code'] = $request->vial_code;
                    }

                    if ($value['price_id'] == $request->id && isset($request->loose_qty)) {
                        $data['products'][$key]['loose_qty'] = $request->loose_qty;
                    }

                    if ($value['price_id'] == $request->id) {
                        $data['amount'] = $data['amount'] - $value['amount'];

                        if (isset($request->main_qty)) {
                            $data['products'][$key]['main_qty']  = $request->main_qty;
                            $data['products'][$key]['loose_qty'] = 0;

                            $main_qty_amount = $request->main_qty * $product->mrp;
                            $product_price   = number_format($main_qty_amount, 2, '.', '');
                            $per_discount    = $value['per_discount'];

                        } elseif (isset($request->loose_qty) && $request->loose_qty > 0) {
                            $data['products'][$key]['loose_qty'] = $request->loose_qty;
                            $data['products'][$key]['main_qty']  = 0;

                            $main_qty_amount = $request->loose_qty * $product->mrp;
                            $product_price    = number_format($main_qty_amount, 2, '.', '');
                            $per_discount     = $value['per_discount'];
                        } else if (isset($request->per_discount) && !empty($request->per_discount)) {
                            $main_qty_amount = $data['products'][$key]['main_qty'] * $product->mrp;
                            $product_price   = number_format($main_qty_amount, 2, '.', '');
                            $per_discount    = $request->per_discount;
                        } else {
                            $main_qty_amount = $data['products'][$key]['main_qty'] * $product->mrp;
                            $product_price   = number_format($main_qty_amount, 2, '.', '');
                            $per_discount    = $value['per_discount'];
                        }

                        $product_price = $product->mrp;
                        $flat_discount = $request->flat_discount ?? '0';
                        $per_discount  = $request->per_discount ?? $data['products'][$key]['per_discount'];

                        $productMrp = $basic_amount = 0;

                        if ($product_price > 0) {
                            if ($flat_discount != '' && $flat_discount != 0) {
                                $per_discount  = $flat_discount / ($product_price * $data['products'][$key]['main_qty']) * 100;

                                $flat_discount = (($per_discount / 100) * $product_price) * $data['products'][$key]['main_qty'];
                                $flat_per_discount = (($per_discount / 100) * $product_price);
                                $per_discount  = $per_discount;
                                $amount        = $product_price - $flat_per_discount;
                            } else if ($per_discount != '' && $per_discount != 0) {

                                $flat_discount = (($per_discount / 100) * $product_price) * $data['products'][$key]['main_qty'];
                                $flat_per_discount = (($per_discount / 100) * $product_price);
                                $per_discount  = $per_discount;
                                $amount        = $product_price - $flat_per_discount;
                            } else {
                                $amount        = $product_price;
                            }
                        }

                        $product_price = $amount ?? $product_price;

                        if ($voucher_master && $voucher_master->tax_calculation == 'EXCLUSIVE') {
                            $tax   =  $flat_tax        = ($tax_per / 100) * $product_price; //(12/100)*1000;
                            $productMrp      = ($product_price + $tax) * $data['products'][$key]['main_qty'];  // 1000+
                            $basic_amount    = $data['products'][$key]['product_price'];  //1000

                            $ActualRateAfterTax = $product_price + $tax;
                            $ActualRateBeforeTax = $product_price * $data['products'][$key]['main_qty'];
                            $totalTax = $tax * $data['products'][$key]['main_qty'];
                        } else {
                            $basic_amount    = $product->mrp / (($tax_per + 100) / 100);
                            $basePrice       = $product_price / (1 + ($tax_per / 100));
                            $tax  =    $flat_tax       = $product_price - $basePrice;
                            $productMrp      = $product_price * $data['products'][$key]['main_qty'];
                            $ActualRateAfterTax = $product_price - $tax;
                            $ActualRateBeforeTax = $ActualRateAfterTax * $data['products'][$key]['main_qty'];
                            $totalTax = $tax * $data['products'][$key]['main_qty'];
                        }


                        $amount = ($basic_amount - $flat_discount);
                        $amount = number_format($amount, 2, '.', '');

                        $convertion_factor = !empty($product->convertion_factor) ? $product->convertion_factor : 1;
                        $amount            = $main_qty_amount * $amount / $convertion_factor;
                        $flat_discount     = number_format($flat_discount, 2, '.', '');
                        $flat_tax          = number_format($totalTax, 2, '.', '');
                        $data['products'][$key]['flat_discount'] = $flat_discount;
                        $data['products'][$key]['per_discount']  = $per_discount;
                        $data['products'][$key]['tax_flat']      = $flat_tax;
                        $data['products'][$key]['amount']        = $productMrp;
                        $data['products'][$key]['product_price'] = $basic_amount;
                        $data['products'][$key]['product_mrp']   = convertDecimelPoint($ActualRateAfterTax) ?? '';
                        $data['products'][$key]['product_basic'] = convertDecimelPoint($ActualRateBeforeTax) ?? '';
                        $data['amount']                          = $data['amount'] + $productMrp;
                        $due_balance_amount                      = $data['amount'] - $flat_discount;
                        $data['due_balance_amount']              = number_format($due_balance_amount - $data['amount_recieved'], 2, '.', '');
                    }



                    if ($value['price_id'] == $request->id && isset($request->product_price)) {

                        $data['amount'] = $data['amount'] - $value['amount'];
                        $product_price = $request->product_price;
                        $flat_discount = $request->flat_discount ?? '0';
                        $per_discount  = $request->per_discount ?? $data['products'][$key]['per_discount'];

                        $productMrp = $basic_amount = 0;

                        if ($product_price > 0) {
                            if ($flat_discount != '' && $flat_discount != 0) {
                                $per_discount  = $flat_discount / ($product_price * $data['products'][$key]['main_qty']) * 100;

                                $flat_discount = (($per_discount / 100) * $product_price) * $data['products'][$key]['main_qty'];
                                $flat_per_discount = (($per_discount / 100) * $product_price);
                                $per_discount  = $per_discount;
                                $amount        = $product_price - $flat_per_discount;
                            } else if ($per_discount != '' && $per_discount != 0) {

                                $flat_discount = (($per_discount / 100) * $product_price) * $data['products'][$key]['main_qty'];
                                $flat_per_discount = (($per_discount / 100) * $product_price);
                                $per_discount  = $per_discount;
                                $amount        = $product_price - $flat_per_discount;
                            } else {
                                $amount        = $product_price;
                            }
                        }

                        $product_price = $amount ?? $product_price;

                        if ($voucher_master && $voucher_master->tax_calculation == 'EXCLUSIVE') {
                            $tax   =  $flat_tax        = ($tax_per / 100) * $product_price; //(12/100)*1000;
                            $productMrp      = ($product_price + $tax) * $data['products'][$key]['main_qty'];  // 1000+
                            $basic_amount    = $request->product_price;  //1000

                            $ActualRateAfterTax = $product_price + $tax;
                            $ActualRateBeforeTax = $product_price * $data['products'][$key]['main_qty'];
                            $totalTax = $tax * $data['products'][$key]['main_qty'];
                        } else {
                            $basic_amount    = $request->product_price / (($tax_per + 100) / 100);
                            $basePrice       = $product_price / (1 + ($tax_per / 100));
                            $tax  =    $flat_tax       = $product_price - $basePrice;
                            $productMrp      = $product_price * $data['products'][$key]['main_qty'];
                            $ActualRateAfterTax = $product_price - $tax;
                            $ActualRateBeforeTax = $ActualRateAfterTax * $data['products'][$key]['main_qty'];
                            $totalTax = $tax * $data['products'][$key]['main_qty'];
                        }


                        $amount = ($basic_amount - $flat_discount);
                        $amount = number_format($amount, 2, '.', '');

                        $convertion_factor = !empty($product->convertion_factor) ? $product->convertion_factor : 1;
                        $amount            = $main_qty_amount * $amount / $convertion_factor;
                        $flat_discount     = number_format($flat_discount, 2, '.', '');
                        $flat_tax          = number_format($totalTax, 2, '.', '');
                        $data['products'][$key]['flat_discount'] = $flat_discount;
                        $data['products'][$key]['per_discount']  = $per_discount;
                        $data['products'][$key]['tax_flat']      = $flat_tax;
                        $data['products'][$key]['amount']        = $productMrp;
                        $data['products'][$key]['product_price'] = $basic_amount;
                        $data['products'][$key]['product_mrp']   = convertDecimelPoint($ActualRateAfterTax) ?? '';
                        $data['products'][$key]['product_basic'] = convertDecimelPoint($ActualRateBeforeTax) ?? '';
                        $data['amount']                          = $data['amount'] + $productMrp;
                        $due_balance_amount                      = $data['amount'] - $flat_discount;
                        $data['due_balance_amount']              = number_format($due_balance_amount - $data['amount_recieved'], 2, '.', '');
                    }
                }
            }

            if (isset($request->patient_id)) {
                $data['patient_id'] = $request->patient_id;
            }

            if (isset($request->doctor_id)) {
                $data['doctor_id'] = $request->doctor_id;
            }

            if (isset($request->refferal_id)) {
                $data['refferal_id'] = $request->refferal_id;
            }

            if (isset($request->collection_id)) {
                $data['collection_id'] = $request->collection_id;
            }
        }
        \Session::put('ipd_sale_order_billing_products_cart', $data);

        return response()->json(['success' => true, 'data' => $data]);
    }


    public function productCart(Request $request, $id = 0, $batch_id = null)
    {
        $page        = $request->page ?? '';
        $data        = \Session::get('ipd_sale_order_billing_products_cart') ?? [];
        return view($this->folderUrl.'.product-cart', compact('data', 'page', 'id', 'batch_id'));
    }

    public function editBilling($id, $batch_id)
    {
        $sale_invoice = SaleInvoice::find($id);

        if (!$sale_invoice) {
            $data = [];
            \Session::put('ipd_sale_order_billing_products_cart', $data);

            return redirect()->route('ipd-sale-orders.index')->with('error', 'IPD billing invoice not found!');
        }

        $data = \Session::get('ipd_sale_order_billing_products_cart') ?? [];

        if (empty($data) || !isset($data['products']) || count($data['products']) < 1) {
            $data = [];
            \Session::put('ipd_sale_order_billing_products_cart', $data);

            return redirect()->route('ipd-sale-orders.edit',['id'=>$id,'batch_id'=>$batch_id])->with('error', 'No product added in cart!');
        }

        $ids = [];

        $ids[] = $data['patient_id'] ?? 0;

        if (isset($data['doctor_id']) && $data['doctor_id'] != '') {
            $ids[] = $data['doctor_id'] ?? 0;
        }

        if (isset($data['refferal_id']) && $data['refferal_id'] != '') {
            $ids[] = $data['refferal_id'] ?? 0;
        }

        if (isset($data['collection_id']) && $data['collection_id'] != '') {
            $ids[] = $data['collection_id'] ?? 0;
        }

        $accounts = Account::select([
            'accounts.id',
            'accounts.account_type_id',
            'account_types.type_code',
            'account_contacts.phone_no as phone_no',
            \DB::raw("
                            CONCAT(
                                COALESCE(account_titles.name, ''),
                                CASE WHEN account_titles.name IS NOT NULL AND accounts.name IS NOT NULL THEN ' ' ELSE '' END,
                                COALESCE(accounts.name, '')
                            ) AS name
                            "),
            \DB::raw("account_contacts.phone_no as phone_no"),
            \DB::raw("genders.name as gender"),
            \DB::raw("account_contacts.date_of_birth")
        ])
            ->leftJoin('account_contacts', 'account_contacts.account_id', '=', 'accounts.id')
            ->leftJoin('account_titles', 'account_titles.id', '=', 'accounts.account_title_id')
            ->leftJoin('genders', 'genders.id', '=', 'account_contacts.account_gender_id')
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->whereIn('accounts.id', $ids)
            ->get();

        if (empty($accounts) || count($accounts) < 1) {
            $data = [];

            return redirect()->route('ipd-sale-orders.create', $id)->with('error', 'Empty cart!');
        }

        $doctors          = [];
        $patients         = [];
        $refferal_lab     = [];
        $collection_agent = [];

        foreach ($accounts as $item) {
            if ($item['type_code'] == 'PATIENT') {
                $patients = $item;
            } elseif ($item['type_code'] == 'DOCTOR') {
                $doctors = $item;
            } elseif ($item['type_code'] == 'REFERRAL_PARTNER') {
                $refferal_lab = $item;
            } elseif ($item['type_code'] == 'COLLECTION_AGENT') {
                $collection_agent = $item;
            }
        }

        $payment_types  = PaymentTerm::select(['id', 'is_default', 'payment_term_name'])
            ->orderBy('priority', 'ASC')
            ->get();

        $special_cases    = SpecialCase::select(['id', 'name'])->orderBy('priority', 'ASC')->get();
        $voucher_master   = VoucherMaster::select(['id', 'voucher_name'])->where('status', 1)->get();
        $bussiness_source = EnquirySource::select(['id', 'enquiry_source_name', 'default'])->where('status', '1')->get();

        $accounting_group = Account::select(['id', 'name', 'account_category_id', 'accounting_group_id'])
            ->with('chart_of_account_sub_type')
            ->where(function ($query) {
                $query->whereHas('chart_of_account_sub_type', function ($accounting_group) {
                    $accounting_group->where('is_payment_mode', '1');
                });
            })
            ->get();
        $AcReceipt = AcReceipt::where('voucher_id', $id)->get();
        $discount_group = Account::where(['code' => 'DISCOUNT_ALLOWED'])->first();
        $round_off      = Account::where(['code' => 'ROUN_OFF'])->first();

        $transactionSummery = $this->TransactionSummery($id, 'IPD_INVOICE');
        $transactionHistory = $this->transactionHistory($id, 'IPD_INVOICE');
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());

        return view($this->folderUrl.'.billing', compact([
            'id',
            'data',
            'doctors',
            'patients',
            'sale_invoice',
            'refferal_lab',
            'voucher_master',
            'collection_agent',
            'bussiness_source',
            'payment_types',
            'special_cases',
            'accounting_group',
            'AcReceipt',
            'discount_group',
            'round_off',
            'transactionSummery',
            'transactionHistory',
            'batch_id',
            'companyDateFormate'
        ]));
    }

    public function update(Request $request, $id, $batch_id)
    {
        $sale_invoice = SaleInvoice::find($id);

        if (!$sale_invoice) {
            $data = [];
            \Session::put('ipd_sale_order_billing_products_cart', $data);

            return redirect()->route('ipd-sale-orders.index')->with('error', 'IPD billing invoice not found!');
        }

        $data = \Session::get('ipd_sale_order_billing_products_cart') ?? [];

        if (empty($data)) {
            return redirect()->back()->with('error', 'Empty cart!');
        }
        $invoice_date        = $request->invoice_date != '' ? date('Y-m-d', strtotime($request->invoice_date)) : '';
        $sample_receive_date = $request->sample_receive_date != '' ? date('Y-m-d', strtotime($request->sample_receive_date)) : '';

        $sale_invoice_update  = [
            'payment_term_id'         => $request->payment_term_id,
            'billing_amount'          => $data['amount'],
            'patient_id'              => $data['patient_id'],
            'doctor_id'               => $data['doctor_id'],
            'collection_agent_id'     => $data['collection_id'],
            'refferal_lab_id'         => $data['refferal_id'],
            'reff_no'                 => $request->reff_no,
            'received_amount'         => $request->amount_recieved,
            'due_amount'              => $data['due_balance_amount'],
            'sample_barcode'          => $request->sample_barcode,
            'sample_receive_date'     => $sample_receive_date,
            'sample_receive_time'     => $request->sample_receive_time,
            'remarks_for_technician'  => $request->remarks_for_technician,
            'remarks'                 => $request->sale_remarks,
            'special_case_id'         => $request->special_case,
            'discount_amount'         => $request->special_discount,
            'adjustment_type'         => $request->discount_type,
            'payment_mode_id'         => $request->payment_mode_id ?? '',
            'bussiness_source_id'     => $request->bussiness_source ?? '',
        ];

        $sale_invoice->update($sale_invoice_update);

        $batchVoucherType = VoucherType::select(['id','code'])->find($data['voucher_type_id']);

        $where = [
            'id'             => $batch_id,
            'invoice_id'     => $sale_invoice->id,
        ];
        $invoice_batchs = [
            'sample_barcode'            => $request->sample_barcode,
            'sample_receive_date'       => $request->sample_receive_date,
            'sample_receive_time'       => $request->sample_receive_time,
            'remarks_for_technician'    => $request->remarks_for_technician,
            'updated_by'                => Auth::user()->id,
            'batch_status'              => 'ACCEPTED',
            'referrence_voucher_type'   => $batchVoucherType->code??'',
        ];


        //sale invoice batch
        $invoice_batch  = SaleInvoiceBatch::where($where)->first();

        $invoice_batch->update($invoice_batchs);


        /*********************  Spacial Discount Store Calculation ***********************/
        $discount['mode_id'] = $request->discount_account_id ?? '';
        $discount['amount'] = $request->special_discount ?? 0;
        /********************* End Spacial Discount Store Calculation ***********************/

        /*********************  Round Off Store Calculation ***********************/
        $roundOff['mode_id'] = $request->round_off_account_id ?? '';
        $roundOff['amount'] = $request->round_off_amount ?? 0;
        /********************* End  Round Off Store Calculation ***********************/


        $task_status  = TaskStatus::where('is_default', '1')->first();
        $sale_invoice_detail_ids = $sale_invoice_sub_detail_ids = $product_ids = $price_ids = [];

        foreach ($data['products'] as $key => $value) {
            $product = Product::where('id', $value['product_id'])
                ->with('getProductPrice')
                ->first();

            $item = [
                
                // 'price'               => $value['product_price'],
                // 'basic_amount'        => $value['product_price'],
                // 'discount_percentage' => $value['per_discount'],
                // 'discount_amount'     => $value['flat_discount'],
                // 'total_amount'        => $value['amount'],
                // 'item_details'        => $value['product_details'],
                // 'item_batch'          => $product->getProductPrice->batch ?? '',
                // 'tax_slab_id'         => $product->tax_slab_id ?? '',
                // 'main_qty'            => $value['main_qty'],
                // 'from_date_time'      => Carbon::now()->format('Y-m-d H:i:s'),
                // 'customer_amount'     => $value['amount']??0,

                'product_price_id'    => $value['price_id'],
                'price'               => $value['product_price'],
                'basic_amount'        => $value['product_basic'],
                'discount_percentage' => $value['per_discount'],
                'discount_amount'     => $value['flat_discount'],
                'total_amount'        => $value['amount'],
                'item_details'        => $value['product_details']??'',
                'main_qty'            => $value['main_qty'],
                'from_date_time'      => Carbon::now()->format('Y-m-d H:i:s'),
                'item_batch'          => $value['batch'],
                'tax_slab_id'         => $product->tax_slab_id ?? '',
                'tpa_amount'          => 0,
                'customer_amount'     => $value['amount'] ?? 0,
                'tax_calculation_type'=> $voucher_master->tax_calculation??'',
            ];

            $product_ids[] = $value['product_id'];
            $price_ids[]               = $value['price_id'];

            $sale_invoice_details = SaleInvoiceDetail::updateOrCreate([
                'sale_invoice_id'     => $sale_invoice->id,
                'product_id'          => $value['product_id'],
                'batch_id'            => $batch_id
            ], $item);

            $sale_invoice_detail_ids[] = $sale_invoice_details->id;

             /**************Stock Out Function ********************/
             if($product->manage_stock=='Yes')
             {
                stockOut($sale_invoice->id,'IPD_INVOICE',$value['product_id'],$value['main_qty'],$value['product_price'],$invoice_batch->id,$value['price_id']);
             }

            $product_test_package = ProductTestPackage::where('product_id', $value['product_id'])->get();

            foreach ($product_test_package as $package) {
                $addedTestPackage = SaleInvoiceSubDetails::updateOrCreate(
                    [
                        'sale_invoice_detail_id' => $sale_invoice_details->id,
                        'sale_invoice_id'        => $sale_invoice->id,
                        'data_referrence_id'     => $package->test_package_id,
                    ],
                    [
                        'subdetails_remarks'     => '',
                        'referrence_type'        => 'LAB',
                        'status'                 => 'SAMPLE_COLLECTION',
                        'task_status_id'         => $task_status->id ?? '',
                        'review_status_id'       => $task_status->id ?? '',
                    ]
                );
                $sale_invoice_sub_detail_ids[] = $addedTestPackage->id;
            }
        }

        if (!empty($product_ids)) {
            $sale_invoice_details = SaleInvoiceDetail::where([
                'sale_invoice_id'     => $sale_invoice->id,
                'batch_id'            => $batch_id
            ])->whereNotIn('product_id', $product_ids)->get();
            foreach ($sale_invoice_details as $key => $value) {
                SaleInvoiceSubDetails::where([
                        'sale_invoice_detail_id' => $value->id,
                        'sale_invoice_id'        => $value->sale_invoice_id,
                        // 'data_referrence_id'     => $package->test_package_id,
                    ])->delete();
                SaleInvoiceDetail::where('id', $value->id)->delete();
            }
        }

        $voucher_type   = VoucherType::with('voucherSeries')->where('code', 'IPD_ADMISSION')->where(['status' => 1])->first();
        /***************************************Basic Transaction Update ***************/
        $this->updateTransaction(
            'IPD_INVOICE',
            $sale_invoice->id,
            $invoice_batch->id,
            $voucher_type->code,
            $data['patient_id'],
            $data,
            $roundOff,
            $discount,
            $request->special_discount ?? 0
        );

        /**************************** End Basic Transaction Update *********************/

        \Session::forget('ipd_sale_order_billing_products_cart');

        return redirect()->route('ipd-sale-orders.invoice', ['id'=>$id,'batch_id'=>$batch_id])->with('success', "Bill Updated Successfully");
    }




}
