<?php

namespace App\Http\Controllers\V1\Quotation;

use App\Http\Controllers\Controller;
use App\Models\ClientType;
use App\Models\PaymentStatus;
use App\Models\IndirectTax;
use App\Models\PaymentMode;
use App\Models\TermsAndConditions;
use App\Models\ClientAddress;
use App\Models\Client;
use App\Models\Quotation;
use App\Models\QuotationDetails;
use App\Models\BankDetails;
use App\Models\POReceiptVoucher;
use App\Models\PoInward;
use App\Models\POInwardTimeline;
use App\Models\StockAllocation;
use App\Models\IndividulClient;
use App\Models\ClientMappingTag;
use App\Models\QuotCharges;
use App\Models\QuotStatus;
use App\Models\QuotOc;
use App\Models\DocumentType;
use App\Models\DocumentSeries;
use App\Models\LogisticDetails;
use App\Models\QuotChallan;
use App\Models\QuotChallanDetails;
use App\Models\QuotChallanExtraCharges;
use App\Models\ReceiptVoucher;
use App\Models\ReceiptVoucherDetails;
use App\Models\ReceiptVoucherExtraCharges;
use App\Models\PaymentDetails;
use App\Models\PoDetails;
use App\Models\PurchaseOrder;
use App\Models\QuotTaxInvoice;
use App\Models\QuotTaxInvoiceExtraCharges;
use App\Models\QuotTaxInvoiceProduct;
use App\Models\QuotProformaInvoice;
use App\Models\QuotProformaInvoiceExtraCharges;
use App\Models\QuotProformaInvoiceProduct;
use App\Models\Inventory;
use App\Models\Store;
use App\Models\User;
use App\Models\Products;
use App\Models\MaterialRequisition;
use App\SchemaMetadata;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use DB;
use Image;
use Illuminate\Support\Facades\Mail;
class QuotationMetadataController extends Controller
{
public function addQuotation(Request $request): JsonResponse
{
    try {
        $validator = Validator::make($request->all(), [
            'client_id' => 'required|numeric|exists:clients,id',
            'parent_quot'=>'nullable|integer|exists:quotation,id',
            'name' => 'nullable|string',
            'file' => 'nullable',
            'reference_id'=>'nullable|numeric|exists:reference,id',
           // 'reviewed_by_user_id' => 'nullable|numeric|numeric|exists:users,id',
            'tnc_id' => 'nullable|numeric|exists:terms_and_conditaions,id',
           // 'payment_status_id' => 'required|numeric|exists:payment_status,id',
            'total_amount' => 'required|numeric|gt:0',
            'indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
            'bank_details_id' => 'nullable|numeric|exists:bank_details,id',
            //'payment_mode_id' => 'required|numeric|exists:payment_mode,id',
            'comment' => 'nullable|string',
            'delivery_date' => 'nullable|date',
            'delivery_address_id' => 'nullable|numeric|exists:client_address,id',
            'attachment_file' => 'nullable',
            'logistic_details_id' => 'numeric|exists:logistic_details,id',
            'is_draftsave'=>'nullable|boolean',
            'products' => 'required|array',
            'products.*.qty' => 'required|numeric|gt:0',
            'products.*.modified_amount' => 'required|numeric|gt:0',
            'products.*.discount' => 'nullable|numeric',
            'products.*.delivery_date' => 'nullable|date',
            'products.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
            'products.*.comment' => 'nullable|string',
            // 'products.*.total_before_tax' => 'nullable|gt:0',
            // 'products.*.total_tax' => 'nullable|gt:0',
            'charges' => 'array',
            'charges.*.description' => 'nullable|string',
            'charges.*.total_amount' => 'nullable',
            'charges.*.indirect_tax_id' => 'nullable|exists:indirect_tax,id',
            'charges.*.total_tax' => 'nullable',
        ]);
        if ($validator->fails()) {
            return $this->sendError('Validation Error.', $validator->errors());
        }
        $newQuotation = new Quotation();
        $newQuotation->client_id = $request->client_id;
        $newQuotation->name = $request->name;
        if($request->has('parent_quot')){
            if($request->parent_quot!=null && $request->parent_quot>0){
                $newQuotation->parent_quot = $request->parent_quot;
            }
        }
        $newQuotation->created_by_user_id = Auth::user()->id;
        if ($request->file != "") {
            if (!str_contains($request->file, "http")) {
                $newQuotation->file = $this->saveImage($request->file, $request->client_id);
            }
        }
        //$newQuotation->reference_no = 'QTN'.'000'.(Quotation::query()->count()+1);
        $count = Quotation::count() + 1;
        $reference_no = 'QTN' . str_pad($count, 4, '0', STR_PAD_LEFT);
        $newQuotation->reference_no = $reference_no;
        $newQuotation->reviewed_by_user_id = $request->reviewed_by_user_id;
        $newQuotation->billing_address_id = $request->billing_address_id;
        $newQuotation->tnc_id = $request->tnc_id;
        $newQuotation->name = $request->name;
       // $newQuotation->payment_status_id = $request->payment_status_id;
       // $newQuotation->total_amount = $request->total_amount;
        $newQuotation->bank_details_id = $request->bank_details_id;
      //  $newQuotation->payment_mode_id = $request->payment_mode_id;
        $newQuotation->comment = $request->comment;
        $newQuotation->delivery_address_id = $request->delivery_address_id;
        if ($request->attachment_file != "") {
            if (!str_contains($request->attachment_file, "http")) {
                $newQuotation->attachment_file = $this->saveImage($request->attachment_file, $request->client_id);
            }
        }
        $newQuotation->logistic_details_id=$request->logistic_details_id;
        $newQuotation->quot_status_id =1;
        $newQuotation->is_draftsave=$request->is_draftsave;
        $newQuotation->delivery_date=$request->delivery_date;
        $newQuotation->reference_id=$request->reference_id;
        $newQuotation->cgst=$request->cgst;
        $newQuotation->sgst=$request->sgst;
        $newQuotation->igst=$request->igst;
        $newQuotation->discount_percentage=$request->discount_percentage;
        $newQuotation->remaining_amount=$newQuotation->total_amount;
        // $newQuotation->send_qty=0;
        $newQuotation->save();
        $totalamount=0.0;
        $totalAmount=0.0;
        $totalDiscount=0.0;
        $totalTax=0.0;
        if (is_array($request->products) || is_object($request->products)) {
            $productCount = count($request->products);
        foreach ($request->products as $eachProduct) {
            $newQuotationDetails = new QuotationDetails();
            $newQuotationDetails->quotation_id = $newQuotation->id;
            $newQuotationDetails->product_id = $eachProduct['product_id'];
            $newQuotationDetails->qty = $eachProduct['qty'];
            $newQuotationDetails->modified_amount = $eachProduct['modified_amount'];
            $totalamount=$newQuotationDetails->qty*$newQuotationDetails->modified_amount;

            $newQuotationDetails->discount_percentage = $eachProduct['discount_percentage'];

            $discount = ($newQuotationDetails->discount_percentage / 100) * $totalamount;

            $newQuotationDetails->discount = $discount;
            $finalAmount=$totalamount-$discount;
            $newQuotationDetails->total_before_tax =$finalAmount;
            $newQuotationDetails->delivery_date = $eachProduct['delivery_date'];
            $tax = 0;
            if(!is_null($eachProduct['indirect_tax_id'])){
                $newQuotationDetails->indirect_tax_id = $eachProduct['indirect_tax_id'];
                $getTaxPercentage=IndirectTax::query()->where('id',$newQuotationDetails->indirect_tax_id)->first();
                $percentage=$getTaxPercentage->percentage;
                $tax = ($percentage / 100) * $finalAmount;
            }
            $newQuotationDetails->total_tax = $tax;
            $newQuotationDetails->tax_percentage = $percentage;
            $newQuotationDetails->comment = $eachProduct['comment'];
            $newQuotationDetails->remaining_qty = $newQuotationDetails->qty;
            $newQuotationDetails->send_qty=0;
            $newQuotationDetails->save();
            $totalAmount += $totalamount;
            $totalDiscount += $discount;
            $totalTax += $tax;

            $checkProductQty=Inventory::query()->where('product_id',$newQuotationDetails->product_id)
                ->where('store_id',Auth::user()->store_id)
                ->where('qty',"<",$newQuotationDetails->qty)
                ->first();
                if($checkProductQty!=null){
                    $newMaterialRequisition=new MaterialRequisition();
                    $newMaterialRequisition->product_id=$newQuotationDetails->product_id;
                    $newMaterialRequisition->qty=$newQuotationDetails->qty;
                    $newMaterialRequisition->store_id=Auth::user()->store_id;
                    $newMaterialRequisition->requested_by=Auth::user()->id;
                    $newMaterialRequisition->quotation_id=$newQuotation->id;
                    $newMaterialRequisition->client_id=$newQuotation->client_id;
                    $newMaterialRequisition->save();

                }

        }

    }
        $totatExtrachargesTax=0.0;
        $totalExtracharges=0.0;
        if (is_array($request->charges) || is_object($request->charges)) {
            foreach ($request->charges as $eachcharges) {
                $charges = new QuotCharges();
                $charges->quotation_id = $newQuotation->id;
                $charges->description = $eachcharges['description'];
                $charges->total_amount = $eachcharges['total_amount'];
                $extrachargestax=0;
                if(!is_null($eachcharges['indirect_tax_id'])){
                    $charges->indirect_tax_id = $eachcharges['indirect_tax_id'];
                    $getTaxPercentage=IndirectTax::query()->where('id',$charges->indirect_tax_id)->first();

                   $percentage=$getTaxPercentage->percentage;
                    $extrachargestax = ($percentage / 100) * $eachcharges['total_amount'];
                }

                $charges->total_tax =$extrachargestax;
                $totalcharges=$charges->total_amount;
                $charges->save();
                $totalExtracharges += $totalcharges;
                $totatExtrachargesTax += $extrachargestax;
            }

        }
        $finalTaxAmount=$totalTax+$totatExtrachargesTax;
        $newQuotation->substotal=round($totalAmount,2);
        $newQuotation->discount_amount=round($totalDiscount,2);
        $newQuotation->total_tax_amount=round($finalTaxAmount,2);
        $newQuotation->extra_charges_amount=round($totalExtracharges,2);
        $grandTotal=$totalAmount-$totalDiscount+$totalTax+$totalExtracharges+$totatExtrachargesTax;
        if($request->roundOffCalculation){
            $roundOffAmount = round($grandTotal);
            $newQuotation->round_off = round($roundOffAmount -$grandTotal,2);
            $newQuotation->total_amount=$roundOffAmount;
        }else{
            $newQuotation->total_amount =$grandTotal;
        }

        $newQuotation->save();

        $clientdata=Client::query()->where('id',$newQuotation->client_id)->first();

        $clientname=$clientdata->company_name;
        $to_email = $clientdata->company_person_email;
        $store=auth::user()->store_id;
        $storeDetails=Store::query()->where('id',$store)->first();
        $login_comanpany_name=$storeDetails->name;
        $user=auth::user()->id;
        $loginDetails=User::query()->where('id',$user)->first();
        $helplinemail=$loginDetails->email;
        $url=$request->url;
        $cruent_id=$newQuotation->id;
        $data = array('quotation_number' => $newQuotation->reference_no,
        'amount' => $newQuotation->total_amount,
        'no_of_item' => $productCount,
        'company_name' => $clientname,
        'login_company_name' => $login_comanpany_name,
        'help_line_email'=>$helplinemail,
        'url'=>$url. '/' .$cruent_id,
    );

        Mail::send('emails.sendQuotation', $data, function($message) use ($to_email) {
        $message->to($to_email)
            ->subject('Quotation Details');
        $message->from(env('MAIL_FROM_ADDRESS'), 'NEUROERP System Mail');
    });
        return $this->sendResponse($newQuotation->id, 'Quotation added successfully', true);
    } catch (Exception $e) {
        return $this->sendError('Something went wrong', $e->getMessage(), 413);
    }
}
public function getAllQuotationsByClientId(Request $request):JsonResponse
    {
        try{
            $validator=Validator::make($request->all(),[
                "id"=>'required|integer|exists:clients,id',
            ]);
            if($validator->fails()){
                return $this->sendError("Validation failed",$validator->errors());
            }
            $data = [];
            $getAllQuot = Quotation::query()
            ->where('client_id', $request->id)
            ->where('quot_status_id','!=',2)
            ->get();
            foreach ($getAllQuot as $key=>$quot) {
                $oc = QuotOc::query()->where('quotation_id', $quot->id)->first();
                if ($oc) {
                    unset($getAllQuot[$key]);
                }else{
                    array_push($data,$quot);
                }
            }
            return $this->sendResponse($data,"Data fetched successfully",true);
        }catch(Exception $e){
            return $this->sendError("Something went wrong",$e->getMessage(),413);
        }
    }
    public function saveFile($image,$productName){
        $imageName = $productName.'-'.rand(100,9999).'.webp';

        $destinationPath = public_path('poimage\\'.$imageName);
        if(env('APP_ENV')=='prod'){
            $destinationPath =  public_path('poimage/'.$imageName);
        }
        $img = Image::make(file_get_contents($image))
            ->resize(300, null)
            ->save($destinationPath,80,'webp');

        return '/poimage/'.$imageName;
    }
    public function editQuotation(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'client_id' => 'nullable|numeric|exists:clients,id',
                'name' => 'nullable|string',
                'file' => 'nullable|string',
                'tnc_id' => 'nullable|numeric|exists:terms_and_conditaions,id',
                'payment_status_id' => 'nullable|numeric|exists:payment_status,id',
                'total_amount' => 'numeric|gt:0',
                'indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'bank_details_id' => 'nullable|numeric|exists:bank_details,id',
                'payment_mode_id' => 'nullable|numeric|exists:payment_mode,id',
                'comment' => 'nullable|string',
                'reference_id'=>'nullable|numeric|exists:reference,id',
                'delivery_date'=>'nullable|date',
                'delivery_address_id' => 'nullable|numeric|exists:client_address,id',
                'attachment_file' => 'nullable|string',
                'logistic_details_id' => 'nullable|numeric|exists:logistic_details,id',
                'quot_status_id' => 'nullable|numeric|exists:quot_status,id',
                'products' => 'array',
                'products.*.qty' => 'nullable|numeric|gt:0',
                'products.*.modified_amount' => 'nullable|numeric|gt:0',
                'products.*.discount' => 'nullable',
                'products.*.delivery_date' => 'nullable|date',
                'products.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'products.*.comment' => 'nullable|string',
                // 'products.*.total_before_tax' => 'nullable|gt:0',
                // 'products.*.total_tax' => 'nullable|gt:0',
                'charges' => 'array',
                'charges.*.description' => 'nullable|string',
                'charges.*.total_amount' => 'nullable',
                'charges.*.indirect_tax_id' => 'nullable|exists:indirect_tax,id',
                'charges.*.total_tax' => 'nullable',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editQuotation = Quotation::query()->where('id',$request->id)->first();
            if ($request->has('client_id')) {
                $editQuotation->client_id = $request->client_id;
            }
            if ($request->has('name')) {
                $editQuotation->name = $request->name;
            }
            if ($request->has('tnc_id')) {
                $editQuotation->tnc_id = $request->tnc_id;
            }
            if ($request->has('payment_status_id')) {
                $editQuotation->payment_status_id = $request->payment_status_id;
            }
            if ($request->has('total_amount')) {
                $editQuotation->total_amount = $request->total_amount;
            }
            if ($request->has('indirect_tax_id')) {
                $editQuotation->indirect_tax_id = $request->indirect_tax_id;
            }
            if ($request->has('bank_details_id')) {
                $editQuotation->bank_details_id = $request->bank_details_id;
            }
            if ($request->has('reference_id')) {
                $editQuotation->reference_id = $request->reference_id;
            }
             if ($request->has('payment_mode_id')) {
                $editQuotation->payment_mode_id = $request->payment_mode_id;
            }
            if ($request->has('comment')) {
                $editQuotation->comment = $request->comment;
            }
            if ($request->has('delivery_address_id')) {
                $editQuotation->delivery_address_id = $request->delivery_address_id;
            }
            if ($request->has('delivery_date')) {
                $editQuotation->delivery_date = $request->delivery_date;
            }
            if ($request->has('logistic_details_id')) {
                $editQuotation->logistic_details_id = $request->logistic_details_id;
            }
            if ($request->file != "") {
                if (!str_contains($request->file, "http")) {
                    $editQuotation->file = $this->saveImage($request->file, $request->client_id);
                }
            }
            if ($request->attachment_file != "") {
                if (!str_contains($request->attachment_file, "http")) {
                    $editQuotation->attachment_file = $this->saveImage($request->attachment_file, $request->client_id);
                }
            }
            if ($request->has('quot_status_id')) {
                $editQuotation->quot_status_id = $request->quot_status_id;
            }
            if ($request->has('discount_percentage')) {
                $editQuotation->discount_percentage = $request->discount_percentage;
            }
            if ($request->has('billing_address_id')) {
                $editQuotation->billing_address_id = $request->billing_address_id;
            }
            $editQuotation->save();
            $totalamount=0.0;
            $totalAmount=0.0;
            $totalDiscount=0.0;
            $totalTax=0.0;
            QuotationDetails::where('quotation_id', $editQuotation->id)->delete();
            foreach ($request->products as $eachProduct) {
                $newQuotationDetails = new QuotationDetails();
                $newQuotationDetails->quotation_id = $editQuotation->id;
                $newQuotationDetails->product_id = $eachProduct['product_id'];
                $newQuotationDetails->qty = $eachProduct['qty'];
                $newQuotationDetails->modified_amount = $eachProduct['modified_amount'];
                $totalamount=$newQuotationDetails->qty*$newQuotationDetails->modified_amount;

                $newQuotationDetails->discount_percentage = $eachProduct['discount_percentage'];

                $discount = ($newQuotationDetails->discount_percentage / 100) * $totalamount;
                $newQuotationDetails->discount = $discount;
                $finalAmount=$totalamount-$discount;
                $newQuotationDetails->total_before_tax =$finalAmount;
                $newQuotationDetails->delivery_date = $eachProduct['delivery_date'];
                $tax = 0;
                $percentage=0;
                if(!is_null($eachProduct['indirect_tax_id'])){
                    $newQuotationDetails->indirect_tax_id = $eachProduct['indirect_tax_id'];
                    $getTaxPercentage=IndirectTax::query()->where('id',$newQuotationDetails->indirect_tax_id)->first();
                    $percentage=$getTaxPercentage->percentage;
                    $tax = ($percentage / 100) * $finalAmount;
                }
                $newQuotationDetails->total_tax = $tax;
                $newQuotationDetails->tax_percentage = $percentage;
                $newQuotationDetails->comment = $eachProduct['comment'];
                $newQuotationDetails->remaining_qty = $newQuotationDetails->qty;
                $newQuotationDetails->send_qty=0;
                $newQuotationDetails->save();
                $totalAmount += $totalamount;
                $totalDiscount += $discount;
                $totalTax += $tax;
            }
            $totatExtrachargesTax=0.0;
        $totalExtracharges=0.0;
            QuotCharges::where('quotation_id', $editQuotation->id)->delete();
            if (is_array($request->charges) || is_object($request->charges)) {
                foreach ($request->charges as $eachcharges) {
                    $charges = new QuotCharges();
                    $charges->quotation_id = $editQuotation->id;
                    $charges->description = $eachcharges['description'];
                    $charges->total_amount = $eachcharges['total_amount'];
                    $extrachargestax=0;
                    if(!is_null($eachcharges['indirect_tax_id'])){
                        $charges->indirect_tax_id = $eachcharges['indirect_tax_id'];
                        $getTaxPercentage=IndirectTax::query()->where('id',$charges->indirect_tax_id)->first();

                       $percentage=$getTaxPercentage->percentage;
                        $extrachargestax = ($percentage / 100) * $eachcharges['total_amount'];
                    }

                    $charges->total_tax =$extrachargestax;
                    $totalcharges=$charges->total_amount;
                    $charges->save();
                    $totalExtracharges += $totalcharges;
                    $totatExtrachargesTax += $extrachargestax;
                }

            }
            $finalTaxAmount=$totalTax+$totatExtrachargesTax;
            $editQuotation->substotal=round($totalAmount,2);
            $editQuotation->discount_amount=round($totalDiscount,2);
            $editQuotation->total_tax_amount=round($finalTaxAmount,2);
            $editQuotation->extra_charges_amount=round($totalExtracharges,2);
            $grandTotal=$totalAmount-$totalDiscount+$totalTax+$totalExtracharges+$totatExtrachargesTax;
            if($request->roundOffCalculation){
                $roundOffAmount = round($grandTotal);
                $editQuotation->round_off = round($roundOffAmount -$grandTotal,2);
                $editQuotation->total_amount=$roundOffAmount;
            }else{
                $editQuotation->total_amount =$grandTotal;
            }

            $editQuotation->save();
            return $this->sendResponse($editQuotation->id, 'Quotation updated successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getmessage(), 413);
        }
    }

    public function updateQuotationStatus(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
               'id'=>'required|numeric|exists:quotation,id',
                'quot_status_id' => 'nullable|numeric|exists:quot_status,id',

            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editQuotation = Quotation::query()->where('id',$request->id)->first();

            if ($request->has('quot_status_id')) {
                $editQuotation->quot_status_id = $request->quot_status_id;
            }
            $editQuotation->save();

            return $this->sendResponse($editQuotation->id, 'Quotation updated successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getmessage(), 413);
        }
    }
    public function cancelQuotation(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quotation,id',
                'quot_status_id' => 'numeric|exists:quot_status,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editQuotation = Quotation::query()->where('id',$request->id)->first();
            $editQuotation->quot_status_id = 2;
            $editQuotation->save();

            return $this->sendResponse([], 'Quotation cancel successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getmessage(), 413);
        }
    }
    public function getAllQuotation(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
                'quot_status_id' => 'integer|exists:quot_status,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = Quotation::query()->with(['client','created_by_user','reviewed_by_user','tnc',
            'payment_status','quot_status','quot_status','bank_details','delivery_address',
            'client.client_address','billing_address']);
            $count = $query->count();
            if ($request->has('quot_status_id')) {
                $query = $query->where('quot_status_id', $request->quot_status_id);
            }
            if ($request->has('company_name')) {
                $query = $query->whereHas('client', function ($q) use ($request) {
                    $q->where('company_name', 'like', '%' . $request->company_name . '%');
                });
            }
            if ($request->has('created_by')) {
                $query = $query->whereHas('created_by_user', function ($q) use ($request) {
                    $q->where('name', 'like', '%' . $request->created_by . '%');
                });
            }
             if ($request->has('total_amount')) {
                $query = $query->where('total_amount', 'like', '%' . $request->total_amount . '%');
            }
            if ($request->has('start_date') && $request->has('end_date')) {
                $query = $query->whereDate('created_at','>=', $request->start_date)->whereDate('created_at','<=', $request->end_date);
            }
            if ($request->has('reference_no')) {
                $query = $query->where('reference_no', 'like', '%' . $request->reference_no . '%');
            }
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            if($request->has('reference_no_sort')){
                if($request->reference_no_sort){
                    $query=$query->orderBy('reference_no','ASC');
                }else{
                    $query=$query->orderBy('reference_no','DESC');
                }
            }
            if($request->has('total_amount_sort')){
                if($request->total_amount_sort){
                    $query=$query->orderBy('total_amount','ASC');
                }else{
                    $query=$query->orderBy('total_amount','DESC');
                }
            }
            if($request->has('created_at_sort')){
                if($request->created_at_sort){
                    $query=$query->orderBy('created_at','ASC');
                }else{
                    $query=$query->orderBy('created_at','DESC');
                }
            }
            $getQuotation = $query->orderBy('id', 'DESC')->get();
            foreach ($getQuotation as $user){
                if($user['id']!=null){
                    $product=QuotationDetails::query()->where('quotation_id',$user['id'])
                    ->with(['products','tax'])->get();
                    $user['quotation_details']=$product;
                }
            }
            if (count($getQuotation) > 0) {
                return $this->sendResponse(["quotations" => $getQuotation, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No quotation are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllCancelQuotation(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = Quotation::query()->where('quot_status_id','2')->with(['client','created_by_user','reviewed_by_user','tnc','payment_status','quot_status','quot_status','bank_details','delivery_address','client.client_address','logistic_details']);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getQuotation = $query->orderBy('id', 'DESC')->get();
            foreach ($getQuotation as $user){
                if($user['id']!=null){
                    $product=QuotationDetails::query()->where('quotation_id',$user['id'])
                    ->with(['products'])->get();
                    $user['quotation_details']=$product;
                }
            }
            if (count($getQuotation) > 0) {
                return $this->sendResponse(["quotations" => $getQuotation, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No quotation address are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteQuotationById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quotation,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteQuotation = Quotation::query()
            ->where('id', $request->id)->first();
            $deleteQuotation->delete();
            return $this->sendResponse([], 'Quotation deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
   public function getQuotationId(Request $request): JsonResponse
{
    try {
        $validator = Validator::make($request->all(), [
            'id' => 'required|numeric|exists:quotation,id',
        ]);

        if ($validator->fails()) {
            return $this->sendError('Validation Error.', $validator->errors());
        }

        $getQuotation = Quotation::query()
            ->where('id', $request->id)
            ->with([
                'client',
                'created_by_user',
                'reviewed_by_user',
                'tnc',
                'payment_status',
                'quot_status',
                'bank_details',
                'delivery_address',
                'Client.client_address',
                'indirect_tax',
                'logistic_details',
                'billing_address'
            ])
            ->first();

        if ($getQuotation !== null) {
            $product = QuotationDetails::query()
                ->where('quotation_id', $getQuotation['id'])
                ->with(['products', 'tax'])
                ->get();

            $getQuotation['quotation_details'] = $product;
        }

        $getQuotOc = QuotOc::query()
            ->where('quotation_id', $request->id)
            ->get();

        $getQuotCharges = QuotCharges::query()
            ->where('quotation_id', $request->id)
            ->with(['indirect_tax'])
            ->get();


        $orderConfirmations = $getQuotOc->isEmpty() ? null : $getQuotOc;

        return $this->sendResponse([
            'quotation' => $getQuotation,
            'order_confermation' => $orderConfirmations,
            'quotation_charges' => $getQuotCharges
        ], 'Data fetch successfully', true);
    } catch (Exception $e) {
        return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
    }
}

    public function getQuotationNextId(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [

            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $response = 'QTN'.'000'.(Quotation::query()->count()+1);
            return $this->sendResponse(["next_id"=>$response], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addBankDetails(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'bank_name' => 'required|string',
                'account_name' => 'required|string',
                'account_no' => 'required|string',
                'ifsc' => 'required|string',
                'branch_name' => 'required|string',
                'swift_code' => 'nullable|string',
                'micr'=>'nullable',
                'address'=> 'nullable|string',
                'payment_mode_id'=> 'required|exists:payment_mode,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newBankDetails = new BankDetails();
            $newBankDetails->bank_name = $request->bank_name;
            $newBankDetails->account_name = $request->account_name;
            $newBankDetails->account_no = $request->account_no;
            $newBankDetails->ifsc = $request->ifsc;
            $newBankDetails->branch_name = $request->branch_name;
            $newBankDetails->swift_code = $request->swift_code;
            $newBankDetails->micr = $request->micr;
            $newBankDetails->address = $request->address;
            $newBankDetails->payment_mode_id = $request->payment_mode_id;
            $newBankDetails->save();
            return $this->sendResponse([], 'Bank details added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getTrace(), 413);
        }
    }
    public function editBankDetails(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'bank_name' => 'string',
                'account_name' => 'string',
                'account_no' => 'string',
                'ifsc' => 'string',
                'branch_name' => 'string',
                'swift_code' => 'string',
                'micr'=>'string',
                'address'=> 'string',
                'payment_mode_id'=> 'numeric|exists:payment_mode,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editBankDetails = BankDetails::query()->where('id', $request->id)->first();
            if ($request->has('account_name')) {
                $editBankDetails->account_name = $request->account_name;
            }
            if ($request->has('account_no')) {
                $editBankDetails->account_no = $request->account_no;
            }
            if ($request->has('ifsc')) {
                $editBankDetails->ifsc = $request->ifsc;
            }
            if ($request->has('branch_name')) {
                $editBankDetails->branch_name = $request->branch_name;
            }
            if ($request->has('swift_code')) {
                $editBankDetails->swift_code = $request->swift_code;
            }
            if ($request->has('micr')) {
                $editBankDetails->micr = $request->micr;
            }
            if ($request->has('address')) {
                $editBankDetails->address = $request->address;
            }
            if ($request->has('payment_mode_id')) {
                $editBankDetails->payment_mode_id = $request->payment_mode_id;
            }
            $editBankDetails->save();
            return $this->sendResponse([], 'Bank details updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllBankDetails(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = BankDetails::query()->with(['payment_mode']);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }

            $getBankDetails = $query->orderBy('id', 'DESC')->get();
            if (count($getBankDetails) > 0) {
                return $this->sendResponse(["bank_details" => $getBankDetails, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No BankDetails address are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteBankDetailsById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|numeric|exists:bank_details,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteBankDetails = BankDetails::query()

            ->where('id', $request->id)->first();

            $deleteBankDetails->delete();
            return $this->sendResponse([], 'Bank details deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getBankDetailsById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|numeric|exists:bank_details,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getBankDetails = BankDetails::query()->where('id', $request->id)->with(['payment_mode'])->first();
            return $this->sendResponse($getBankDetails, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function saveImage($image,$productName){
        $imageName = $productName.'-'.rand(100,9999).'.webp';

        $destinationPath = public_path('productimage\\'.$imageName);
        if(env('APP_ENV')=='prod'){
            $destinationPath =  public_path('productimage/'.$imageName);
        }
        $img = Image::make(file_get_contents($image))
            ->resize(300, null)
            ->save($destinationPath,80,'webp');

        return '/productimage/'.$imageName;
    }
    public function addClient(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'address' => 'nullable',
                'address.address_line_1' => 'nullable|string',
                'address.address_line_2' => 'nullable',
                'address.pincode' => 'nullable|string',
                'address.state' => 'nullable|string',
                'address.city' => 'nullable|string',
                'address.country' => 'nullable|string',
                'company_name' => 'required|string',
                'company_person_name' => 'required|string',
                'company_person_mobile' => 'required|string|unique:clients,company_person_mobile',
                'company_person_email' => 'required|string|email|unique:clients,company_person_email',
                'company_email' => 'required|string|email|unique:clients,company_email',
                'gst_no'=>'nullable',
                'logo'=>'nullable|string',
                'client_type'=>  [Rule::in(['both', 'buyer', 'supplier'])],
                'tags' => 'array',
                'tags.*.product_tag_id' => 'nullable|numeric|exists:product_tags,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newAddress = new ClientAddress();
            $newAddress->address_line_1 = $request->address['address_line_1'] ;
            $newAddress->address_line_2 = $request->address['address_line_2'];
            $newAddress->pincode = $request->address['pincode'];
            $newAddress->state = $request->address['state'];
            $newAddress->city = $request->address['city'];
            $newAddress->country = $request->address['country'];
            $newAddress->save();
            $newClient = new Client();
            $newClient->client_address_id =$newAddress->id;
            //$newClient->billing_address_id =$newAddress->id;
            $newClient->company_name = $request->company_name;
            $newClient->company_person_name = $request->company_person_name;
            $newClient->company_person_mobile = $request->company_person_mobile;
            $newClient->company_person_email = $request->company_person_email;
            $newClient->company_email = $request->company_email;
            if($request->has('gst_no')){
                if (!preg_match("/^([0-9]){2}([A-Za-z]){5}([0-9]){4}([A-Za-z]){1}([0-9]{1})[Z]{1}([A-Za-z0-9]){1}?$/", $request->gst_no))
                 {
                    return $this->sendError([], 'Invalid GSTIN');
                }
                else{
                    $newClient->gst_no = $request->gst_no;
                }
            }

            $newClient->client_type = $request->client_type;

            if ($request->logo != "") {
                if (!str_contains($request->logo, "http")) {
                    $newClient->logo = $this->saveImage($request->logo, $request->company_name);
                }
            }
            $newClient->save();
            $newAddress->client_id=$newClient->id;
            $newAddress->address_for='client';
            $newAddress->save();
            if(is_array($request->tags) || is_object($request->tags)){
            foreach($request->tags as $tag){
            $newClientMappingTag = new ClientMappingTag();
            $newClientMappingTag->client_id = $newClient->id;
            $newClientMappingTag->product_tag_id = $tag['product_tag_id'];
            $newClientMappingTag->save();
            }
        }
            return $this->sendResponse($newClient->id, 'Client added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function addClientAddress(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'address_line_1' => 'nullable|string',
                'address_line_2' => 'nullable',
                'pincode' => 'nullable|string',
                'state' => 'nullable|string',
                'city' => 'nullable|string',
                'country' => 'nullable|string',
                'client_id' => 'nullable|numeric|exists:clients,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newAddress = new ClientAddress();
            $newAddress->address_line_1 = $request->address_line_1;
            $newAddress->address_line_2 = $request->address_line_2;
            $newAddress->pincode = $request->pincode;
            $newAddress->state = $request->state;
            $newAddress->city = $request->city;
            $newAddress->country = $request->country;
            $newAddress->client_id = $request->client_id;
            $newAddress->save();

            return $this->sendResponse([], 'Client address added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getAllClientAddressUsingClientId(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = ClientAddress::query()->with(['client'])
            ->where('client_id',$request->client_id);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getClientAddress = $query->orderBy('id', 'DESC')->get();
            if (count($getClientAddress) > 0) {
                return $this->sendResponse(["client_address" => $getClientAddress, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No client address are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function editClient(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:clients,id',
                'address' => '',
                'address.address_line_1' => 'nullable|string',
                'address.address_line_2' => 'nullable|string',
                'address.pincode' => 'nullable|string',
                'address.state' => 'nullable|string',
                'address.city' => 'nullable|string',
                'address.country' => 'nullable|string',
                'client_address_id' => 'numeric|exists:client_address,id',
                'company_name' => 'string',
                'company_person_name' => 'string',
                'company_person_mobile' => 'string',
                'company_person_email' => 'string|email',
                'company_email' => 'string|email',
                'logo'=>'nullable',
                'client_type'=>  [Rule::in(['both', 'buyer', 'supplier'])],
                'tags' => 'array',
                'tags.*.product_tag_id' => 'nullable|numeric|exists:product_tags,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
                $editClient = Client::query()->where('id', $request->id)->first();
                if ($request->has('company_name')) {
                    $editClient->company_name = $request->company_name;
                }
                if ($request->has('company_person_name')) {
                    $editClient->company_person_name = $request->company_person_name;
                }
                if ($request->has('company_person_mobile')) {
                    $editClient->company_person_mobile = $request->company_person_mobile;
                }
                if ($request->has('company_person_email')) {
                    $editClient->company_person_email = $request->company_person_email;
                }
                if ($request->has('company_email')) {
                    $editClient->company_email = $request->company_email;
                }
                if($request->logo!=""){
                    if(!str_contains($request->logo,"http")){
                        $editClient->logo=$this->saveImage($request->logo,$request->company_name);
                    }
                }
                if ($request->has('client_type')) {
                    $editClient->client_type = $request->client_type;
                }
            if (is_array($request->address) || is_object($request->address)) {
                $getSupplierAddress = ClientAddress::query()->where('id', $editClient->client_address_id)->first();
                $getSupplierAddress->address_line_1 = $request->address['address_line_1'];
                $getSupplierAddress->address_line_2 = $request->address['address_line_2'];
                $getSupplierAddress->pincode = $request->address['pincode'];
                $getSupplierAddress->state = $request->address['state'];
                $getSupplierAddress->city = $request->address['city'];
                $getSupplierAddress->country = $request->address['country'];
                $getSupplierAddress->save();
            }
            $editClient->save();
                if (is_array($request->tags) || is_object($request->tags)) {
                    foreach ($request->tags as $tag) {
                        $newClientMappingTag = new ClientMappingTag();
                        $newClientMappingTag->client_id = $editClient->id;
                        $newClientMappingTag->product_tag_id = $tag['product_tag_id'];
                        $newClientMappingTag->save();
                    }
                }
            return $this->sendResponse([], 'Client updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getTrace(), 413);
        }
    }
    public function getAllClient(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
               //    'client_type_id'=>'numeric'
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = Client::query()->with(['client_type','client_address']);
            if($request->has('client_type')){
                    $emails = array_unique(explode(',',$request->client_type));
                    $query = $query->whereIn('client_type', $emails);
                }
                $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getClient = $query->orderBy('id', 'DESC')->get();
            foreach ($getClient as $user){
                if($user['id']!=null){
                    $clienttag=ClientMappingTag::query()->where('client_id',$user['id'])
                    ->with(['tags'])->get();
                    $user['client_tag']=$clienttag;
                }
            }
            if (count($getClient) > 0) {
                return $this->sendResponse(["clients" => $getClient, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No client are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteClientById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:clients,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteClient = Client::query()
            ->where('id', $request->id)->first();
            $deleteClient->delete();
            return $this->sendResponse([],'Client deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getClientById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:clients,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getClient = Client::query()->where('id', $request->id)->with(['client_type','client_address'])->first();
            return $this->sendResponse($getClient, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addClientAddress1(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'address_line_1' => 'required|string',
                'address_line_2' => 'nullable|string',
                'pincode' => 'required|string',
                'state' => 'required|string',
                'city' => 'required|string',
                'country' => 'required|string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newClientAddress = new ClientAddress();
            $newClientAddress->address_line_1 = $request->address_line_1;
            $newClientAddress->address_line_2 = $request->address_line_2;
            $newClientAddress->pincode = $request->pincode;
            $newClientAddress->state = $request->state;
            $newClientAddress->city = $request->city;
            $newClientAddress->country = $request->country;
            $newClientAddress->save();
            return $this->sendResponse($newClientAddress,'Client address added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getTrace(), 413);
        }
    }
    public function editClientAddress(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:client_address,id',
                'address_line_1' => 'string',
                'address_line_2' => 'string',
                'pincode' => 'string',
                'state' => 'string',
                'city' => 'string',
                'country' => 'string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editClientAddress = ClientAddress::query()->where('id', $request->id)->first();
            if ($request->has('address_line_1')) {
                $editClientAddress->address_line_1 = $request->address_line_1;
            }
            if ($request->has('address_line_2')) {
                $editClientAddress->address_line_2 = $request->address_line_2;
            }
            if ($request->has('pincode')) {
                $editClientAddress->pincode = $request->pincode;
            }
            if ($request->has('state')) {
                $editClientAddress->state = $request->state;
            }
            if ($request->has('city')) {
                $editClientAddress->city = $request->city;
            }
            if ($request->has('country')) {
                $editClientAddress->country = $request->country;
            }
            $editClientAddress->save();
            return $this->sendResponse([], 'Client address updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllClientAddress(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = ClientAddress::query();
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getClientAddress = $query->orderBy('id', 'DESC')->get();
            if (count($getClientAddress) > 0) {
                return $this->sendResponse(["client_address" => $getClientAddress, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No client address are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteClientAddressById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:client_address,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteClientAddress = ClientAddress::query()->where('id', $request->id)->first();
            $deleteClientAddress->delete();
            return $this->sendResponse([], 'Client address deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getClientAddressById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:client_address,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getClientAddress = ClientAddress::query()->where('id', $request->id)->first();
            return $this->sendResponse($getClientAddress, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addIndirectTax(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'type' => 'required|string|unique:indirect_tax',
                'percentage' => 'required|numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newIndirectTax = new IndirectTax();
            $newIndirectTax->type = $request->type;
            $newIndirectTax->percentage = $request->percentage;
            $newIndirectTax->save();
            return $this->sendResponse([], 'Indirect tax added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getTrace(), 413);
        }
    }
    public function editIndirectTax(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:indirect_tax,id',
                'type' => 'string|unique:indirect_tax',
                'percentage' => 'numeric|gt:0',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editIndirectTax = IndirectTax::query()->where('id', $request->id)->first();
            if ($request->has('type')) {
                $editIndirectTax->type = $request->type;
            }
            if ($request->has('percentage')) {
                $editIndirectTax->percentage = $request->percentage;
            }
            $editIndirectTax->save();
            return $this->sendResponse([], 'Indirect tax updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllIndirectTax(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = IndirectTax::query();
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getIndirectTax = $query->orderBy('id', 'DESC')->get();
            if (count($getIndirectTax) > 0) {
                return $this->sendResponse(["indirect_tax" => $getIndirectTax, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No Indirect tax are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteIndirectTaxById(Request $request): JsonResponse

    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:indirect_tax,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteIndirectTax = IndirectTax::query()->where('id', $request->id)->first();
            $deleteIndirectTax->delete();
            return $this->sendResponse([], 'Indirect tax deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getIndirectTaxById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:indirect_tax,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getIndirectTax = IndirectTax::query()->where('id', $request->id)->first();
            return $this->sendResponse($getIndirectTax, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addClientType(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|unique:client_type',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newClientType = new ClientType();
            $newClientType->name = $request->name;
            $newClientType->save();
            return $this->sendResponse([], 'Client type added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getTrace(), 413);
        }
    }
    public function getAllClientType(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = ClientType::query();
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getClientType = $query->orderBy('id', 'DESC')->get();
            if (count($getClientType) > 0) {
                return $this->sendResponse(["client_type" => $getClientType, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No Client type are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addQuotCharge(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'description' => 'required|string',
                'total_amount' => 'required|numeric|gt:0',
                'quotation_id' => 'required|numeric|exists:quotation,id',
                'indirect_tax_id' => 'required|numeric|exists:indirect_tax,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newQuotCharges = new QuotCharges();
            $newQuotCharges->description = $request->description;
            $newQuotCharges->total_amount = $request->total_amount;
            $newQuotCharges->quotation_id = $request->quotation_id;
            $newQuotCharges->indirect_tax_id = $request->indirect_tax_id;
            $newQuotCharges->save();
            return $this->sendResponse([], 'Quotation charge added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function editQuotCharge(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'integer|exists:quot_charges,id',
                'description' => 'string',
                'total_amount' => 'numeric|gt:0',
                'quotation_id' => 'numeric|exists:quotation,id',
                'indirect_tax_id' => 'numeric|exists:indirect_tax,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editQuotCharges = QuotCharges::query()->where('id', $request->id)->first();
            if ($request->has('description')) {
                $editQuotCharges->description = $request->description;
            }
            if ($request->has('total_amount')) {
                $editQuotCharges->total_amount = $request->total_amount;
            }
            if ($request->has('quotation_id')) {
                $editQuotCharges->quotation_id = $request->quotation_id;
            }
            if ($request->has('indirect_tax_id')) {
                $editQuotCharges->indirect_tax_id = $request->indirect_tax_id;
            }
            $editQuotCharges->save();
            return $this->sendResponse([], 'Quotation charge updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllQuotCharge(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = QuotCharges::query();
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getQuotCharges = $query->orderBy('id', 'DESC')->get();
            if (count($getQuotCharges) > 0) {
                return $this->sendResponse(["quotation_charges " => $getQuotCharges, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No Product tag are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteQuotChargeById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_charges,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteQuotCharges = QuotCharges::query()->where('id', $request->id)->first();
            $deleteQuotCharges->delete();
            return $this->sendResponse([], 'Quotation charges tag deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getQuotChargeById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_charges,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getQuotCharges = QuotCharges::query()->where('id', $request->id)->first();
            return $this->sendResponse($getQuotCharges, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addTermsAndConditions(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'description' => 'required|string',
                'delivery_terms' => 'nullable|string',
                'payment_terms' => 'nullable|string',
                'transport_terms' => 'nullable|string',
                'important_note' => 'nullable|string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newTermsAndConditions = new TermsAndConditions();
            $newTermsAndConditions->description = $request->description;
            $newTermsAndConditions->delivery_terms = $request->delivery_terms;
            $newTermsAndConditions->payment_terms = $request->payment_terms;
            $newTermsAndConditions->transport_terms = $request->transport_terms;
            $newTermsAndConditions->important_note = $request->important_note;
            $newTermsAndConditions->save();
            return $this->sendResponse([], 'Terms and conditions added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getTrace(), 413);
        }
    }
    public function editTermsAndConditions(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:terms_and_conditaions,id',
                'description' => 'nullable|string',
                'delivery_terms' => 'nullable|string',
                'payment_terms' => 'nullable|string',
                'transport_terms' => 'nullable|string',
                'important_note' => 'nullable|string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editTermsAndConditions = TermsAndConditions::query()->where('id', $request->id)->first();
            if ($request->has('description')) {
                $editTermsAndConditions->description = $request->description;
            }
            if ($request->has('delivery_terms')) {
                $editTermsAndConditions->delivery_terms = $request->delivery_terms;
            }
            if ($request->has('payment_terms')) {
                $editTermsAndConditions->payment_terms = $request->payment_terms;
            }
            if ($request->has('transport_terms')) {
                $editTermsAndConditions->transport_terms = $request->transport_terms;
            }
            if ($request->has('important_note')) {
                $editTermsAndConditions->important_note = $request->important_note;
            }
            $editTermsAndConditions->save();
            return $this->sendResponse([], 'Terms and conditions updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllTermsAndConditions(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = TermsAndConditions::query();
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getTermsAndConditions = $query->orderBy('id', 'DESC')->get();
            if (count($getTermsAndConditions) > 0) {
                return $this->sendResponse(["terms_and_conditaions" => $getTermsAndConditions, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No terms and conditions are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteTermsAndConditionsById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:terms_and_conditaions,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteTermsAndConditions = TermsAndConditions::query()->where('id', $request->id)->first();
            $deleteTermsAndConditions->delete();
            return $this->sendResponse([], 'Terms and conditions deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getTermsAndConditionsById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:terms_and_conditaions,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getTermsAndConditions = TermsAndConditions::query()->where('id', $request->id)->first();
            return $this->sendResponse($getTermsAndConditions, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addPaymentMode(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|unique:payment_mode',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newPaymentMode = new PaymentMode();
            $newPaymentMode->name = $request->name;
            $newPaymentMode->is_active =1;
            $newPaymentMode->save();
            return $this->sendResponse([], 'Payment mode added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getTrace(), 413);
        }
    }
    public function editPaymentMode(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:payment_mode,id',
                'name' => 'string|unique:payment_mode',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editPaymentMode = PaymentMode::query()->where('id', $request->id)->first();
            if ($request->has('name')) {
                $editPaymentMode->name = $request->name;
            }
            if ($request->has('is_active')) {
                $editPaymentMode->is_active = $request->is_active;
            }
            $editPaymentMode->save();
            return $this->sendResponse([], 'Payment mode updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllPaymentMode(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = PaymentMode::query();
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getPaymentMode = $query->orderBy('id', 'DESC')->get();
            if (count($getPaymentMode) > 0) {
                return $this->sendResponse(["payment_mode" => $getPaymentMode, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No Payment mode are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deletePaymentModeById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:payment_mode,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deletePaymentMode = PaymentMode::query()->where('id', $request->id)->first();
            $deletePaymentMode->delete();
            return $this->sendResponse([], 'Payment mode deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getPaymentModeById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:payment_mode,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getPaymentMode = PaymentMode::query()->where('id', $request->id)->first();
            return $this->sendResponse($getPaymentMode, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addPaymentStatus(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|unique:payment_status',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newPaymentStatus = new PaymentStatus();
            $newPaymentStatus->name = $request->name;
            $newPaymentStatus->save();
            return $this->sendResponse([], 'Payment status added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getTrace(), 413);
        }
    }
    public function editPaymentStatus(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:payment_status,id',
                'name' => 'string|unique:payment_status',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editPaymentStatus = PaymentStatus::query()->where('id', $request->id)->first();
            if ($request->has('name')) {
                $editPaymentStatus->name = $request->name;
            }
            $editPaymentStatus->save();
            return $this->sendResponse([], 'Payment status updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllPaymentStatus(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = PaymentStatus::query();
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getPaymentStatus = $query->orderBy('id', 'DESC')->get();
            if (count($getPaymentStatus) > 0) {
                return $this->sendResponse(["payment_status" => $getPaymentStatus, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No payment status are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deletePaymentStatusById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:payment_status,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deletePaymentStatus = PaymentStatus::query()->where('id', $request->id)->first();
            $deletePaymentStatus->delete();
            return $this->sendResponse([], 'Payment status deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getPaymentStatusById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:payment_status,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getPaymentStatus = PaymentStatus::query()->where('id', $request->id)->first();
            return $this->sendResponse($getPaymentStatus, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    // public function addQuotInvoice(Request $request): JsonResponse
    // {
    //     try {
    //         $validator = Validator::make($request->all(), [
    //             'quotation_id' => 'required|numeric|exists:quotation,id',
    //             'payment_mode_id' => 'required|numeric|exists:payment_mode,id',
    //            // 'file' => 'required',
    //           //  'reviewed_by_user_id' => 'required|numeric|exists:users,id',
    //             'payment_date' => 'required|date',
    //             'amount'=>'nullable|numeric|gt:0',

    //         ]);
    //         if ($validator->fails()) {
    //             return $this->sendError('Validation Error.', $validator->errors());
    //         }
    //         $newQuotInvoice = new QuotInvoice();
    //         $newQuotInvoice->quotation_id = $request->quotation_id;
    //         $newQuotInvoice->payment_mode_id = $request->payment_mode_id;
    //         if ($request->hasFile('file')) {
    //             $newQuotInvoice->file = $this->saveFile($request->file('file'));
    //         }
    //         $newQuotInvoice->reviewed_by_user_id = $request->reviewed_by_user_id;
    //         $newQuotInvoice->payment_date = $request->payment_date;
    //         $newQuotInvoice->reference_no = 'TXIN'.'000'.(QuotInvoice::query()->count());
    //         $newQuotInvoice->amount = $request->amount;
    //         $newQuotInvoice->save();
    //         $newQuotpayment = new Quotpayment();
    //         $newQuotpayment->quotation_id = $newQuotInvoice->quotation_id;
    //         $newQuotpayment->amount_recived = $newQuotInvoice->amount;
    //         $newQuotpayment->quot_invoice_id = $newQuotInvoice->id;
    //         $newQuotpayment->save();
    //         return $this->sendResponse([], 'Quotation invoice created successfully', true);
    //     } catch (Exception $e) {
    //         return $this->sendError('Something went wrong', $e->getTrace(), 413);
    //     }
    // }
    // public function editQuotInvoice(Request $request): JsonResponse
    // {
    //     try {
    //         $validator = Validator::make($request->all(), [
    //             'id' => 'required|integer|exists:quot_invoice,id',
    //             'quotation_id' => 'numeric|exists:quotation,id',
    //             'payment_mode_id' => 'numeric|exists:payment_mode,id',
    //             'file' => 'required',
    //             'reviewed_by_user_id' => 'numeric|exists:users,id',
    //             'payment_date' => 'date',
    //             'amount'=>'nullable|numeric|gt:0',
    //         ]);
    //         if ($validator->fails()) {
    //             return $this->sendError('Validation Error.', $validator->errors());
    //         }
    //         $editQuotInvoice = QuotInvoice::query()->where('id', $request->id)->first();

    //         if ($request->has('quotation_id')) {
    //             $editQuotInvoice->quotation_id = $request->quotation_id;
    //         }
    //         if ($request->has('payment_mode_id')) {
    //             $editQuotInvoice->payment_mode_id = $request->payment_mode_id;
    //         }
    //         if ($request->hasFile('file')) {
    //             $editQuotInvoice->file = $this->saveFile($request->file('file'));
    //         }
    //         if ($request->has('reviewed_by_user_id')) {
    //             $editQuotInvoice->reviewed_by_user_id = $request->reviewed_by_user_id;
    //         }
    //         if ($request->has('payment_date')) {
    //             $editQuotInvoice->payment_date = $request->payment_date;
    //         }
    //         if ($request->has('amount')) {
    //             $editQuotInvoice->amount = $request->amount;
    //         }
    //         $editQuotInvoice->save();
    //         $newQuotpayment = new Quotpayment();
    //         $newQuotpayment->quotation_id = $editQuotInvoice->quotation_id;
    //         $newQuotpayment->amount_recived = $editQuotInvoice->amount;
    //         $newQuotpayment->quot_invoice_id = $editQuotInvoice->id;
    //         $newQuotpayment->save();
    //         return $this->sendResponse([], 'Quotation invoice updated successfully');
    //     } catch (Exception $e) {
    //         return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
    //     }
    // }
    // public function getAllQuotInvoice(Request $request): JsonResponse
    // {
    //     try {
    //         $validator = Validator::make($request->all(), [
    //             'limit' => 'numeric',
    //             'pageNo' => 'numeric',
    //         ]);
    //         if ($validator->fails()) {
    //             return $this->sendError('Validation Error.', $validator->errors());
    //         }
    //         $query = QuotInvoice::query()->with(['quotation','reviewed_by_user','payment_mode']);
    //         $count = $query->count();
    //         if ($request->has('pageNo') && $request->has('limit')) {
    //             $limit = $request->limit;
    //             $pageNo = $request->pageNo;
    //             $skip = $limit * $pageNo;
    //             $query = $query->skip($skip)->limit($limit);
    //         }
    //         $getQuotInvoice = $query->orderBy('id', 'DESC')->get();
    //         if (count($getQuotInvoice) > 0) {
    //             return $this->sendResponse(["QuotInvoices" => $getQuotInvoice, 'count' => $count], 'Data fetch successfully');
    //         } else {
    //             return $this->sendResponse([], 'No quotation invoice address are available', false);
    //         }
    //     } catch (Exception $e) {
    //         return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
    //     }
    // }
    // public function deleteQuotInvoiceById(Request $request): JsonResponse
    // {
    //     try {
    //         $validator = Validator::make($request->all(), [
    //             'id' => 'required|integer|exists:quot_invoice,id',
    //         ]);
    //         if ($validator->fails()) {
    //             return $this->sendError('Validation Error.', $validator->errors());
    //         }
    //         $deleteQuotInvoice = QuotInvoice::query()
    //         ->where('id', $request->id)->first();
    //         $deleteQuotInvoice->delete();
    //         return $this->sendResponse([], 'Quotation invoice deleted successfully', true);
    //     } catch (Exception $e) {
    //         return $this->sendError('Something went wrong', $e->getMessage(), 413);
    //     }
    // }
    // public function getQuotInvoiceById(Request $request): JsonResponse
    // {
    //     try
    //     {
    //         $validator = Validator::make($request->all(), [
    //             'id' => 'required|integer|exists:quot_invoice,id',
    //         ]);
    //         if ($validator->fails()) {
    //             return $this->sendError('Validation Error.', $validator->errors());
    //         }
    //         $getQuotInvoice = QuotInvoice::query()->where('id', $request->id)->with(['quotation','reviewed_by_user','payment_mode'])->first();
    //         return $this->sendResponse($getQuotInvoice, 'Data fetch successfully', true);
    //     } catch (Exception $e) {
    //         return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
    //     }
    // }


    public function createQuotationOrder(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'quotation_id' => 'required|numeric|exists:quotation,id',
                // 'reference_no' => 'required',
                'expected_delivery_date' => 'required|date',
                'title' => 'nullable|string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getQuotation = Quotation::query()->where('id',$request->quotation_id)->first();
            if($getQuotation){
                if($getQuotation->parent_quot==null){
                    $allChildQuot = Quotation::query()->where('parent_quot',$getQuotation->id)->get();
                    foreach($allChildQuot as $child){
                        $childQuot = Quotation::query()->where('id',$child->id)->first();
                        $childQuot->is_cancelled = true;
                        $childQuot->quot_status_id=2;
                        $childQuot->save();
                    }
                }
                if($getQuotation->parent_quot!=null){
                    $parentQuot = Quotation::query()->where('id',$getQuotation->parent_quot)->first();
                    $parentQuot->is_cancelled = true;
                    $parentQuot->quot_status_id=2;
                    $parentQuot->save();
                    $allSiblingQuot = Quotation::query()->where('parent_quot',$getQuotation->parent_quot)->get();
                    foreach($allSiblingQuot as $sibling){
                        if($sibling->id!=$getQuotation->id){
                            $siblingQuot = Quotation::query()->where('id',$sibling->id)->first();
                            $siblingQuot->is_cancelled = true;
                            $siblingQuot->quot_status_id=2;
                            $siblingQuot->save();
                        }
                    }
                }
            }
            $user = Auth::user()->store_id;
            $newQuotOc = new QuotOc();
            $newQuotOc->quotation_id = $request->quotation_id;
            $count = QuotOc::count() + 1;
            $reference_no = 'OC' . str_pad($count, 4, '0', STR_PAD_LEFT);
            $newQuotOc->reference_no = $reference_no;
            $newQuotOc->expected_delivery_date = $request->expected_delivery_date;
            $newQuotOc->title = $request->title;
            $newQuotOc->cgst = $request->cgst;
            $newQuotOc->sgst = $request->sgst;
            $newQuotOc->igst = $request->igst;
            $newQuotOc->save();

            // $quotOc = QuotOc::where('quotation_id', $request->quotation_id)->where('is_stock_updated', 0)->exists();
            // $quotChallan = QuotChallan::where('quotation_id', $request->quotation_id)->where('is_stock_updated', 0)->exists();
            // $quotInvoice = QuotTaxInvoice::where('quotation_id', $request->quotation_id)->where('is_stock_updated', 0)->exists();

            // if ($quotOc || $quotChallan || $quotInvoice) {

            // $quotation = QuotationDetails::query()->with(['products'])
            //     ->where('quotation_id', $newQuotOc->quotation_id)->first();
            // $getqty = $quotation->qty;
            // $getproduct = $quotation->product_id;

            // $inventory = Inventory::query()->where('store_id', $user)
            //     ->where('product_id', $getproduct)->first();

            // $getinventoryqty = $inventory->qty;

            // $inventoryUpdatedqty = $getinventoryqty - $getqty;
            // $inventory->qty = $inventoryUpdatedqty;

            // $inventory->save();

            // QuotOc::where('quotation_id', $newQuotOc->quotation_id)->update(['is_stock_updated' => 1]);

            // QuotChallan::where('quotation_id', $newQuotOc->quotation_id)->update(['is_stock_updated' => 1]);

            // QuotTaxInvoice::where('quotation_id', $newQuotOc->quotation_id)->update(['is_stock_updated' => 1]);

            // }
            // $getAllocationstock= QuotationDetails::query()->with(['products'])
            // ->where('quotation_id', $newQuotOc->quotation_id)->get();
            // foreach($getAllocationstock as $data){
            //     $newStockAllocation=new StockAllocation();
            //     $newStockAllocation->store_id=$user;
            //     $newStockAllocation->quotation_id=$newQuotOc->quotation_id;
            //     $newStockAllocation->product_id=$data['product_id'];
            //     $newStockAllocation->allocated_qty=$data['qty'];
            //     $inventory = Inventory::query()->where('store_id', $user)
            //     ->where('product_id', $newStockAllocation->product_id)->first();

            //      $getinventoryqty = $inventory->qty;

            //     $inventoryUpdatedqty = $getinventoryqty - $newStockAllocation->allocated_qty;
            //     $inventory->qty = $inventoryUpdatedqty;

            //     $inventory->save();
            //     $newStockAllocation->save();
            // }
            $getproductAndqty=QuotationDetails::query()->with(['products'])->where('quotation_id',$newQuotOc->quotation_id)->get();

                foreach($getproductAndqty as $data){
                    $getproduct=$data->product_id;

                     $getqty=$data->qty;

                     $getInventory=Inventory::query()->where('store_id',$user)
                     ->where('product_id',$getproduct)->first();
                      //   if($getInventory==null){
                //         return $this->sendResponse([], 'Product not in found inventory', false);
                //     }else{
                    $getinventoryqty=$getInventory->qty;
                    $inventoryqty=$getinventoryqty-$getqty;
                    $getInventory->qty=$inventoryqty;
                    $getStockAlloucation=$getInventory->stock_allocation;
                    $stockAlloucation=$getStockAlloucation + $getqty;
                    $getInventory->stock_allocation=$stockAlloucation;
                    $getInventory->save();
                //}
                }
            $clientdata = Quotation::query()->where('id', $newQuotOc->quotation_id)->with(['client'])->first();
            if (!$clientdata) {
                return $this->sendError('Validation Error.', 'Quotation not found');
            }

            $clientname = $clientdata->client->company_name;
            $to_email = $clientdata->client->company_person_email;
            $store=auth::user()->store_id;
            $storeDetails=Store::query()->where('id',$store)->first();
            $login_comanpany_name=$storeDetails->name;
            $user=auth::user()->id;
            $loginDetails=User::query()->where('id',$user)->first();
            $helplinemail=$loginDetails->email;
            $url=$request->url;
            $cruent_id=$newQuotOc->id;
            $data = array('quotation_number' => $newQuotOc->reference_no,
            'expected_delivery_date' => $newQuotOc->expected_delivery_date,
            'company_name' => $clientname,
            'login_company_name' => $login_comanpany_name,
            'help_line_email'=>$helplinemail,
            'url'=>$url. '/' .$cruent_id,
        );

            Mail::send('emails.quotationConfirmation', $data, function($message) use ($to_email) {

                $message->to($to_email)
                    ->subject('Quotation Confirmation Details');
                $message->from(env('MAIL_FROM_ADDRESS'), 'NEUROERP System Mail');
            });

            return $this->sendResponse([], 'Order Confirm successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function editQuotationOrder(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_oc,id',
                'quotation_id' => 'numeric|exists:quotation,id',
                'expected_delivery_date' => 'date',
                'title' => 'nullable|string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editQuotOc = QuotOc::query()->where('id', $request->id)->first();
            if ($request->has('quotation_id')) {
                $editQuotOc->quotation_id = $request->quotation_id;
            }
            if ($request->has('expected_delivery_date')) {
                $editQuotOc->expected_delivery_date = $request->expected_delivery_date;
            }
            if ($request->has('title')) {
                $editQuotOc->title = $request->title;
            }
            $editQuotOc->save();
            return $this->sendResponse([], 'Order updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllQuotationOrder(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = QuotOc::query()->with(['quotation','quotation.client','quotation.created_by_user','quotation.reviewed_by_user','quotation.tnc','quotation.payment_status','quotation.quot_status','quotation.quot_status','quotation.bank_details','quotation.delivery_address','quotation.client.client_address','quotation.logistic_details']);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getQuotOc = $query->orderBy('id', 'DESC')->get();
            foreach ($getQuotOc as $user){
                if($user['quotation_id']!=null){
                    $product=QuotationDetails::query()->where('quotation_id',$user['quotation_id'])
                    ->with(['products'])->get();
                    $user['quotation_details']=$product;
                }
            }
            if (count($getQuotOc) > 0) {
                return $this->sendResponse(["order_confirmation" => $getQuotOc, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No oredr are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteQuotationOrderById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_oc,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteQuotOc = QuotOc::query()->where('id', $request->id)->first();
            $deleteQuotOc->delete();
            return $this->sendResponse([], 'Order deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getQuotationOrderById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_oc,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getQuotOc = QuotOc::query()->where('id', $request->id)->with(['quotation','quotation.client','quotation.created_by_user','quotation.reviewed_by_user','quotation.tnc','quotation.payment_status','quotation.quot_status','quotation.quot_status','quotation.bank_details','quotation.delivery_address','quotation.client.client_address','quotation.logistic_details'])->first();
            if ($getQuotOc['quotation_id'] != null) {
                $product = QuotationDetails::query()->where('quotation_id', $getQuotOc['quotation_id'])
                    ->with(['products'])->get();
                $getQuotOc['quotation_details'] = $product;
            }
            return $this->sendResponse($getQuotOc, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getQuotationOrderConfirmationNextId(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $prefix=DocumentSeries::query()->get();

            $response = 'OC'.'000'.(QuotOc::query()->count()+1);
            return $this->sendResponse(["next_id"=>$response], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getQuotationInvoiceNextId(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [

            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $response = 'QTI'.'000'.(QuotTaxInvoice::query()->count()+1);
            return $this->sendResponse(["next_id"=>$response], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addQuotStatus(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|unique:quot_status',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newQuotStatus = new QuotStatus();
            $newQuotStatus->name = $request->name;
            $newQuotStatus->is_active =1;
            $newQuotStatus->save();
            return $this->sendResponse([], 'Quotation status added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function editQuotStatus(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_status,id',
                'name' => 'string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editQuotStatus = QuotStatus::query()->where('id', $request->id)->first();
            if ($request->has('name')) {
                $editQuotStatus->name = $request->name;
            }
            if ($request->has('is_active')) {
                $editQuotStatus->is_active = $request->is_active;
            }
            $editQuotStatus->save();
            return $this->sendResponse([], 'Quotation status updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllQuotStatus(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = QuotStatus::query();
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getQuotStatus = $query->orderBy('id', 'DESC')->get();
            if (count($getQuotStatus) > 0) {
                return $this->sendResponse(["quotation_status" => $getQuotStatus, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No quotation status are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteQuotStatusById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_status,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteQuotStatus = QuotStatus::query()->where('id', $request->id)->first();
            $deleteQuotStatus->delete();
            return $this->sendResponse([], 'Quotation status deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getQuotStatuseById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_status,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getQuotStatus = QuotStatus::query()->where('id', $request->id)->first();
            return $this->sendResponse($getQuotStatus, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addDocumentType(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|unique:document_types',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newDocumentType = new DocumentType();
            $newDocumentType->name = $request->name;
            $newDocumentType->save();
            return $this->sendResponse([], 'Document type added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function editDocumentType(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:document_types,id',
                'name' => 'string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editDocumentType = DocumentType::query()->where('id', $request->id)->first();
            if ($request->has('name')) {
                $editDocumentType->name = $request->name;
            }
            if ($request->has('is_auto_generated')) {
                $editDocumentType->is_auto_generated = $request->is_auto_generated;
            }
            $editDocumentType->save();
            return $this->sendResponse([], 'Document type updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllDocumentType(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = DocumentType::query();
            $count = $query->count();
            if($request->has('pageNo') && $request->has('limit')){
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit*$pageNo;
                $query= $query->skip($skip)->limit($limit);
            }
            $getDocumentType = $query->orderBy('id', 'DESC')->get();
            if (count($getDocumentType) > 0) {
                return $this->sendResponse(["document_type" => $getDocumentType, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No document type are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteDocumentTypeById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:document_types,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteDocumentType = DocumentType::query()->where('id', $request->id)->first();
            $deleteDocumentType->delete();
            return $this->sendResponse([], 'Document type deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getDocumentTypeById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:document_types,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getDocumentType = DocumentType::query()->where('id', $request->id)->first();
            return $this->sendResponse($getDocumentType, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function documentSeries(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string',
                'prefix' => 'required|string',
                'next_number' => 'required|string|unique:document_series',
                'document_type_id' => 'required|integer|exists:document_types,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newDocumentSeries = new DocumentSeries();
            $newDocumentSeries->name = $request->name;
            $newDocumentSeries->prefix = $request->prefix;
            $newDocumentSeries->next_number = $request->next_number;
            $newDocumentSeries->document_type_id = $request->document_type_id;
            $nextDocumentSeries=$newDocumentSeries->prefix.'/'.$newDocumentSeries->next_number;
            $newDocumentSeries->save();
            return $this->sendResponse($nextDocumentSeries, 'Document series created successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function createLogisticDetail(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'logistic_type' => 'required|string',
                'description' => 'required|string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $createLogisticDetails=new LogisticDetails;
            $createLogisticDetails->logistic_type = $request->logistic_type;
            $createLogisticDetails->description = $request->description;
            $createLogisticDetails->save();
            return $this->sendResponse([], 'Logistic details added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function editLogisticDetail(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:logistic_details,id',
                'logistic_type' => 'required|string',
                'description' => 'required|string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editLogisticDetails = LogisticDetails::query()->where('id', $request->id)->first();
            if ($request->has('logistic_type')) {
                $editLogisticDetails->logistic_type = $request->logistic_type;
            }
            if ($request->has('description')) {
                $editLogisticDetails->description = $request->description;
            }
            $editLogisticDetails->save();
            return $this->sendResponse([], 'Logistic details updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getAllLogisticDetails(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = LogisticDetails::query();
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getLogisticDetails = $query->orderBy('id', 'DESC')->get();
            if (count($getLogisticDetails) > 0) {
                return $this->sendResponse(["logistic_details" => $getLogisticDetails, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No logistic details are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getLogisticDetailById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:logistic_details,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getLogisticDetails = LogisticDetails::query()->where('id', $request->id)->first();
            return $this->sendResponse(["logistic_details" =>$getLogisticDetails], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteLogisticDetailById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:logistic_details,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteLogisticDetails = LogisticDetails::query()->where('id', $request->id)->first();
            $deleteLogisticDetails->delete();
            return $this->sendResponse([], 'Logistic details deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    // public function createChallan(Request $request): JsonResponse
    // {
    //     try {
    //         $validator = Validator::make($request->all(), [
    //             'quotation_id' => 'required|numeric|exists:quotation,id',
    //             'transporter_details_id' => 'nullable|numeric|exists:transporter_details,id',
    //             'transporter_doc_no'=>'nullable|string',
    //             'vehical_no'=>'nullable|string',
    //             'transportation_doc_date'=>'nullable|date',
    //             'delivery_note'=>'nullable|string',
    //             'kind_attention'=>'nullable|string',
    //             'signature_file' => 'nullable',
    //             'tnc_id' => 'nullable|numeric|exists:terms_and_conditaions,id',
    //             'comment' => 'nullable|string',
    //             'logistic_details_id' => 'nullable|numeric|exists:logistic_details,id',
    //             'pay_to_transporter'=>'nullable|integer',
    //             'attachment_file' => 'nullable',
    //             'products' => 'required|array',
    //             'products.*.product_id' => 'required|numeric',
    //             'products.*.qty' => 'required|numeric|gt:0',
    //             'products.*.price' => 'required|numeric|gt:0',
    //             'products.*.discount' => 'nullable|numeric',
    //             'products.*.delivery_date' => 'nullable|date',
    //             'products.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
    //             'products.*.comment' => 'nullable|string',
    //             // 'products.*.total_tax' => 'nullable|gt:0',
    //             'charges' => 'array',
    //             'charges.*.description' => 'nullable|string',
    //             'charges.*.total_amount' => 'nullable|gt:0',
    //             'charges.*.indirect_tax_id' => 'nullable|exists:indirect_tax,id',
    //             'charges.*.total_tax' => 'nullable|gt:0',
    //         ]);
    //         if ($validator->fails()) {
    //             return $this->sendError('Validation Error.', $validator->errors());
    //         }
    //         $remainingQty = QuotationDetails::query()
    //         ->where('quotation_id', $request->quotation_id)
    //         ->pluck('remaining_qty');

    //     if ($remainingQty->sum() <= 0) {
    //         return $this->sendResponse([],'Your invoice product are dispatch successfully.',false);

    //     }
    //         $newQuotChallan = new QuotChallan();
    //         $newQuotChallan->quotation_id = $request->quotation_id;
    //         $newQuotChallan->transporter_details_id = $request->transporter_details_id;
    //         $count = QuotChallan::count() + 1;
    //         $reference_no = 'CL' . str_pad($count, 4, '0', STR_PAD_LEFT);
    //         $newQuotChallan->reference_no = $reference_no;
    //         $newQuotChallan->transporter_doc_no = $request->transporter_doc_no;
    //         if ($request->signature_file != "") {
    //             if (!str_contains($request->signature_file, "http")) {
    //                 $newQuotChallan->signature_file = $this->saveImage($request->signature_file, $request->transporter_doc_no);
    //             }
    //         }
    //         $newQuotChallan->vehical_no = $request->vehical_no;
    //         $newQuotChallan->transportation_doc_date = $request->transportation_doc_date;
    //         $newQuotChallan->delivery_note = $request->delivery_note;
    //         $newQuotChallan->kind_attention = $request->kind_attention;
    //         $newQuotChallan->tnc_id = $request  ->tnc_id;
    //         $newQuotChallan->pay_to_transporter = $request->pay_to_transporter;
    //         $newQuotChallan->comment = $request->comment;
    //         $newQuotChallan->logistic_details_id = $request->logistic_details_id;
    //         $newQuotChallan->cgst = $request->cgst;
    //         $newQuotChallan->sgst = $request->sgst;
    //         $newQuotChallan->igst = $request->igst;
    //         $newQuotChallan->site_details = $request->site_details;
    //         $newQuotChallan->total_amount = $request->total_amount;
    //         if ($request->attachment_file != "") {
    //             if (!str_contains($request->attachment_file, "http")) {
    //                 $newQuotChallan->attachment_file = $this->saveImage($request->attachment_file, $request->transporter_doc_no);
    //             }
    //         }
    //         $amount=Quotation::query()->where('id',$request->quotation_id)->first();
    //         $totalAmount=$amount->total_amount;
    //         $remainingAmount=$amount->remaining_amount;
    //         $finalAmount=$totalAmount-$remainingAmount;
    //         $amount->remaining_amount=$finalAmount;

    //         $newQuotChallan->save();
    //         $amount->save();
    //         $totalamount=0.0;
    //         if (is_array($request->products) || is_object($request->products)) {
    //             $productCount = count($request->products);
    //         foreach ($request->products as $eachProduct) {
    //             $newQuotChallanDetails = new QuotChallanDetails();
    //             $newQuotChallanDetails->quot_challan_id = $newQuotChallan->id;
    //             $newQuotChallanDetails->product_id = $eachProduct['product_id'];
    //             $newQuotChallanDetails->qty = $eachProduct['qty'];
    //             $newQuotChallanDetails->price = $eachProduct['price'];
    //             $newQuotChallanDetails->discount = $eachProduct['discount'];
    //             $newQuotChallanDetails->delivery_date = $eachProduct['delivery_date'];
    //             $newQuotChallanDetails->indirect_tax_id = $eachProduct['indirect_tax_id'];
    //             $newQuotChallanDetails->comment = $eachProduct['comment'];
    //             $totalamount=$newQuotChallanDetails->qty*$newQuotChallanDetails->modified_amount;
    //             $newQuotChallanDetails->total_before_tax =$totalamount;
    //             $newQuotChallanDetails->total_tax = $eachProduct['total_tax'];
    //             $newQuotChallanDetails->discount_percentage = $eachProduct['discount_percentage'];
    //             $qty=QuotationDetails::query()->where('quotation_id',$newQuotChallan->quotation_id)
    //             ->where('product_id',$newQuotChallanDetails->product_id)->first();
    //             $remaingQty=$qty->qty;
    //             // dd($remaingQty);
    //             $finalQty=$remaingQty-$newQuotChallanDetails->qty;
    //             $sendQty=$qty->send_qty;
    //             $qty->remaining_qty = $finalQty;

    //             if($sendQty==0){
    //                 $qty->send_qty=$eachProduct['qty'];
    //             }
    //             else{
    //                 $addqty=$sendQty+$newQuotChallanDetails->qty;
    //                 $qty->send_qty=$addqty;
    //             }
    //             $qty->save();
    //             $newQuotChallanDetails->discount_percentage = $eachProduct['discount_percentage'];
    //             $newQuotChallanDetails->save();

    //             $transferstock=Inventory::query()->where('product_id',$newQuotChallanDetails->product_id)
    //             ->where('store_id',Auth::user()->store_id)->first();

    //             if($transferstock!=null){
    //                 $toatalStock=$transferstock->stock_allocation - $newQuotChallanDetails->qty;
    //                 $transferstock->stock_allocation=$toatalStock;
    //                 $transferstock->save();
    //             }
    //         }
    //     }
    //         if (is_array($request->charges) || is_object($request->charges)) {
    //             foreach ($request->charges as $eachcharges) {
    //                 $charges = new QuotChallanExtraCharges();
    //                 $charges->quot_challan_id = $newQuotChallan->id;
    //                 $charges->description = $eachcharges['description'];
    //                 $charges->total_amount = $eachcharges['total_amount'];
    //                 $charges->indirect_tax_id = $eachcharges['indirect_tax_id'];
    //                 $charges->total_tax = $eachcharges['total_tax'];
    //                 $charges->save();
    //             }
    //         }


    //         $clientdata = Quotation::query()->where('id', $newQuotChallan->quotation_id)->with(['client'])->first();
    //         if (!$clientdata) {
    //             return $this->sendError('Validation Error.', 'Quotation not found');
    //         }
    //         $clientname = $clientdata->client->company_name;
    //         $to_email = $clientdata->client->company_person_email;
    //         $store=auth::user()->store_id;
    //         $storeDetails=Store::query()->where('id',$store)->first();
    //         $login_comanpany_name=$storeDetails->name;
    //         $user=auth::user()->id;
    //         $loginDetails=User::query()->where('id',$user)->first();
    //         $helplinemail=$loginDetails->email;
    //         $url=$request->url;
    //         $cruent_id=$newQuotChallan->id;
    //         $data = array('challan_number' => $newQuotChallan->reference_no,
    //         'no_of_item' => $productCount,'company_name' => $clientname,
    //         'delivery_date'=>$newQuotChallanDetails->delivery_date,
    //         'login_company_name' => $login_comanpany_name,
    //         'help_line_email'=>$helplinemail,
    //         'url'=>$url. '/' .$cruent_id,
    //     );

    //         Mail::send('emails.quotationChallan', $data, function($message) use ($to_email) {
    //             $message->to($to_email)
    //                 ->subject('Challan Details');
    //             $message->from(env('MAIL_FROM_ADDRESS'), 'NEUROERP System Mail');
    //         });
    //         return $this->sendResponse($newQuotChallan->id, 'Challan created successfully', true);
    //     } catch (Exception $e) {
    //         return $this->sendError('Something went wrong', $e->getTrace(), 413);
    //     }
    // }
    public function createChallan(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'quotation_id' => 'required|numeric|exists:quotation,id',
                'transporter_details_id' => 'nullable|numeric|exists:transporter_details,id',
                'transporter_doc_no'=>'nullable|string',
                'vehical_no'=>'nullable|string',
                'transportation_doc_date'=>'nullable|date',
                'delivery_note'=>'nullable|string',
                'kind_attention'=>'nullable|string',
                'signature_file' => 'nullable',
                'tnc_id' => 'nullable|numeric|exists:terms_and_conditaions,id',
                'comment' => 'nullable|string',
                'logistic_details_id' => 'nullable|numeric|exists:logistic_details,id',
                'pay_to_transporter'=>'nullable|integer',
                'attachment_file' => 'nullable',
                'products' => 'required|array',
                'products.*.product_id' => 'required|numeric',
                'products.*.qty' => 'required|numeric|gt:0',
                'products.*.price' => 'required|numeric|gt:0',
                'products.*.discount' => 'nullable|numeric',
                'products.*.delivery_date' => 'nullable|date',
                'products.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'products.*.comment' => 'nullable|string',
                // 'products.*.total_tax' => 'nullable|gt:0',
                'charges' => 'array',
                'charges.*.description' => 'nullable|string',
                'charges.*.total_amount' => 'nullable',
                'charges.*.indirect_tax_id' => 'nullable|exists:indirect_tax,id',
                'charges.*.total_tax' => 'nullable',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $remainingQty = QuotationDetails::query()
            ->where('quotation_id', $request->quotation_id)
            ->pluck('remaining_qty');

        if ($remainingQty->sum() <= 0) {
            return $this->sendResponse([],'Your invoice product are dispatch successfully.',false);

        }
            $newQuotChallan = new QuotChallan();
            $newQuotChallan->quotation_id = $request->quotation_id;
            $newQuotChallan->transporter_details_id = $request->transporter_details_id;
            $count = QuotChallan::count() + 1;
            $reference_no = 'CL' . str_pad($count, 4, '0', STR_PAD_LEFT);
            $newQuotChallan->reference_no = $reference_no;
            $newQuotChallan->transporter_doc_no = $request->transporter_doc_no;
            if ($request->signature_file != "") {
                if (!str_contains($request->signature_file, "http")) {
                    $newQuotChallan->signature_file = $this->saveImage($request->signature_file, $request->transporter_doc_no);
                }
            }
            $newQuotChallan->delivery_address_id=$request->delivery_address_id;
            $newQuotChallan->vehical_no = $request->vehical_no;
            $newQuotChallan->transportation_doc_date = $request->transportation_doc_date;
            $newQuotChallan->delivery_note = $request->delivery_note;
            $newQuotChallan->kind_attention = $request->kind_attention;
            $newQuotChallan->tnc_id = $request  ->tnc_id;
            $newQuotChallan->pay_to_transporter = $request->pay_to_transporter;
            $newQuotChallan->comment = $request->comment;
            $newQuotChallan->logistic_details_id = $request->logistic_details_id;
            $newQuotChallan->cgst = $request->cgst;
            $newQuotChallan->sgst = $request->sgst;
            $newQuotChallan->igst = $request->igst;
            $newQuotChallan->billing_address_id = $request->billing_address_id;
            if($request->quot_tax_invoice_id){
                $newQuotChallan->quot_tax_invoice_id = $request->quot_tax_invoice_id;
            }
            else{
                $newQuotChallan->quot_tax_invoice_id =null;
            }
            $newQuotChallan->site_details = $request->site_details;
            //$newQuotChallan->total_amount = $request->total_amount;
            if ($request->attachment_file != "") {
                if (!str_contains($request->attachment_file, "http")) {
                    $newQuotChallan->attachment_file = $this->saveImage($request->attachment_file, $request->transporter_doc_no);
                }
            }
            $amount=Quotation::query()->where('id',$request->quotation_id)->first();
            $totalAmount=$amount->total_amount;
            $remainingAmount=$amount->remaining_amount;
            $finalAmount=$totalAmount-$remainingAmount;
            $amount->remaining_amount=$finalAmount;

            $newQuotChallan->save();
            $amount->save();
            $totalamount=0.0;
            $totalAmount=0.0;
            $totalDiscount=0.0;
            $totalTax=0.0;
            if (is_array($request->products) || is_object($request->products)) {
                $productCount = count($request->products);
            foreach ($request->products as $eachProduct) {
                $newQuotChallanDetails = new QuotChallanDetails();
                $newQuotChallanDetails->quot_challan_id = $newQuotChallan->id;
                $newQuotChallanDetails->product_id = $eachProduct['product_id'];
                $newQuotChallanDetails->qty = $eachProduct['qty'];
                $newQuotChallanDetails->price = $eachProduct['price'];
                $totalamount=$newQuotChallanDetails->qty*$newQuotChallanDetails->price;
                //$newQuotChallanDetails->total_before_tax =$totalamount;
                $newQuotChallanDetails->discount_percentage = $eachProduct['discount_percentage'];

                $discount = ($newQuotChallanDetails->discount_percentage / 100) * $totalamount;

                $newQuotChallanDetails->discount = $discount;
                $finalAmount=$totalamount-$discount;
                $newQuotChallanDetails->total_before_tax =$finalAmount;
                $newQuotChallanDetails->delivery_date = $eachProduct['delivery_date'];
                $tax = 0;
                $percentage=0;
            if(!is_null($eachProduct['indirect_tax_id'])){
                $newQuotChallanDetails->indirect_tax_id = $eachProduct['indirect_tax_id'];
                $getTaxPercentage=IndirectTax::query()->where('id',$newQuotChallanDetails->indirect_tax_id)->first();
                $percentage=$getTaxPercentage->percentage;
                $tax = ($percentage / 100) * $finalAmount;
            }
                $newQuotChallanDetails->total_tax = $tax;
                $newQuotChallanDetails->tax_percentage = $percentage;
                $newQuotChallanDetails->comment = $eachProduct['comment'];
                $qty=QuotationDetails::query()->where('quotation_id',$newQuotChallan->quotation_id)
                ->where('product_id',$newQuotChallanDetails->product_id)->first();
                $remaingQty=$qty->qty;
                // dd($remaingQty);
                $finalQty=$remaingQty-$newQuotChallanDetails->qty;
                $sendQty=$qty->send_qty;
                $qty->remaining_qty = $finalQty;

                if($sendQty==0){
                    $qty->send_qty=$eachProduct['qty'];
                }
                else{
                    $addqty=$sendQty+$newQuotChallanDetails->qty;
                    $qty->send_qty=$addqty;
                }
                $qty->save();

                $newQuotChallanDetails->save();

                $transferstock=Inventory::query()->where('product_id',$newQuotChallanDetails->product_id)
                ->where('store_id',Auth::user()->store_id)->first();

                if($transferstock!=null){
                    $toatalStock=$transferstock->stock_allocation - $newQuotChallanDetails->qty;
                    $transferstock->stock_allocation=$toatalStock;
                    $transferstock->save();
                }
                $totalAmount += $totalamount;
                $totalDiscount += $discount;
                $totalTax += $tax;
            }
        }
        $totatExtrachargesTax=0.0;
        $totalExtracharges=0.0;
            if (is_array($request->charges) || is_object($request->charges)) {
                foreach ($request->charges as $eachcharges) {
                    $charges = new QuotChallanExtraCharges();
                    $charges->quot_challan_id = $newQuotChallan->id;
                    $charges->description = $eachcharges['description'];
                    $charges->total_amount = $eachcharges['total_amount'];
                    $extrachargestax=0;
                    if(!is_null($eachcharges['indirect_tax_id'])){
                        $charges->indirect_tax_id = $eachcharges['indirect_tax_id'];
                        $getTaxPercentage=IndirectTax::query()->where('id',$charges->indirect_tax_id)->first();

                       $percentage=$getTaxPercentage->percentage;
                        $extrachargestax = ($percentage / 100) * $eachcharges['total_amount'];
                    }

                    $charges->total_tax =$extrachargestax;
                    $totalcharges=$charges->total_amount;
                    $charges->save();
                    $totalExtracharges += $totalcharges;
                    $totatExtrachargesTax += $extrachargestax;
                    $charges->save();
                }
            }
            $finalTaxAmount=$totalTax+$totatExtrachargesTax;
            $newQuotChallan->subtotal=round($totalAmount,2);
            $newQuotChallan->discount_amount=round($totalDiscount,2);
            $newQuotChallan->total_tax_amount=round($finalTaxAmount,2);
            $newQuotChallan->extra_charges_amount=round($totalExtracharges,2);
            $grandTotal=$totalAmount-$totalDiscount+$totalTax+$totalExtracharges+$totatExtrachargesTax;

        if($request->roundOffCalculation){
            $roundOffAmount = round($grandTotal);
            $newQuotChallan->round_off = round($roundOffAmount -$grandTotal,2);
            $newQuotChallan->total_amount=$roundOffAmount;
        }else{
            $newQuotChallan->total_amount =$grandTotal;
        }

            $newQuotChallan->save();


            $clientdata = Quotation::query()->where('id', $newQuotChallan->quotation_id)->with(['client'])->first();
            if (!$clientdata) {
                return $this->sendError('Validation Error.', 'Quotation not found');
            }
            $clientname = $clientdata->client->company_name;
            $to_email = $clientdata->client->company_person_email;
            $store=auth::user()->store_id;
            $storeDetails=Store::query()->where('id',$store)->first();
            $login_comanpany_name=$storeDetails->name;
            $user=auth::user()->id;
            $loginDetails=User::query()->where('id',$user)->first();
            $helplinemail=$loginDetails->email;
            $url=$request->url;
            $cruent_id=$newQuotChallan->id;
            $data = array('challan_number' => $newQuotChallan->reference_no,
            'no_of_item' => $productCount,'company_name' => $clientname,
            'delivery_date'=>$newQuotChallanDetails->delivery_date,
            'login_company_name' => $login_comanpany_name,
            'help_line_email'=>$helplinemail,
            'url'=>$url. '/' .$cruent_id,
        );

            Mail::send('emails.quotationChallan', $data, function($message) use ($to_email) {
                $message->to($to_email)
                    ->subject('Challan Details');
                $message->from(env('MAIL_FROM_ADDRESS'), 'NEUROERP System Mail');
            });
            return $this->sendResponse($newQuotChallan->id, 'Challan created successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function editChallan(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'quotation_id' => 'nullable|numeric|exists:quotation,id',
                'transporter_details_id' => 'nullable|numeric|exists:transporter_details,id',
                'transporter_doc_no'=>'nullable|string',
                'vehical_no'=>'nullable|string',
                'transportation_doc_date'=>'nullable|date',
                'delivery_note'=>'nullable|string',
                'kind_attention'=>'nullable|string',
                'signature_file' => 'nullable',
                'tnc_id' => 'nullable|numeric|exists:terms_and_conditaions,id',
                'comment' => 'nullable|string',
                'logistic_details_id' => 'nullable|numeric|exists:logistic_details,id',
                'pay_to_transporter'=>'nullable|integer',
                'attachment_file' => 'nullable',
                'products' => 'nullable|array',
                'products.*.product_id' => 'nullable|numeric',
                'products.*.qty' => 'nullable|numeric|gt:0',
                'products.*.price' => 'nullable|numeric|gt:0',
                'products.*.discount' => 'nullable|numeric',
                'products.*.delivery_date' => 'nullable|date',
                'products.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'products.*.comment' => 'nullable|string',
                // 'products.*.total_tax' => 'nullable|gt:0',
                'charges' => 'array',
                'charges.*.description' => 'nullable|string',
                'charges.*.total_amount' => 'nullable|gt:0',
                'charges.*.indirect_tax_id' => 'nullable|exists:indirect_tax,id',
                'charges.*.total_tax' => 'nullable|gt:0',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $editChallan = QuotChallan::query()->where('id',$request->id)->first();
            if ($request->has('quotation_id')) {
                $editChallan->quotation_id = $request->quotation_id;
            }
            if ($request->has('transporter_details_id')) {
                $editChallan->transporter_details_id = $request->transporter_details_id;
            }
            if ($request->signature_file != "") {
                if (!str_contains($request->signature_file, "http")) {
                    $editChallan->signature_file = $this->saveImage($request->signature_file, $request->client_id);
                }
            }
            if ($request->has('transporter_doc_no')) {
                $editChallan->transporter_doc_no = $request->transporter_doc_no;
            }
            if ($request->has('vehical_no')) {
                $editChallan->vehical_no = $request->vehical_no;
            }
            if ($request->has('transportation_doc_date')) {
                $editChallan->transportation_doc_date = $request->transportation_doc_date;
            }
            if ($request->has('delivery_note')) {
                $editChallan->delivery_note = $request->delivery_note;
            }
            if ($request->has('kind_attention')) {
                $editChallan->kind_attention = $request->kind_attention;
            }
            if ($request->has('tnc_id')) {
                $editChallan->tnc_id = $request->tnc_id;
            }
            if ($request->has('pay_to_transporter')) {
                $editChallan->pay_to_transporter = $request->pay_to_transporter;
            }
            if ($request->has('comment')) {
                $editChallan->comment = $request->comment;
            }
            if ($request->has('logistic_details_id')) {
                $editChallan->logistic_details_id = $request->logistic_details_id;
            }
            if ($request->attachment_file != "") {
                if (!str_contains($request->attachment_file, "http")) {
                    $editChallan->attachment_file = $this->saveImage($request->attachment_file, $request->client_id);
                }
            }
            if ($request->has('total_amount')) {
                $editChallan->total_amount = $request->total_amount;
            }
            $editChallan->save();
            QuotChallanDetails::where('quot_challan_id', $editChallan->id)->delete();
            $totalamount=0.0;
            foreach ($request->products as $eachProduct) {
                $newQuotChallanDetails = new QuotChallanDetails();
                $newQuotChallanDetails->quot_challan_id = $editChallan->id;
                $newQuotChallanDetails->product_id = $eachProduct['product_id'];
                $newQuotChallanDetails->qty = $eachProduct['qty'];
                $newQuotChallanDetails->price = $eachProduct['price'];
                $newQuotChallanDetails->discount = $eachProduct['discount'];
                $newQuotChallanDetails->delivery_date = $eachProduct['delivery_date'];
                $newQuotChallanDetails->indirect_tax_id = $eachProduct['indirect_tax_id'];
                $newQuotChallanDetails->comment = $eachProduct['comment'];
                $totalamount=$newQuotChallanDetails->qty*$newQuotChallanDetails->modified_amount;
                $newQuotChallanDetails->total_before_tax =$totalamount;
                $newQuotChallanDetails->total_tax = $eachProduct['total_tax'];
                $newQuotChallanDetails->discount_percentage = $eachProduct['discount_percentage'];
                $newQuotChallanDetails->save();
            }
            QuotChallanExtraCharges::where('quot_challan_id', $editChallan->id)->delete();
            if (is_array($request->charges) || is_object($request->charges)) {
                foreach ($request->charges as $eachcharges) {
                    $charges = new QuotChallanExtraCharges();
                    $charges->quot_challan_id = $editChallan->id;
                    $charges->description = $eachcharges['description'];
                    $charges->total_amount = $eachcharges['total_amount'];
                    $charges->indirect_tax_id = $eachcharges['indirect_tax_id'];
                    $charges->total_tax = $eachcharges['total_tax'];
                    $charges->save();
                }
            }
            return $this->sendResponse([], 'Challan created successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getAllChallan(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = QuotChallan::query()->with(['quotation','tnc','transpoter','Quotation.client',
            'Quotation.tnc','Quotation.payment_status','Quotation.indirect_tax','Quotation.bank_details',
            'Quotation.delivery_address','Quotation.billing_address','Quotation.quot_status','logistic_details']);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getChallan = $query->orderBy('id', 'DESC')->get();
            if (count($getChallan) > 0) {
                return $this->sendResponse(["challan" => $getChallan, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No challan details are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getChallanById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_challan,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getChallan = QuotChallan::query()->where('id', $request->id)->with(['quotation','tnc','transpoter',
            'Quotation.client','Quotation.tnc','Quotation.payment_status','Quotation.indirect_tax',
            'Quotation.bank_details','Quotation.delivery_address','Quotation.billing_address','Quotation.quot_status','logistic_details'])->first();
            if ($getChallan['id'] != null) {
                $product = QuotationDetails::query()->where('quotation_id', $getChallan['quotation_id'])
                ->with(['products','tax'])->get();
                $getChallan['quotation_details'] = $product;
            }
            if ($getChallan['id'] != null) {
                $product = QuotChallanDetails::query()->where('quot_challan_id', $getChallan['id'])
                    ->with(['products','indirect_tax'])->get();
                $getChallan['quotation_challan_details'] = $product;
            }
            if ($getChallan['id'] != null) {
                $product = QuotChallanExtraCharges::query()->where('quot_challan_id', $getChallan['id'])
                    ->with(['indirect_tax'])->get();
                $getChallan['quotation_challan_extra_charges'] = $product;
            }
            if ($getChallan['quotation_id'] != null) {
                $product = QuotOc::query()->where('quotation_id', $getChallan['quotation_id'])
                    ->get();
                $getChallan['qoutation_oc'] = $product;
            }
            return $this->sendResponse(["challan" =>$getChallan], 'Data fetch successfully', true);

        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteChallanById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_challan,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteChallan = QuotChallan::query()->where('id', $request->id)->first();
            $deleteChallan->delete();
            return $this->sendResponse([], 'Challan deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getchallanNextId(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [

            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $response = 'CL'.'000'.(Quotation::query()->count()+1);
            return $this->sendResponse(["next_id"=>$response], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function getReceiptVoucherAmount(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                //'quotation_id' => 'required|integer|exists:receipt_voucher,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getReceiptVoucher = ReceiptVoucher::query()->where('quotation_id', $request->quotation_id)->orderBy('id', 'DESC')->first();

            return $this->sendResponse(["receipt_voucher" =>$getReceiptVoucher], 'Data fetch successfully', true);

        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function addReceiptVouchar(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'payment_date' => 'nullable|date',
                'delivery_address_id' => 'nullable|numeric|exists:client_address,id',
                'comment' => 'nullable|string',
                'advance_description' => 'nullable|string',
                'advance_percentage'=>'nullable',
                'advance_amount'=>'nullable|numeric',
                'tnc_id' => 'nullable|numeric|exists:terms_and_conditaions,id',
                'quotation_id' => 'nullable|numeric|exists:quotation,id',
                'total_amount'=> 'nullable|numeric|gt:0',
                'products' => 'required|array',
                'products.*.product_id' => 'required|numeric|gt:0',
                'products.*.qty' => 'required|numeric|gt:0',
                'products.*.modified_amount' => 'required|numeric|gt:0',
                'products.*.delivery_date' => 'nullable|date',
                'products.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'products.*.advance_amount' => 'nullable|numeric',
                'extra_charges' => 'nullable|array',
                'extra_charges.*.extra_charge_description' => 'nullable|string',
                'extra_charges.*.total_amount' => 'nullable|numeric|gt:0',
                'extra_charges.*.advance' => 'nullable|numeric|gt:0',
                'extra_charges.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'extra_charges.*.total_tax' => 'nullable',
                'amount' => 'nullable|numeric',
                'payment_mode_id' => 'required|numeric|exists:payment_mode,id',
                'payment_account' => 'required|string',
                'reference_number' => 'nullable|string',
                'comment' => 'nullable|string',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newReceiptVoucher = new ReceiptVoucher();
            $count = ReceiptVoucher::count() + 1;
            $reference_no = 'RV' . str_pad($count, 4, '0', STR_PAD_LEFT);
            $newReceiptVoucher->reference_no =$reference_no;
            $newReceiptVoucher->payment_date = $request->payment_date;
            $newReceiptVoucher->delivery_address_id = $request->delivery_address_id;
            if ($request->attachment_file != "") {
                if (!str_contains($request->attachment_file, "http")) {
                    $newReceiptVoucher->attachment_file = $this->saveImage($request->attachment_file, $request->payment_date);
                }
            }
            if ($request->file != "") {
                if (!str_contains($request->file, "http")) {
                    $newReceiptVoucher->file = $this->saveImage($request->file, $request->payment_date);
                }
            }
            $newReceiptVoucher->quotation_id = $request->quotation_id;
            $newReceiptVoucher->advance_description = $request->advance_description;
            $newReceiptVoucher->advance_percentage = $request->advance_percentage;
             $getAdvanceAmount=ReceiptVoucher::query()->where('quotation_id',$newReceiptVoucher->quotation_id)->orderBy('id', 'DESC')->first();

             if($getAdvanceAmount!=null){
                $AdvanceAmount=$getAdvanceAmount->advance_amount;
                $toatalAdvanceAmount=$AdvanceAmount + $request->advance_amount;
            }
            else
            {
                $toatalAdvanceAmount=0+$request->advance_amount;
            }
            $newReceiptVoucher->advance_amount = $toatalAdvanceAmount;
            $newReceiptVoucher->tnc_id = $request->tnc_id;

           //$totalBalanceAmount=$getAdvanceAmount->balance_amount;

            // if($totalBalanceAmount!=0){
            $newReceiptVoucher->total_amount = $request->total_amount;
            $balanceamount=$newReceiptVoucher->total_amount - $newReceiptVoucher->advance_amount;
            $newReceiptVoucher->balance_amount=$balanceamount;
            // }
            // else{
            //     return $this->sendResponse([], 'The quotation amount has been fully paid.', false);
            // }
            $newReceiptVoucher->save();
            if(is_array($request->products) || is_object($request->products)){
            foreach ($request->products as $eachProduct) {
                $newReceiptVoucherDetails = new ReceiptVoucherDetails();
                $newReceiptVoucherDetails->receipt_voucher_id = $newReceiptVoucher->id;
                $newReceiptVoucherDetails->product_id = $eachProduct['product_id'];
                $newReceiptVoucherDetails->qty = $eachProduct['qty'];
                $newReceiptVoucherDetails->modified_amount = $eachProduct['modified_amount'];
                $newReceiptVoucherDetails->delivery_date = $eachProduct['delivery_date'];
                $newReceiptVoucherDetails->indirect_tax_id = $eachProduct['indirect_tax_id'];
                $newReceiptVoucherDetails->advance_amount = $eachProduct['advance_amount'];
                $newReceiptVoucherDetails->save();
            }
        }
            if(is_array($request->extra_charges) || is_object($request->extra_charges)){
            foreach($request->extra_charges as $extra_charge){
                $newReceiptVoucherExtraCharges = new ReceiptVoucherExtraCharges();
                $newReceiptVoucherExtraCharges->receipt_voucher_id = $newReceiptVoucher->id;
                $newReceiptVoucherExtraCharges->extra_charge_description = $extra_charge['extra_charge_description'];
                $newReceiptVoucherExtraCharges->total_amount = $extra_charge['total_amount'];
                $newReceiptVoucherExtraCharges->advance = $extra_charge['advance'];
                $newReceiptVoucherExtraCharges->indirect_tax_id = $extra_charge['indirect_tax_id'];
                $newReceiptVoucherExtraCharges->total_tax = $extra_charge['total_tax'];
                $newReceiptVoucherExtraCharges->save();
            }
        }
        $newPaymentDetails = new PaymentDetails();
        $newPaymentDetails->receipt_voucher_id = $newReceiptVoucher->id;
        $newPaymentDetails->amount = $request->amount;
        $newPaymentDetails->payment_mode_id = $request->payment_mode_id;
        $newPaymentDetails->payment_account = $request->payment_account;
        $newPaymentDetails->reference_number = $request->reference_number;
        $newPaymentDetails->comment = $request->comment;
        $newPaymentDetails->save();

        $clientdata = Quotation::query()->where('id', $newReceiptVoucher->quotation_id)->with(['client'])->first();
        if (!$clientdata) {
            return $this->sendError('Validation Error.', 'Quotation not found');
        }
        $clientname = $clientdata->client->company_name;
        $to_email = $clientdata->client->company_person_email;
        $store=auth::user()->store_id;
        $storeDetails=Store::query()->where('id',$store)->first();
        $login_comanpany_name=$storeDetails->name;
        $user=auth::user()->id;
        $loginDetails=User::query()->where('id',$user)->first();
        $helplinemail=$loginDetails->email;
        $url=$request->url;
        $cruent_id=$newReceiptVoucher->id;
        $data = array('receipt_voucher_number' => $newReceiptVoucher->reference_no,'company_name' => $clientname,
        'recived_amount'=>$newPaymentDetails->amount,
        'login_company_name' => $login_comanpany_name,
        'help_line_email'=>$helplinemail,
        'url'=>$url. '/' .$cruent_id,
    );

        Mail::send('emails.receiptVoucher', $data, function($message) use ($to_email) {

            $message->to($to_email)
                ->subject('Receipt Voucher Details');
            $message->from(env('MAIL_FROM_ADDRESS'), 'NEUROERP System Mail');
        });
            return $this->sendResponse($newReceiptVoucher->id, 'Receipt vouchar created successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getReceiptVoucherById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|numeric|exists:receipt_voucher,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getReceiptVouchers = ReceiptVoucher::query()->where('id', $request->id)->with(['delivery_address','tnc'])->first();
            if ($getReceiptVouchers['id'] != null) {
                $product = ReceiptVoucherDetails::query()->where('receipt_voucher_id', $getReceiptVouchers['id'])
                    ->with(['products','indirect_tax'])->get();
                $getReceiptVouchers['receipt_voucher_details'] = $product;
            }
            if ($getReceiptVouchers['id'] != null) {
                $product = ReceiptVoucherExtraCharges::query()->where('receipt_voucher_id', $getReceiptVouchers['id'])
                    ->with(['indirect_tax'])->get();
                $getReceiptVouchers['receipt_voucher_details'] = $product;
            }
            if ($getReceiptVouchers['id'] != null) {
                $product = PaymentDetails::query()->where('receipt_voucher_id', $getReceiptVouchers['id'])
                    ->with(['payment_mode'])->get();
                $getReceiptVouchers['receipt_voucher_details'] = $product;
            }
            if ($getReceiptVouchers['id'] != null) {
                $product = Quotation::query()->where('id', $getReceiptVouchers['quotation_id'])
                ->with(['client','created_by_user','reviewed_by_user','tnc',
                'payment_status','quot_status','quot_status','bank_details','delivery_address','client.client_address'])->get();
                $getReceiptVouchers['quotation'] = $product;
            }
            if ($getReceiptVouchers['id'] != null) {
                $product = QuotationDetails::query()->where('id', $getReceiptVouchers['quotation_id'])
                ->with(['products','tax'])->get();
                $getReceiptVouchers['quotation_details'] = $product;
            }
            if ($getReceiptVouchers['id'] != null) {
                $product = QuotCharges::query()->where('id', $getReceiptVouchers['quotation_id'])
                ->with(['indirect_tax'])->get();
                $getReceiptVouchers['quotation_extra_charges'] = $product;
            }
            return $this->sendResponse(["receipt_voucher" =>$getReceiptVouchers], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function sendQuotationMail(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'quotation_id' => 'required|numeric',
            'emails' => 'nullable|array',
            'emails.*' => 'nullable|email',
            'pdf_file' => 'required|mimes:pdf',
        ]);
        if ($validator->fails()) {
            return $this->sendError('Validation Error.', $validator->errors());
        }
        $quotation = Quotation::with('client')->findOrFail($request->quotation_id);
        $client_email = $quotation->client->company_email;
        $to_email = $client_email;
        if (!empty($request->emails)) {
            $valid_emails = array_filter($request->emails, function ($email) {
                return filter_var($email, FILTER_VALIDATE_EMAIL);
            });
            $additional_emails = implode(',', $valid_emails);
            $to_email .= ',' . $additional_emails;
        }
        $to_email = explode(',', $to_email);
        $pdf_path = $request->pdf_file->store('pdfs');
        $data = ['pdf_path' => $pdf_path];
        Mail::send('emails.sendQuotation', $data, function ($message) use ($to_email, $pdf_path) {
            $message->to($to_email)
                ->subject('Quotation');
            $message->attach(storage_path('app/' . $pdf_path));
            $message->from(env('MAIL_FROM_ADDRESS'), 'NEURO ERP System Mail');
        });
        return $this->sendResponse([], 'Quotation Sent Successfully', true);
    }
    public function addQuotInvoice(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'quotation_id' => 'required|numeric|exists:quotation,id',
                'payment_date' => 'date',
                'amount' => 'nullable|numeric',
                'document_date' => 'date',
                'payment_terms_id' => 'required|numeric|exists:payment_terms,id',
                'delivery_address_id' => 'required|numeric|exists:client_address,id',
                'comment' => 'nullable|string',
                'kind_attention' => 'nullable|string',
                'store_id' => 'nullable|numeric|exists:stores,id',
                'total' => 'nullable|numeric',
                'delivery_note'=>'nullable|string',
                'logistic_details_id' => 'nullable|numeric|exists:logistic_details,id',
                'tnc_id' => 'nullable|numeric|exists:terms_and_conditaions,id',
                'bank_detail_id' => 'required|numeric|exists:bank_details,id',
                'products' => 'required|array',
                'products.*.product_id' => 'required|numeric|exists:products,id',
                'products.*.qty' => 'required|numeric|gt:0',
                'products.*.modified_amount' => 'required|numeric|gt:0',
                'products.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'extra_charges' => 'nullable|array',
                'extra_charges.*.extra_charge_description' => 'nullable|string',
                'extra_charges.*.total_amount' => 'nullable|numeric|gt:0',
                'extra_charges.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'extra_charges.*.total_tax' => 'nullable',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newQuotTaxInvoice = new QuotTaxInvoice();
            $count = QuotTaxInvoice::count() + 1;
            $reference_no = 'QTI' . str_pad($count, 4, '0', STR_PAD_LEFT);
            $newQuotTaxInvoice->reference_no = $reference_no;
            $newQuotTaxInvoice->quotation_id = $request->quotation_id;
            $newQuotTaxInvoice->payment_date = $request->payment_date;
            $newQuotTaxInvoice->document_date = $request->document_date;
            $newQuotTaxInvoice->payment_terms_id = $request->payment_terms_id;
            $newQuotTaxInvoice->delivery_address_id = $request->delivery_address_id;
            $newQuotTaxInvoice->billing_address_id = $request->billing_address_id;
            if($request->quot_challan_id){
                $newQuotTaxInvoice->quot_challan_id = $request->quot_challan_id;
            }
            else{
                $newQuotTaxInvoice->quot_challan_id =null;
            }
            if ($request->attachment_file != "") {
                if (!str_contains($request->attachment_file, "http")) {
                    $newQuotTaxInvoice->attachment_file = $this->saveImage($request->attachment_file, $request->payment_date);
                }
            }
            if ($request->file != "") {
                if (!str_contains($request->file, "http")) {
                    $newQuotTaxInvoice->file = $this->saveImage($request->file, $request->payment_date);
                }
            }
            $newQuotTaxInvoice->amount = $request->amount;
            $newQuotTaxInvoice->kind_attention = $request->kind_attention;
            $newQuotTaxInvoice->delivery_note = $request->delivery_note;
            $newQuotTaxInvoice->total = $request->total;
            $newQuotTaxInvoice->tnc_id = $request->tnc_id;
            $newQuotTaxInvoice->bank_details_id = $request->bank_details_id;
            $newQuotTaxInvoice->logistic_details_id = $request->logistic_details_id;
            $newQuotTaxInvoice->store_id = $request->store_id;
            $newQuotTaxInvoice->cgst = $request->cgst;
            $newQuotTaxInvoice->sgst = $request->sgst;
            $newQuotTaxInvoice->igst = $request->igst;
            $newQuotTaxInvoice->save();
            $totalamount=0.0;
            $totalAmount=0.0;
            $totalDiscount=0.0;
            $totalTax=0.0;
            if (is_array($request->products) || is_object($request->products)) {
                foreach ($request->products as $eachProduct) {
                    $newQuotTaxInvoiceProductsDetails = new QuotTaxInvoiceProduct();
                    $newQuotTaxInvoiceProductsDetails->quot_tax_invoice_id = $newQuotTaxInvoice->id;
                    $newQuotTaxInvoiceProductsDetails->product_id = $eachProduct['product_id'];
                    $newQuotTaxInvoiceProductsDetails->qty = $eachProduct['qty'];
                    $newQuotTaxInvoiceProductsDetails->modified_amount = $eachProduct['modified_amount'];
                    $totalamount=$newQuotTaxInvoiceProductsDetails->qty*$newQuotTaxInvoiceProductsDetails->modified_amount;

                    $newQuotTaxInvoiceProductsDetails->total_before_tax =$totalamount;
                    $newQuotTaxInvoiceProductsDetails->discount_percentage = $eachProduct['discount_percentage'];

                    $discount = ($newQuotTaxInvoiceProductsDetails->discount_percentage / 100) * $totalamount;

                    $newQuotTaxInvoiceProductsDetails->discount = $discount;
                    $finalAmount=$totalamount-$discount;
                    // $newQuotTaxInvoiceProductsDetails->delivery_date = $eachProduct['delivery_date'];
                    $tax = 0;
            if(!is_null($eachProduct['indirect_tax_id'])){
                $newQuotTaxInvoiceProductsDetails->indirect_tax_id = $eachProduct['indirect_tax_id'];
                $getTaxPercentage=IndirectTax::query()->where('id',$newQuotTaxInvoiceProductsDetails->indirect_tax_id)->first();
                $percentage=$getTaxPercentage->percentage;
                $tax = ($percentage / 100) * $finalAmount;
            }
                $newQuotTaxInvoiceProductsDetails->total_tax = $tax;
                $newQuotTaxInvoiceProductsDetails->tax_percentage = $percentage;
                //$newQuotTaxInvoiceProductsDetails->comment = $eachProduct['comment'];
                    $newQuotTaxInvoiceProductsDetails->save();
                }
                $totalAmount += $totalamount;
                $totalDiscount += $discount;
                $totalTax += $tax;
            }
            $totatExtrachargesTax=0.0;
            $totalExtracharges=0.0;
            if (is_array($request->extra_charges) || is_object($request->extra_charges)) {
                foreach ($request->extra_charges as $extra_charge) {
                    $newQuotTaxInvoiceExtraCharges = new QuotTaxInvoiceExtraCharges();
                    $newQuotTaxInvoiceExtraCharges->quot_tax_invoice_id = $newQuotTaxInvoice->id;
                    $newQuotTaxInvoiceExtraCharges->extra_charge_description = $extra_charge['extra_charge_description'];
                    $newQuotTaxInvoiceExtraCharges->total_amount = $extra_charge['total_amount'];
                    $extrachargestax=0;
                    if(!is_null($extra_charge['indirect_tax_id'])){
                        $newQuotTaxInvoiceExtraCharges->indirect_tax_id = $extra_charge['indirect_tax_id'];
                        $getTaxPercentage=IndirectTax::query()->where('id',$newQuotTaxInvoiceExtraCharges->indirect_tax_id)->first();

                       $percentage=$getTaxPercentage->percentage;
                        $extrachargestax = ($percentage / 100) * $extra_charge['total_amount'];
                    }

                    $newQuotTaxInvoiceExtraCharges->total_tax =$extrachargestax;
                    $totalcharges=$newQuotTaxInvoiceExtraCharges->total_amount;
                    $newQuotTaxInvoiceExtraCharges->save();
                    $totalExtracharges += $totalcharges;
                    $totatExtrachargesTax += $extrachargestax;
                }

            }
            $finalTaxAmount=$totalTax+$totatExtrachargesTax;
            $newQuotTaxInvoice->subtotal=round($totalAmount,2);
            $newQuotTaxInvoice->discount_amount=round($totalDiscount,2);
            $newQuotTaxInvoice->total_tax_amount=round($finalTaxAmount,2);
            $newQuotTaxInvoice->extra_charges_amount=round($totalExtracharges,2);
            $grandTotal=$totalAmount-$totalDiscount+$totalTax+$totalExtracharges+$totatExtrachargesTax;
            if($request->roundOffCalculation){
                $roundOffAmount = round($grandTotal);
                $newQuotTaxInvoice->round_off = round($roundOffAmount -$grandTotal,2);
                $newQuotTaxInvoice->amount=$roundOffAmount;
            }else{
                $newQuotTaxInvoice->amount =$grandTotal;
            }
            $newQuotTaxInvoice->save();
            return $this->sendResponse($newQuotTaxInvoice->id, 'Quotation tax invoice created successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getAllQuotInvoice(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'pageNo' => 'numeric',
                'limit' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors(), 400);
            }
            $query = QuotTaxInvoice::query()
                ->with(['delivery_address', 'quotation', 'payment_terms','billing_address','challan']);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $data = $query->orderBy('id', 'DESC')->get();
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = QuotTaxInvoiceProduct::query()->where('quot_tax_invoice_id', $user['id'])
                        ->with(['products', 'indirect_tax'])->get();
                    $user['quot_tax_invoice_details'] = $product;
                }
            }
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = QuotTaxInvoiceExtraCharges::query()->where('quot_tax_invoice_id', $user['id'])
                        ->with(['indirect_tax'])->get();
                    $user['quot_tax_invoice_extra_charges'] = $product;
                }
            }
            if (count($data) > 0) {
                $response['quot_invoice_tax'] = $data;
                $response['count'] = $count;
                return $this->sendResponse($response, 'Data Fetched Successfully', true);
            } else {
                return $this->sendResponse('No Data Available', [], false);
            }
        } catch (Exception $e) {
            return $this->sendError($e->getMessage(), $e->getTrace(), 500);
        }
    }
    public function getQuotInvoiceById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_tax_invoice,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getPOTaxInvoice = QuotTaxInvoice::query()->where('id', $request->id)->with(['delivery_address',
            'quotation', 'payment_terms','billing_address','challan'])->first();
            if ($getPOTaxInvoice['id'] != null) {
                $product = QuotTaxInvoiceProduct::query()->where('quot_tax_invoice_id', $getPOTaxInvoice['id'])
                    ->with(['products', 'indirect_tax'])->get();
                $getPOTaxInvoice['quot_tax_invoice_details'] = $product;
            }
            if ($getPOTaxInvoice['id'] != null) {
                $product = QuotTaxInvoiceExtraCharges::query()->where('quot_tax_invoice_id', $getPOTaxInvoice['id'])
                    ->with(['indirect_tax'])->get();
                $getPOTaxInvoice['quot_tax_invoice_extra_charges'] = $product;
            }
            return $this->sendResponse(["quot_invoice_tax" => $getPOTaxInvoice], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteQuotInvoiceById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:po_tax_invoice,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $user = QuotTaxInvoice::query()->where('id', $request->id)->first();
            $user->delete();
            return $this->sendResponse([], 'PO tax invoice deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }

    public function addIndividulClient(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'address' => 'nullable',
                'address.address_line_1' => 'nullable|string|required',
                'address.address_line_2' => 'nullable|string',
                'address.pincode' => 'nullable|string|required',
                'address.state' => 'nullable|string|required',
                'address.city' => 'nullable|string|required',
                'address.country' => 'nullable|string|required',
                'fisrt_name' => 'required|string',
                'last_name' => 'required|string',
                'contact_number' => 'required|string',
                'contact_email' => 'required|string|email',
                'dob' => 'string|date',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newAddress = new ClientAddress();
            $newAddress->address_line_1 = $request->address['address_line_1'];
            $newAddress->address_line_2 = $request->address['address_line_2'];
            $newAddress->pincode = $request->address['pincode'];
            $newAddress->state = $request->address['state'];
            $newAddress->city = $request->address['city'];
            $newAddress->country = $request->address['country'];
            $newAddress->save();
            $newIndividulClient = new IndividulClient();
            $newIndividulClient->client_address_id =$newAddress->id;
            $newIndividulClient->fisrt_name = $request->fisrt_name;
            $newIndividulClient->last_name = $request->last_name;
            $newIndividulClient->contact_number = $request->contact_number;
            $newIndividulClient->contact_email = $request->contact_email;
            $newIndividulClient->gender = $request->gender;
            $newIndividulClient->dob = $request->dob;
            $newIndividulClient->save();
            $newAddress->client_id=$newIndividulClient->id;
            $newAddress->address_for='individul_client';
            $newAddress->save();
            return $this->sendResponse([], 'Client added successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function editIndividulClient(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:individul_client,id',
                'address' => '',
                'address.address_line_1' => 'nullable|string',
                'address.address_line_2' => 'nullable|string',
                'address.pincode' => 'nullable|string',
                'address.state' => 'nullable|string',
                'address.city' => 'nullable|string',
                'address.country' => 'nullable|string',
                'fisrt_name' => 'required|string',
                'last_name' => 'required|string',
                'contact_number' => 'required|string',
                'contact_email' => 'required|string|email',
                'dob' => 'string|date',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
                $editClient = IndividulClient::query()->where('id', $request->id)->first();
                if ($request->has('fisrt_name')) {
                    $editClient->fisrt_name = $request->fisrt_name;
                }
                if ($request->has('last_name')) {
                    $editClient->last_name = $request->last_name;
                }
                if ($request->has('contact_number')) {
                    $editClient->contact_number = $request->contact_number;
                }
                if ($request->has('contact_email')) {
                    $editClient->contact_email = $request->contact_email;
                }
                if ($request->has('dob')) {
                    $editClient->dob = $request->dob;
                }

            if (is_array($request->address) || is_object($request->address)) {
                $getSupplierAddress = ClientAddress::query()->where('id', $editClient->client_address_id)->first();
                $getSupplierAddress->address_line_1 = $request->address['address_line_1'];
                $getSupplierAddress->address_line_2 = $request->address['address_line_2'];
                $getSupplierAddress->pincode = $request->address['pincode'];
                $getSupplierAddress->state = $request->address['state'];
                $getSupplierAddress->city = $request->address['city'];
                $getSupplierAddress->country = $request->address['country'];
                $getSupplierAddress->save();
            }
            $editClient->save();

            return $this->sendResponse([], 'Client updated successfully');
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getTrace(), 413);
        }
    }
    public function getAllIndividulClient(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
               //    'client_type_id'=>'numeric'
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $query = IndividulClient::query()->with(['client_address']);

                $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $getClient = $query->orderBy('id', 'DESC')->get();

            if (count($getClient) > 0) {
                return $this->sendResponse(["clients" => $getClient, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No client are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteIndividulClientById(Request $request): JsonResponse

    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:clients,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $deleteClient = IndividulClient::query()
            ->where('id', $request->id)->first();
            $deleteClient->delete();
            return $this->sendResponse([],'Client deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getIndividulClientById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:clients,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getClient = IndividulClient::query()->where('id', $request->id)->with(['client_address'])->first();
            return $this->sendResponse($getClient, 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }

    public function addQuotProformaInvoice(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'quotation_id' => 'required|numeric|exists:quotation,id',
                'payment_date' => 'nullable|date',
                'po_number'=>'nullable|string',
                'po_date'=>'nullable|date',
                'amount' => 'nullable|integer|gt:0',
                'document_date' => 'nullable|date',
                'payment_terms_id' => 'nullable|numeric|exists:payment_terms,id',
                'delivery_address_id' => 'nullable|numeric|exists:client_address,id',
                'comment' => 'nullable|string',
                'kind_attention' => 'nullable|string',
                'total_amount' => 'nullable',
                'delivery_note'=>'nullable|string',
                'logistic_details_id' => 'nullable|numeric|exists:logistic_details,id',
                'tnc_id' => 'nullable|numeric|exists:terms_and_conditaions,id',
                'bank_detail_id' => 'nullable|numeric|exists:bank_details,id',
                'products' => 'required|array',
                'products.*.product_id' => 'required|numeric|exists:products,id',
                'products.*.qty' => 'required|numeric|gt:0',
                'products.*.modified_amount' => 'required|numeric|gt:0',
                'products.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'extra_charges' => 'nullable|array',
                'extra_charges.*.extra_charge_description' => 'nullable|string',
                'extra_charges.*.total_amount' => 'nullable|numeric|gt:0',
                'extra_charges.*.indirect_tax_id' => 'nullable|numeric|exists:indirect_tax,id',
                'extra_charges.*.total_tax' => 'nullable',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $newQuotProformaInvoice= new QuotProformaInvoice();
            $count = QuotProformaInvoice::count() + 1;
            $reference_no = 'QPI' . str_pad($count, 4, '0', STR_PAD_LEFT);
            $newQuotProformaInvoice->reference_no = $reference_no;
            $newQuotProformaInvoice->quotation_id = $request->quotation_id;
            $newQuotProformaInvoice->payment_date = $request->payment_date;
            $newQuotProformaInvoice->document_date = $request->document_date;
            $newQuotProformaInvoice->payment_terms_id = $request->payment_terms_id;
            $newQuotProformaInvoice->delivery_address_id = $request->delivery_address_id;
            $newQuotProformaInvoice->billing_address_id=$request->billing_address_id;
            if ($request->attachment_file != "") {
                if (!str_contains($request->attachment_file, "http")) {
                    $newQuotProformaInvoice->attachment_file = $this->saveImage($request->attachment_file, $request->payment_date);
                }
            }
            if ($request->file != "") {
                if (!str_contains($request->file, "http")) {
                    $newQuotProformaInvoice->file = $this->saveImage($request->file, $request->payment_date);
                }
            }
            $newQuotProformaInvoice->amount = $request->amount;
            $newQuotProformaInvoice->kind_attention = $request->kind_attention;
            $newQuotProformaInvoice->total_amount = $request->total_amount;
            $newQuotProformaInvoice->tnc_id = $request->tnc_id;
            $newQuotProformaInvoice->bank_details_id = $request->bank_details_id;
            $newQuotProformaInvoice->logistic_details_id = $request->logistic_details_id;
            $newQuotProformaInvoice->save();
            $totalBeforeTax = 0.0;
            if (is_array($request->products) || is_object($request->products)) {
                foreach ($request->products as $eachProduct) {
                    $newQuotProformaInvoiceProductsDetails = new QuotProformaInvoiceProduct();
                    $newQuotProformaInvoiceProductsDetails->quot_proforma_invoice_id = $newQuotProformaInvoice->id;
                    $newQuotProformaInvoiceProductsDetails->product_id = $eachProduct['product_id'];
                    $newQuotProformaInvoiceProductsDetails->qty = $eachProduct['qty'];
                    $newQuotProformaInvoiceProductsDetails->modified_amount = $eachProduct['modified_amount'];
                    $newQuotProformaInvoiceProductsDetails->indirect_tax_id = $eachProduct['indirect_tax_id'];
                    $totalBeforeTax = $newQuotProformaInvoiceProductsDetails->product_id * $newQuotProformaInvoiceProductsDetails->qty;
                    $newQuotProformaInvoiceProductsDetails->total_before_tax = $totalBeforeTax;
                    $newQuotProformaInvoiceProductsDetails->save();
                }
            }
            if (is_array($request->extra_charges) || is_object($request->extra_charges)) {
                foreach ($request->extra_charges as $extra_charge) {
                    $newQuotProformaInvoiceExtraCharges = new QuotProformaInvoiceExtraCharges();
                    $newQuotProformaInvoiceExtraCharges->quot_proforma_invoice_id = $newQuotProformaInvoice->id;
                    $newQuotProformaInvoiceExtraCharges->extra_charge_description = $extra_charge['extra_charge_description'];
                    $newQuotProformaInvoiceExtraCharges->total_amount = $extra_charge['total_amount'];
                    $newQuotProformaInvoiceExtraCharges->indirect_tax_id = $extra_charge['indirect_tax_id'];
                    $newQuotProformaInvoiceExtraCharges->total_tax = $extra_charge['total_tax'];
                    $newQuotProformaInvoiceExtraCharges->save();
                }
            }
            return $this->sendResponse($newQuotProformaInvoice->id, 'Quotation perform invoice created successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }
    public function getAllQuotProformaInvoice(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'pageNo' => 'numeric',
                'limit' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors(), 400);
            }
            $query = QuotProformaInvoice::query()
                ->with(['delivery_address', 'quotation', 'payment_terms','billing_address']);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            $data = $query->orderBy('id', 'DESC')->get();
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = QuotProformaInvoiceProduct::query()->where('quot_proforma_invoice_id', $user['id'])
                        ->with(['products', 'indirect_tax'])->get();
                    $user['quot_proforma_invoice_details'] = $product;
                }
            }
            foreach ($data as $user) {
                if ($user['id'] != null) {
                    $product = QuotProformaInvoiceExtraCharges::query()->where('quot_proforma_invoice_id', $user['id'])
                        ->with(['indirect_tax'])->get();
                    $user['quot_proforma_invoice_extra_charges'] = $product;
                }
            }
            if (count($data) > 0) {
                $response['quot_proforma_invoice'] = $data;
                $response['count'] = $count;
                return $this->sendResponse($response, 'Data Fetched Successfully', true);
            } else {
                return $this->sendResponse('No Data Available', [], false);
            }
        } catch (Exception $e) {
            return $this->sendError($e->getMessage(), $e->getTrace(), 500);
        }
    }
    public function getQuotProformaInvoiceById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_proforma_invoice,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $getPOTaxInvoice = QuotProformaInvoice::query()->where('id', $request->id)->with(['delivery_address',
            'quotation', 'payment_terms','billing_address'])->first();
            if ($getPOTaxInvoice['id'] != null) {
                $product = QuotProformaInvoiceProduct::query()->where('quot_proforma_invoice_id', $getPOTaxInvoice['id'])
                    ->with(['products', 'indirect_tax'])->get();
                $getPOTaxInvoice['quot_proforma_invoice_details'] = $product;
            }
            if ($getPOTaxInvoice['id'] != null) {
                $product = QuotProformaInvoiceExtraCharges::query()->where('quot_proforma_invoice_id', $getPOTaxInvoice['id'])
                    ->with(['indirect_tax'])->get();
                $getPOTaxInvoice['quot_proforma_invoice_extra_charges'] = $product;
            }
            return $this->sendResponse(["quot_proforma_invoice" => $getPOTaxInvoice], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }
    public function deleteQuotProformaInvoiceById(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:quot_proforma_invoice,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $user = QuotProformaInvoice::query()->where('id', $request->id)->first();
            $user->delete();
            return $this->sendResponse([], 'Quotation proforma invoice deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }

    public function getQuotProformaInvoiceNextId(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [

            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $count = QuotProformaInvoice::count() + 1;
            $reference_no = 'QPI' . str_pad($count, 4, '0', STR_PAD_LEFT);
            $response = $reference_no;
            return $this->sendResponse(["next_id"=>$response], 'Data fetch successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getMessage(), 413);
        }
    }

    public function getAllMaterialRequisition(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'pageNo' => 'numeric',
                'limit' => 'numeric',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors(), 400);
            }
            $query = MaterialRequisition::query()
                ->with(['products', 'quotation', 'store','client','requested_by']);
            $count = $query->count();
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }
            if ($request->has('name')) {
                $query = $query->where('name', 'like', '%' . $request->name . '%');
            }
            if ($request->has('product_code')) {
                $query = $query->where('product_code', 'like', '%' . $request->product_code . '%');
            }
            $data = $query->orderBy('id', 'DESC')->get();

            foreach ($data as $user) {
                if ($user['quotation_id'] !== null) {
                    $product = QuotOc::query()->where('quotation_id', $user['quotation_id'])->get();
                    $user['quot_oc'] = $product;
                    if($product==null){
                        $user['quot_oc']=null;
                    }
                }
                else {
                    $user['quot_oc'] = null;
                }
            }
            if (count($data) > 0) {
                $response['material_requisition'] = $data;
                $response['count'] = $count;
                return $this->sendResponse($response, 'Data Fetched Successfully', true);
            } else {
                return $this->sendResponse('No Data Available', [], false);
            }
        } catch (Exception $e) {
            return $this->sendError($e->getMessage(), $e->getTrace(), 500);
        }
    }
    public function deleteMaterialRequisition(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer|exists:material_requisition,id',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            $user = MaterialRequisition::query()->where('id', $request->id)->first();
            $user->delete();
            return $this->sendResponse([], 'Quotation proforma invoice deleted successfully', true);
        } catch (Exception $e) {
            return $this->sendError('Something went wrong', $e->getMessage(), 413);
        }
    }

    public function getAccountDetails(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
                'type' => [ Rule::in(['sales', 'purchase_order', 'expense'])],
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            if($request->type=='sales'){
            $query = QuotOc::query()->with(['quotation','quotation.client','quotation.created_by_user',
            'quotation.created_by_user.store',
            'quotation.quot_status','quotation.delivery_address',
            'quotation.client.client_address']);
            $getQuotOc = $query->orderBy('id', 'DESC')->get();
            foreach ($getQuotOc as $user){
                if($user['quotation_id']!=null){
                    $product=QuotationDetails::query()->where('quotation_id',$user['quotation_id'])
                    ->with(['products'])->get();
                    $user['quotation_details']=$product;
                }
            }
            foreach ($getQuotOc as $user){
                if($user['quotation_id']!=null){
                    $product=ReceiptVoucher::query()->where('quotation_id',$user['quotation_id'])
                   ->get();
                    $user['receipt_voucher']=$product;

                }
            }
            foreach ($getQuotOc as $user){
                if($user['quotation_id']!=null){
                    $product=QuotTaxInvoice::query()->where('quotation_id',$user['quotation_id'])
                   ->get();
                    $user['quotation_tax_invoice']=$product;

                }
            }
        }
            if($request->type=='purchase_order'){
                $query = PurchaseOrder::query()->with(['client', 'created_by_user','created_by_user.store',
                 'reviewed_by_user', 'tnc', 'payment_status', 'indirect_tax', 'delivery_address', 'client.client_address', 'logistic_details']);
                 $getQuotOc = $query->orderBy('id', 'DESC')->get();

            foreach ($getQuotOc as $user) {
                if ($user['id'] != null) {
                    $product = PoDetails::query()->where('purchase_order_id', $user['id'])
                        ->with(['products', 'indirect_tax'])->get();
                    $user['purchase_order_details'] = $product;
                }
            }
            foreach ($getQuotOc as $user) {
                if ($user['id'] != null) {
                    $product = PoInward::query()->where('purchase_order_id', $user['id'])
                        ->with(['transporter_details'])->get();
                    $user['purchase_order_inward_details'] = $product;
                }
            }
            // foreach ($getQuotOc as $user) {
            //     if ($user['id'] != null) {
            //         $product = POInwardTimeline::query()->where('purchase_order_id', $user['id'])
            //             ->with(['transporter_details'])->get();
            //         $user['purchase_order_inward_details'] = $product;
            //     }
            // }
            foreach ($getQuotOc as $user) {
                if ($user['id'] != null) {
                    $product = POReceiptVoucher::query()->where('purchase_order_id', $user['id'])
                        ->with(['delivery_address'])->get();
                    $user['purchase_order_recived_note_details'] = $product;
                }
            }
        }
            // if('type'=='expence'){

            // }
            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }

            // $getQuotOc = $query->orderBy('id', 'DESC')->get();
            $count = $getQuotOc->count();
            if (count($getQuotOc) > 0) {
                return $this->sendResponse(["data" => $getQuotOc, 'count' => $count], 'Data fetch successfully');
            } else {
                return $this->sendResponse([], 'No oredr are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getTrace(), 413);
        }
    }
    public function getAccountDetailsPaybelAndRecivebleAmount(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }

            $query = QuotOc::query()->with([
                'quotation',
                'quotation.client',
                'quotation.created_by_user',
                'quotation.created_by_user.store',
                'quotation.quot_status',
                'quotation.delivery_address',
                'quotation.client.client_address'
            ]);

            $getQuotOc = $query->orderBy('id', 'DESC')->get();

            foreach ($getQuotOc as $user) {
                if ($user['quotation_id'] != null) {
                    $product = QuotationDetails::query()->where('quotation_id', $user['quotation_id'])
                        ->with(['products'])->get();
                    $user['quotation_details'] = $product;
                }
            }

            foreach ($getQuotOc as $user) {
                if ($user['quotation_id'] != null) {
                    $product = ReceiptVoucher::query()->where('quotation_id', $user['quotation_id'])
                        ->get();
                    $user['receipt_voucher'] = $product;
                }
            }

            foreach ($getQuotOc as $user) {
                if ($user['quotation_id'] != null) {
                    $product = QuotTaxInvoice::query()->where('quotation_id', $user['quotation_id'])
                        ->get();
                    $user['quotation_tax_invoice'] = $product;
                }
            }

            $query = PurchaseOrder::query()->with([
                'client',
                'created_by_user',
                'created_by_user.store',
                'reviewed_by_user',
                'tnc',
                'payment_status',
                'indirect_tax',
                'delivery_address',
                'client.client_address',
                'logistic_details'
            ])->orderBy('id', 'DESC'); // Move the orderBy here

            $getpo = $query->get();

            foreach ($getpo as $user) {
                if ($user['id'] != null) {
                    $product = PoDetails::query()->where('purchase_order_id', $user['id'])
                        ->with(['products', 'indirect_tax'])->get();
                    $user['purchase_order_details'] = $product;
                }
            }

            foreach ($getpo as $user) {
                if ($user['id'] != null) {
                    $product = PoInward::query()->where('purchase_order_id', $user['id'])
                        ->with(['transporter_details'])->get();
                    $user['purchase_order_inward_details'] = $product;
                }
            }

            foreach ($getpo as $user) {
                if ($user['id'] != null) {
                    $product = POReceiptVoucher::query()->where('purchase_order_id', $user['id'])
                        ->with(['delivery_address'])->get();
                    $user['purchase_order_recived_note_details'] = $product;
                }
            }

            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }

            $paybleAmount = $getpo; // Removed the orderBy function here
            $count = $getQuotOc->count();
            $totalAmount = 0;

            foreach ($getQuotOc as $user) {
                if (isset($user['quotation']) && isset($user['quotation']['total_amount'])) {
                    $totalAmount += $user['quotation']['total_amount'];
                }
            }
            $paybletotalAmount = 0;

            foreach ($paybleAmount as $order) {
                if (isset($order['total_amount'])) {
                    $paybletotalAmount += $order['total_amount'];
                }
            }

            if (count($getQuotOc) > 0) {
                return $this->sendResponse(["reciveble_amount" => $totalAmount, 'payble_amount' => $paybletotalAmount], 'Data fetched successfully');
            } else {
                return $this->sendResponse([], 'No orders are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getTrace(), 413);
        }
    }
    public function getAllPendingOC(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'limit' => 'numeric',
                'pageNo' => 'numeric',
                'start_date' => 'date',
                'end_date' => 'date',
            ]);
            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }

            $query = QuotOc::query()->with([
                'quotation',
                'quotation.client',
                'quotation.created_by_user',
                'quotation.reviewed_by_user',
                'quotation.tnc',
                'quotation.payment_status',
                'quotation.quot_status',
                'quotation.quot_status',
                'quotation.bank_details',
                'quotation.delivery_address',
                'quotation.client.client_address',
                'quotation.logistic_details'
            ]);

            if ($request->has('company_id')) {
                $query = $query->whereHas('quotation.client', function ($subQuery) use ($request) {
                    $subQuery->where('client_id', 'like', '%' . $request->company_id . '%');
                });
            }

            if ($request->has('start_date') && $request->has('end_date')) {
                $startDate = $request->start_date;
                $endDate = $request->end_date;
                $query = $query->whereBetween('created_at', [$startDate, $endDate]);
            }

            if ($request->has('pageNo') && $request->has('limit')) {
                $limit = $request->limit;
                $pageNo = $request->pageNo;
                $skip = $limit * $pageNo;
                $query = $query->skip($skip)->limit($limit);
            }

            $getQuotOc = $query->orderBy('id', 'DESC')->get();

            foreach ($getQuotOc as $key => $user) {
                if ($user['quotation_id'] != null) {
                    $product = QuotationDetails::query()
                        ->where('quotation_id', $user['quotation_id'])
                        ->with(['products'])
                        ->get();
                    $user['quotation_details'] = $product;

                    // $quotChallanExists = QuotChallan::query()
                    //     ->where('quotation_id', $user['quotation_id'])
                    //     ->exists();
                    $quotChallanExists = QuotChallan::query()
                        ->where('quotation_id', $user['quotation_id'])
                        ->exists();

                    if ($quotChallanExists) {
                        unset($getQuotOc[$key]);
                    }
                }
            }
            $getQuotOc = json_decode(json_encode($getQuotOc), true);
            $getQuotOc = array_values($getQuotOc);


            if (count($getQuotOc) > 0) {
                return $this->sendResponse(
                    ["order_confirmation" => $getQuotOc, 'count' => count($getQuotOc)],
                    'Data fetched successfully'
                );
            } else {
                return $this->sendResponse([], 'No orders are available', false);
            }
        } catch (Exception $e) {
            return $this->sendError('Something Went Wrong', $e->getTrace(), 413);
        }
    }



}
