<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\LogisticBooking;
use App\Models\LogisticBookingDetail;
use App\Models\LogisticBookingCharge;
use App\Models\LogisticBookingConsignorWaybill;
use App\Models\LogisticBookingInsurance;
use App\Models\LogisticBookingContainerDetail;
use App\Models\AccountAddress;
use App\Models\AccountLicense;
use App\Models\MasterType;
use App\Models\AccountingGroup;
use App\Models\Account;
use App\Models\TransportationMode;
use App\Models\TransportType;
use App\Models\TaxPaidBy;
use App\Models\TaxMaster;
use App\Models\PrimaryUnit;
use App\Models\DeliveryType;
use App\Models\ShippingRisk;
use App\Models\VoucherType;
use App\Models\VoucherMaster;
use App\Models\LicenseType;
use App\Models\ContainerSize;
use App\Models\ContainerType;
use App\Models\CargoType;
use App\Models\CustomClearanceStatus;
use App\Models\ContainerReturnStatus;
use App\Models\PaymentMode;
use App\Models\RateCalculationType;
use App\Models\Country;
use App\Models\CompanyAddress;
use App\Models\AccountContact;
use App\Models\Product;
use App\Models\VehicleType;
use App\Models\ProductPrice;
use App\Models\AdditionalCharge;
use App\Models\AcReceipt;
use App\Models\User;
use App\Models\City;
use App\Models\SaleInvoice;
use App\Models\PaymentTerm;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Carbon\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use DB;

class BookingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        
        $data = LogisticBooking::Select(
            'logistic_bookings.*',
            DB::raw('SUM(logistic_booking_details.total_amount) as total_amount'),
            DB::raw('SUM(logistic_booking_charges.charge_amount) as charge_amount'),
            DB::raw('SUM(logistic_booking_consignor_waybills.consignor_invoice_value) as consignor_invoice_value'),
            'consignor.name as consignor',
            'consignee.name as consignee',
            'vendor.name as vendor',
            'from_location.name as from_location',
            'to_location.name as to_location',
            'transportation_modes.name as transportation_mode',
            'payment_terms.payment_term_name as payment_term',
        )
        ->leftjoin('accounts as consignor','consignor.id','logistic_bookings.consignor_id')
        ->leftjoin('accounts as consignee','consignee.id','logistic_bookings.consignee_id')
        ->leftjoin('accounts as vendor','vendor.id','logistic_bookings.vendor_id')
        ->leftjoin('cities as from_location','from_location.id','logistic_bookings.from_location_id')
        ->leftjoin('cities as to_location','to_location.id','logistic_bookings.to_location_id')
        ->leftjoin('transportation_modes','transportation_modes.id','logistic_bookings.transportation_mode_id')
        ->leftjoin('payment_terms','payment_terms.id','logistic_bookings.payment_term_id')
        ->leftjoin('logistic_booking_details','logistic_booking_details.booking_id','logistic_bookings.id')
        ->leftjoin('logistic_booking_charges','logistic_booking_charges.booking_id','logistic_bookings.id')
        ->leftjoin('logistic_booking_consignor_waybills','logistic_booking_consignor_waybills.booking_id','logistic_bookings.id')
         ->groupBy('logistic_bookings.id')
        ->orderBy('id', 'DESC');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data
                        ->when(!empty($search_query), function ($query) use ($search_query) {
                            return $query->where('logistic_bookings.main_booking_no', 'like', '%'.$search_query.'%');
                        })
                        ->paginate($sort_by);

            return view('booking.table', compact('data'));
        }
        else
        {
              $data = $data->paginate(10);

             return view('booking.index', compact('data'));
        }
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {   
        $total             = $this->totalAmount('$amount');
        $taxable_amount    = $this->noTaxAmount();
        $weights           = PrimaryUnit::select('id','name','code')->where('unit_type','Weight')->get();
        $rate_calculations = RateCalculationType::select('id','name')->get();
        $payment_terms     = PaymentTerm::select('id','payment_term_name')->get();
        $tax               = TaxMaster::select('id','name')->get();
        $vehicles          = VehicleType::select('id','name')->get();
        $deliveries        = DeliveryType::select('id','name')->get();
        $risks             = ShippingRisk::select('id','name')->get();
        $transportations   = TransportationMode::select('id','code')->get();
        $transports        = TransportType::select('id','name')->get();
        $taxpaidby         = TaxPaidBy::select('id','code')->get();
        $license_types     = LicenseType::select('id','name','code')->where('is_mandatory', '1')->where('status',1)->get();
        $country           = Country::select(['id','name'])->get();
        $company_address   = \Session::get('company_data')['companies_addresses'] ?? '';
        $country_id        = $company_address['country_id'] ?? '';
        $state_id          = $company_address['state_id'] ?? '';
        $city_id           = $company_address['city_id'] ?? '';
        $account_types     = MasterType::select(['id', 'type_name'])->where('type_code','CUSTOMER')->first();
        $accounting_groups = AccountingGroup::select(['id', 'name'])->where('code','SUNDRY_DEBTORS')->first();
        $accounting_group  = Account::select(['id', 'name', 'account_category_id', 'accounting_group_id'])
            ->with('chart_of_account_sub_type')
            ->where(function ($query) {
                $query->whereHas('chart_of_account_sub_type', function ($accounting_group) {
                    $accounting_group->where('is_payment_mode', '1');
                });
            })
            ->get();
        $voucher_types       = VoucherType::select([
            'voucher_types.id as voucher_id',
            'voucher_types.code as code',
            'voucher_masters.id',
            'voucher_masters.voucher_code'])
        ->leftjoin('voucher_masters','voucher_masters.id','voucher_types.voucher_master_id')
        ->where('voucher_masters.voucher_code','SALES')
        ->get();

        return view('booking.create',compact(
            'country',
            'weights',
            'country_id',
            'state_id',
            'city_id',
            'tax',
            'account_types',
            'accounting_group',
            'accounting_groups',
            'transportations',
            'transports',
            'rate_calculations',
            'taxpaidby',
            'deliveries',
            'risks',
            'vehicles',
            'voucher_types',
            'payment_terms',
            'total',
            'taxable_amount',
        ));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $cart = \Session::get('all_products_cart') ?? [];

        $voucher_master = VoucherMaster::leftJoin('voucher_series', 'voucher_masters.id', '=', 'voucher_series.voucher_master_id')
        ->where('voucher_masters.voucher_code', 'SALES')
        ->where('voucher_masters.status', 1)
        ->where('voucher_series.series_name', 'Sales')
        ->select('voucher_masters.*', 'voucher_series.*')
        ->first();

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

        $voucher_type_last_count = LogisticBooking::select('last_voucher_type_count')->orderBy('created_at', 'DESC')->first();
        $voucher_type_count      = isset($voucher_type_last_count) && isset($voucher_type_last_count->last_voucher_type_count) ? $voucher_type_last_count->last_voucher_type_count + 1 : ($voucher_type->voucherSeries->start_from + 1 ?? 1);
        $voucher_type_invoice_no = $this->generateCode(
            $voucher_type_count,
            ($voucher_type->voucherSeries->prefix ?? 'INV'),
            ($voucher_type->voucherSeries->postfix ?? ''),
            ($voucher_type->voucherSeries->separator ?? '-'),
            ($voucher_type->voucherSeries->length ?? 5)
        );
        $data             = $cart['all_products'][0];

        $consignoraddress =AccountAddress::select('id','account_id')->where('account_id',$data['consignor_id'])->first();
        $consigneeaddress =AccountAddress::Select('id','account_id')->where('account_id',$data['consignee_id'],)->first();
        $company_id       = Auth::user()->company_id ?? '';
        $billing_date     = $request->invoice_date != '' ? date('Y-m-d', strtotime($request->invoice_date)) : '';
        $trackingId       = sprintf('%012d', mt_rand(0, 999999999999));
        $main_booking_no  = sprintf('%05d', mt_rand(0, 99999));

        $booking  = [
            'voucher_type_id'                => $data['voucher_type_id'],
            'tax_paid_by_id'                 => $data['tax_paid_by'] ,
            'consignor_id'                   => $data['consignor_id'],
            'consignee_id'                   => $data['consignee_id'],
            'vendor_id'                      => $data['vendor_id'],
            'bill_to_account_id'             => $data['bill_to_party'],
            'from_location_id'               => $data['from_id'],
            'to_location_id'                 => $data['to_id'],
            'bill_to_address_id'             => $consigneeaddress->id ?? ' ',
            'ship_to_address_id'             => $consigneeaddress->id ?? ' ',
            'despatch_from_address_id'       => $consignoraddress->id ?? ' ',
            'transportation_mode_id'         => $data['transportation_mode_id'] ,
            'shipping_risk'                  => $data['shipping_risk'],
            'delivery_type_id'               => $data['delivery_type'],
            'insurance'                      =>  $request->insurance ? 'Yes':'No',
            'broker_id'                      =>  ' ',
            'broker_commission'              => $request->broker_commission ?? ' ',
            'payment_term_id'                => $request->payment_term ?? ' ',
            'main_booking_no'                => $voucher_type_invoice_no,
            'manual_lr_no'                   => $request->manual_lr_no,
            'branch_booking_no'              => $voucher_type_invoice_no,
            'voucher_type_booking_no'        => $voucher_type_invoice_no,
            'voucher_type_code'              => $data['voucher_type_code'] ??  ' ' ,
            'booking_date'                   => $billing_date ?? ' ',
            'last_voucher_count'             => $voucher_type_count ??  ' ',
            'last_voucher_type_count'        =>$voucher_type_count??  ' ',
            'voucher_type_id'                => $data['voucher_type_id']??  ' ',
            'destination_branch_id'          => $data['destination_branch_id']??  ' ',
            'transport_type_id'              => $data['transport_type']??  ' ',
            'booking_status'                 => 'PENDING',
            'tracking_id'                    => $trackingId,
            'party_mark'                     => $data['booking_remarks'] ??  ' ',
            'booking_remarks'                => $data['party_mark']  ??  ' ',
            'hide_booking_amount_for_branch' => $data['hide_booking_amount_for_branch'] ??  ' ',
            'created_by_user_id'             =>\Auth::id( ) ?? '',
            'company_id'                     => $company_id,
        ];

        $booking                      = LogisticBooking::create($booking);
        $lc_date                      =  $data['lc_date'] != '' ? date('Y-m-d', strtotime($data['lc_date'])) : '';
        $container_return_expiry_date = $data['container_return_expiry_date'] != '' ? date('Y-m-d', strtotime($data['container_return_expiry_date'])) : '';
        $do_validity_date             = $data['do_validity_date'] != '' ? date('Y-m-d', strtotime($data['do_validity_date'])) : '';

        if($data['container_no']   != null){
            $container  = [
                'container_no'                 => $data['container_no']??  ' ',
                'seal_no'                      => $data['seal_number']??  ' ' ,
                'delivery_order_no'            => $data['do_number']??  ' ',
                'delivery_order_validity_date' => $do_validity_date??  ' ',
                'container_return_date'        => $data['container_return_date']??  ' ',
                'container_return_expiry_date' =>$container_return_expiry_date,
                'lc_no'                        => $data['lc_number'] ??  ' ',
                'lc_authority_id'              => $data['lc_issued_by'] ??  ' ',
                'lc_date'                      => $lc_date  ??  ' ',
                'cfs_agent_id'                 => $data['cfs']  ??  ' ',
                'booking_id'                   => $booking->id,
                'container_size_id'            => $data['container_size_id']??  ' ' ,
                'container_type_id'            => $data['container_type_id']??  ' ',
                'cargo_weight'                 => $data['cargo_weight ']??  ' ',
                'cargo_type_id'                => $data['cargo_type_id'] ??  ' ',
                'cargo_volume'                 => $data['cargo_volume'] ??  ' ',
                'cargo_shipping_line_id'       => $data['cargo_shipping_line_id ']  ??  ' ',
                'vehicle_type_id'              => $data['vehicle_type_id']  ??  ' ',
                'tracking_number'              => $data['tracking_number']  ??  ' ',
                'temperature_control'          => $data['temperature_control']  ??  ' ',
                'temperature_range'            => $data['temperature_range']  ??  ' ',
                'estimated_arrival_date'       => $data['estimated_arrival_date']  ??  ' ',
                'insurance_value'              => $data['insurance_value']  ??  ' ',
                'loading_port_id'              => $data['loading_port_id']  ??  ' ',
                'destination_port_id'          => $data['destination_port_id']  ??  ' ',
                'bill_of_landing_no'           => $data['bill_of_landing_no']  ??  ' ',
                'unique_vessel_no'             => $data['vessel_no']  ??  ' ',
                'vessel_name'                  => $data['vessel_name']  ??  ' ',
                'voyage_no'                    => $data['voyage_no']  ??  ' ',
                'offload_destination_date'     => $data['offload_destination_date']  ??  ' ',
                'customs_clearance_status_id'  => $data['customs_clearance_status_id']  ??  ' ',
                'container_return_status_id'   => $data['container_return_status_id']  ??  ' ',
                'security_compliance'          => $data['security_compliance']  ??  ' ',
                'remarks'                      => $data['remarks']  ??  ' ',
            ];

            $container   = LogisticBookingContainerDetail::create($container);
        }

        $productcart = \Session::get('products_cart') ?? [];
        $data1       = $productcart['products']?? [];;

        foreach($data1 as $list ){
            $bookingdetails  = [
                'booking_id'            =>  $booking->id,
                'product_id'            => $list['product_id'],
                'product_batch_id'      => $list['product_batch_id'] ?? '',
                'item_details'          => $list['product'],
                'material_details'      => $list['material_details'] ?? '',
                'quantity'              => $list['item_qty'],
                'distance'              => $list['distance'] ?? '',
                'hours'                 => $list['hours'] ?? '',
                'length'                => $list['length'] ?? '',
                'breadth'               => $list['breadth']?? '',
                'height'                => $list['length']?? '',
                'actual_weight'         => $list['actual_weight'],
                'gross_weight'          => $list['gross_weight'],
                'charge_weight'         => $list['charge_weight'] ?? '',
                'weight_type_id'        => $list['weight_type_id'],
                'weight_calculation_on' => $list['weight_type_code'],
                'tax_id'                => $list['tax_id'],
                'tax_calculation_type'  => $list['tax_calculation_type'] ?? '',
                'rate_calculation_on'   => $list['rate_calculation_type_id'],
                'rate'                  => $list['product_price'],  
                'discount_type'         => $list['discount_type'] ?? '', 
                'discount_amount'       => $list['discount_amount']?? '',
                'discount_percentage'   => $list['discount_percentage'] ?? '',
                'total_amount'          =>$list['amount'],
            ];
        
            $bookingdetails = LogisticBookingDetail::create($bookingdetails);

        }

        $chargecart = \Session::get('charges_cart') ?? [];
        $data2      = $chargecart['charges'] ?? [];;

        foreach($data2 as $list){
            $bookingcharges  = [
                'booking_id'         => $booking->id,
                'charge_account_id'  => $list['account_id'],
                'charge_date'        => $charge_date ?? '',
                'charge_tax_id'      => $list['charge_tax_id'],
                'charge_quantity'    => $list['charge_qty'] ?? '',
                'charge_rate'        => $list['charge_rate'],
                'charge_amount'      =>  $chargecart['amount'] ?? '',
                'remarks'            => $list['remarks'] ?? '',
                'created_by_user_id' => \Auth::id( ) ?? '',
                'updated_by_user_id' => \Auth::id( ) ?? '',
                'status'             => $list['status']?? '',
            ];
          $bookingcharges = LogisticBookingCharge::create($bookingcharges);
        }

        $invoice_cart = \Session::get('invoice_cart') ?? [];
        $data3        = $invoice_cart['invoice'] ?? [];

        foreach($data3 as $list){
            $invoice_date         =  $list['bill_date'] != '' ? date('Y-m-d', strtotime( $list['bill_date'])) : '';
            $way_bill_date        =  $list['way_bill_date'] != '' ? date('Y-m-d', strtotime( $list['way_bill_date'])) : '';
            $way_bill_expiry_date =  $list['way_exp_date'] != '' ? date('Y-m-d', strtotime( $list['way_exp_date'])) : '';

            $bookinginvoices  = [
                'booking_id'              => $booking->id,
                'consignor_invoice_date'  =>  $invoice_date,
                'consignor_invoice_no'    => $list['bill_no'] ?? '',
                'consignor_invoice_value' => $list['invoice_value'],
                'way_bill_no'             => $list['way_bill_no'] ?? '',
                'way_bill_date'           => $way_bill_date ,
                'way_bill_expiry_date'    => $way_bill_expiry_date ,
                'way_bill_status'         => $list['way_bill_status'] ?? '',

            ];
            
            $bookinginvoices = LogisticBookingConsignorWaybill::create($bookinginvoices);
        }

        if($booking->insurance == 'YES'){
            $insurance = LogisticBookingInsurance::insert([
                'booking_id'         => $booking->id ?? ' ',
                'insurance_provider' => $request->insurance_provider ?? ' ',
                'policy_date'        => $request->policy_date ?? ' ',
                'policy_no'          => $request->policy_number ?? ' ',
                'policy_percentage'  => $request->policy_percentage ?? ' ',
                'policy_amount'      => $request->policy_amount ?? ' ', 
                'claim_amount'       => $request->claim_amount ??  ' ',
            ]);
        }

        \Session::forget('invoice_cart');
        \Session::forget('all_products_cart');
        \Session::forget('charges_cart');
        \Session::forget('products_cart');

        return redirect()->route('booking-register.index')->with('success', "Booking Created Successfully");
    }
                                
    /**     
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $booking           = LogisticBooking::find($id);
        $total             = $this->totalAmount('$amount');
        $taxable_amount =$this->noTaxAmount();
        $weights           = PrimaryUnit::select('id','name','code')->where('unit_type','Weight')->get();
        $rate_calculations = RateCalculationType::select('id','name')->get();
        $vehicles               = VehicleType::select('id','name')->get();
        $voucher_types       = VoucherType::select([
            'voucher_types.id as voucher_id',
            'voucher_types.code as code',
            'voucher_masters.id',
            'voucher_masters.voucher_code'])
        ->leftjoin('voucher_masters','voucher_masters.id','voucher_types.voucher_master_id')
        ->where('voucher_masters.voucher_code','SALES')
        ->get();

        $payment_terms     = PaymentTerm::select('id','payment_term_name')->get();
        $tax               = TaxMaster::select('id','name')->get();
        $deliveries        = DeliveryType::select('id','name')->where('id',$booking->delivery_type_id)->first();
        $risks             = ShippingRisk::select('id','name')->where('id',$booking->shipping_risk)->first();
        $transportations   = TransportationMode::select('id','code')->where('id',$booking->transportation_mode_id)->first();
        $transports        = TransportType::select('id','name')->where('id',$booking->transport_type_id)->first();
        $taxpaidby         = TaxPaidBy::select('id','code')->where('id',$booking->tax_paid_by_id)->first();
        $license_types     = LicenseType::select('id','name','code')->where('is_mandatory', '1')->where('status',1)->get();
        $country           = Country::select(['id','name'])->get();
        $company_address   = \Session::get('company_data')['companies_addresses'] ?? '';
        $country_id        = $company_address['country_id'] ?? '';
        $state_id          = $company_address['state_id'] ?? '';
        $city_id           = $company_address['city_id'] ?? '';
        $bill_to_party     = Account::select('id','name')->where('id',$booking->bill_to_account_id)->first();
        $account_types     = MasterType::select(['id', 'type_name'])->where('type_code','CUSTOMER')->first();
        $accounting_groups = AccountingGroup::select(['id', 'name'])->where('code','SUNDRY_DEBTORS')->first();
        $accounting_group  = Account::select(['id', 'name', 'account_category_id', 'accounting_group_id'])
            ->with('chart_of_account_sub_type')
            ->where(function ($query) {
                $query->whereHas('chart_of_account_sub_type', function ($accounting_group) {
                    $accounting_group->where('is_payment_mode', '1');
                });
            })
            ->get();

        $consignor = $consignee = $vendor =  '';

        if ($booking && isset($booking->consignor_id) && $booking->consignor_id != '') {
            $consignor = Account::getAccount([
                'accounts.id' => $booking->consignor_id
            ]);
            if (isset($consignor)) {
                $consignor->name     = $consignor->name ;
                $consignor->address  != '' ? ', ' . $consignor->address : '' ;
                $consignor->phone_no != '' ? ', ' . $consignor->phone_no : '';
                $consignor->email    != '' ? ', ' . $consignor->email : '';
            }
        }
        if ($booking && isset($booking->consignee_id) && $booking->consignee_id != '') {
            $consignee = Account::getAccount([
                'accounts.id' => $booking->consignee_id
            ]);
            if (isset($consignee)) {
                $consignee->id       = $consignee->id;
                $consignee->name     = $consignee->name ;
                $consignor->address  != '' ? ', ' . $consignor->address : ''; 
                $consignee->phone_no != '' ? ', ' . $consignee->phone_no : '';
                $consignee->email    != '' ? ', ' . $consignee->email : '';
            }
        }

        if ($booking && isset($booking->vendor_id) && $booking->vendor_id != '') {
            $vendor = Account::getAccount([
                'accounts.id' => $booking->vendor_id ?? ''
            ]);
            if (isset($vendor)) {
                $vendor->name     = $vendor->name ;
                $vendor->phone_no != '' ? ', ' . $vendor->phone_no : '';
                $vendor->city_id  != '' ? ', ' . $vendor->city_id : '';
                $vendor->email    != '' ? ', ' . $vendor->email : '';
            }
        }

        $containerDetails = LogisticBookingContainerDetail::where('booking_id' , $id)->first();   

        $from_location_id = City::select('name')->where('id',$consignor->city_id)->first();        
        $to_location_id   = City::select('name')->where('id',$consignee->city_id)->first();         
        $vendor_city      = City::select('name')->where('id',$vendor->city_id ?? 0)->first();     

        $insurance          = LogisticBookingInsurance::where('booking_id',$id)->first();
        $insurance_provider = Account::select('name')->where('id',$insurance->insurance_provider ?? 0)->first();

        $pickup_address  = AccountAddress::select('address_line1')->where('id',$booking->despatch_from_address_id)->first();
        $bill_to_address = AccountAddress::select('address_line1')->where('id',$booking->bill_to_address_id)->first();
        $ship_to_address = AccountAddress::select('address_line1')->where('id',$booking->ship_to_address_id)->first();

        $broker = Account::select('name')->where('id',$booking->broker_id)->first();

        return view('booking.show',compact('booking',
            'country',
            'country_id',
            'state_id',
            'city_id',
            'tax',
            'account_types',
            'accounting_group',
            'accounting_groups',
            'transportations',
            'transports',
            'taxpaidby',
            'bill_to_party',
            'deliveries',
            'consignor',
            'consignee',
            'vendor',
            'from_location_id',
            'to_location_id',
            'vendor_city',
            'risks',
            'voucher_types',
            'booking',
            'payment_terms',
            'containerDetails',
            'rate_calculations',
            'weights',
            'vehicles',
            'insurance',
            'insurance_provider',
            'pickup_address',
            'bill_to_address',
            'ship_to_address',
            'broker'
        ));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $booking           = LogisticBooking::find($id);
        $payment_terms     = PaymentTerm::select('id','payment_term_name')->get();
        $tax               = TaxMaster::select('id','name')->get();
        $deliveries        = DeliveryType::select('id','name')->get();
        $risks             = ShippingRisk::select('id','name')->get();
        $transportations   = TransportationMode::select('id','code')->get();
        $transports        = TransportType::select('id','name')->get();
        $taxpaidby         = TaxPaidBy::select('id','code')->get();
        $license_types     = LicenseType::select('id','name','code')->where('is_mandatory', '1')->where('status',1)->get();
        $country           = Country::select(['id','name'])->get();
        $company_address   = \Session::get('company_data')['companies_addresses'] ?? '';
        $country_id        = $company_address['country_id'] ?? '';
        $state_id          = $company_address['state_id'] ?? '';
        $city_id           = $company_address['city_id'] ?? '';
        $account_types     = MasterType::select(['id', 'type_name'])->where('type_code','CUSTOMER')->first();
        $accounting_groups = AccountingGroup::select(['id', 'name'])->where('code','SUNDRY_DEBTORS')->first();
        $accounting_group  = Account::select(['id', 'name', 'account_category_id', 'accounting_group_id'])
            ->with('chart_of_account_sub_type')
            ->where(function ($query) {
                $query->whereHas('chart_of_account_sub_type', function ($accounting_group) {
                    $accounting_group->where('is_payment_mode', '1');
                });
            })
            ->get();

        $voucher_types       = VoucherType::select([
            'voucher_types.id as voucher_id',
            'voucher_types.code as code',
            'voucher_masters.id',
            'voucher_masters.voucher_code'])
        ->leftjoin('voucher_masters','voucher_masters.id','voucher_types.voucher_master_id')
        ->where('voucher_masters.voucher_code','SALES')
        ->get();
        $consignor  = $consignee = $vendor =  '';
        if ($booking && isset($booking->consignor_id) && $booking->consignor_id != '') {
            $consignor = Account::getAccount([
                'accounts.id' => $booking->consignor_id
            ]);
            if (isset($consignor)) {
                $consignor->name = $consignor->name ;
                $consignor->phone_no != '' ? ', ' . $consignor->phone_no : '';
            }
        }
        if ($booking && isset($booking->consignee_id) && $booking->consignee_id != '') {
            $consignee = Account::getAccount([
                'accounts.id' => $booking->consignee_id
            ]);
            if (isset($consignee)) {
                $consignee->name = $consignee->name ;
                $consignee->phone_no != '' ? ', ' . $consignee->phone_no : '';
            }
        }

        if ($booking && isset($booking->vendor_id) && $booking->vendor_id != '') {
            $vendor = Account::getAccount([
                'accounts.id' => $booking->vendor_id 
            ]);
            if (isset($vendor)) {
                $vendor->name = $vendor->name ;
                $vendor->phone_no != '' ? ', ' . $vendor->phone_no : '';
            }
        }
        $from_location_id = City::select('name')->where('id',$booking->from_location_id)->first();        
        $to_location_id   = City::select('name')->where('id',$booking->to_location_id)->first();        

        return view('booking.edit',compact('booking',
            'country',
            'country_id',
            'state_id',
            'city_id',
            'tax',
            'account_types',
            'accounting_group',
            'accounting_groups',
            'transportations',
            'transports',
            'taxpaidby',
            'deliveries',
            'consignor',
            'consignee',
             'vendor',
            'from_location_id',
            'to_location_id',
            'risks',
            'voucher_types',
            'payment_terms',
        ));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $booking = LogisticBooking::find($id);
        $booking_update  = [
            'voucher_type_id'                      => $data['voucher_type_id'],
            'tax_paid_by_id'                         => $data['tax_paid_by'] ,
            'consignor_id'                              => $data['consignor_id'],
            'consignee_id'                             => $data['consignee_id'],
            'vendor_id'                                   => $data['vendor_id'],
            'bill_to_account_id'                    => $data['bill_to_party'],
            'from_location_id'                      => $data['from_id'],
            'to_location_id'                            => $data['to_id'],
            'transportation_mode_id'         => $data['transportation_mode_id'] ,
            'shipping_risk'                              => $data['shipping_risk'],
            'delivery_type_id'                              => $data['delivery_type'],
            'transport_type_id'                      => $data['transport_type']??  ' ',
        ];
        $booking = LogisticBooking::update($booking_update);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


    public function createConsignor()
    {
        $license_types = LicenseType::select('id','name','code')->where('is_mandatory', '1')->where('status',1)->get();
        $country         = Country::select(['id','name'])->get();
        $company_address = \Session::get('company_data')['companies_addresses'] ?? '';

        $country_id = $company_address['country_id'] ?? '';
        $state_id   = $company_address['state_id'] ?? '';
        $city_id    = $company_address['city_id'] ?? '';

        return view('booking.createconsignor', compact(
            'country',
            'country_id',
            'state_id',
            'city_id',
            'license_types'
        ));
    }
     public function storeConsignor(Request $request)
    {
        
        $validator = \Validator::make($request->all(), [
            'phone_no'                 => [
                'required',
                function ($attribute, $value, $fail) use ($request) {
                    $existingContact = AccountContact::where('name', $request->name)
                        ->where('phone_no', $value)
                        ->exists();
                    if ($existingContact) {
                        $fail('This Name and Phone No combination already exists.');
                    }
                }
            ],
            'name'                     => [
                'required',
                function ($attribute, $value, $fail) use ($request) {
                    $existingContact = AccountContact::where('phone_no', $request->phone_no)
                        ->where('name', $value)
                        ->exists();
                    if ($existingContact) {
                        $fail('This Name and Phone No combination already exists.');
                    }
                }
            ],
        ], [
            'required' => 'The :attribute field is required.',
            'unique'   => 'This Name and Phone No are already taken.',
        ]);

        // Check if validation fails
        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->errors()->first());
        }

        $type = MasterType::findOrFail($request->account_type_id);

        if (isset($type) && strtolower($type->type_name) != 'student') {
            $rules['accounting_group_id'] = 'required';

        }

        $validator = \Validator::make($request->all(), $rules, [
            'unique' => 'This Name and Phone No are already taken.',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
         }
        $company_id         = \Auth::user()->company_id ?? '';

        $data = $request->except([
             '_token',
            '_method',
            'country_id',
            'state_id',
            'cityid',
            'city_id',
            'phone_no',
            'whatsapp_no',
            'address',
            'email',
            'contact',
            'license_type_id',
            'license_number',
            'valid_from',
            'valid_upto',
            'postal_code',
            

        ]);
        $data['company_id'] = $company_id;
        $account = Account::create($data);
       
         $data = $request->input('license_number');

        if (!is_null($data) && is_array($data)) {
            foreach ($data as $type => $licenseInfo) {
                if (!empty($licenseInfo['license_number'])) {
                    AccountLicense::create([
                        'account_id'      => $account->id,
                        'license_number'  => $licenseInfo['license_number'],
                        'license_type_id' => $licenseInfo['license_type_id'],
                        'valid_from'      => '',
                        'valid_upto'      => '',
                    ]);
                }
            }
        }

       $address = AccountAddress::insert([
            'account_id'    => $account->id,
            'country_id'    => $request->country_id,
            'state_id'      => $request->state_id,
            'city_id'       => $request->city_id,
            'address_line1' => $request->address,
            'post_code'     => $request->postal_code,
            'is_default'    => '1'
        ]);

        $contact = AccountContact::insert([
            'account_id'          => $account->id,
            'phone_no'            => $request->phone_no,
            'whatsapp_no'         => $request->whatsapp_no,
            'email'               => $request->email ?? '',
            'name'                => $request->name ?? '',
            'country_id'          => $request->country_id,
            'state_id'            => $request->state_id,
            'city_id'             => $request->city_id,
            'pin'                 => $request->postal_code,
            'postal_code'         => $request->postal_code,
            'address'             => $request->address,
        ]);

        $response = [
            'id'         => $account->id,
            'name'       => $request->name,
            'address'    => $request->address,
            'country_id' => $request->country_id,
        ];
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Customer has been created successfully',
                'data'    => $response
            ]);
        }
        return redirect()->route('booking.create')
            ->with('success','Customer has been created successfully.');
    }

    public function editConsignor($id)
    {  
     $account_license = AccountLicense::select('id','license_type_id','account_id','license_number')->where('account_id', $id)->get();
        $account_license = $account_license->keyBy('license_type_id');
        $license_types = LicenseType::select('id', 'name', 'code')->where('status',1)->where('is_mandatory','1')->get();
        $account         = Account::where('id',$id)->with('first_account_address','account_contact')->first();
        $country         = Country::select(['id','name'])->get();
        $company_id      = Auth::user()->company_id ?? '';
        $company_address = CompanyAddress::select([
            'companies_addresses.country_id',
                'companies_addresses.state_id',
            'companies_addresses.city_id',
            'companies.id',
        ])
        ->leftjoin('companies', 'companies.id', 'companies_addresses.company_id')
        ->where('company_id', $company_id)
        ->orWhere('companies.is_default', '1')
        ->first();

        $country_id = $company_address->country_id ?? '';
        $state_id   = $company_address->state_id ?? '';
        $city_id    = $company_address->city_id ?? '';

        return view('booking.editconsignor', compact(
            'country',
            'country_id',
            'state_id',
            'city_id',
            'account',
            'account_license',
            'license_types',
        ));
    }

    public function UpdateConsignor(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'phone_no'   => 'required|unique:account_contacts,phone_no,'.$request->name.',name,id,'.$id,
            'name'       => 'required|unique:account_contacts,name,'.$request->phone_no.',phone_no,id,'.$id,
            'country_id' => 'required',
        ], [
            'unique' => 'This Name and Phone No are already taken.',
        ]);


        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'country_id',
            'state_id',
            'cityid',
            'city_id',
            'phone_no',
            'whatsapp_no',
            'address',
            'email',
            'contact',
            'license_type_id',
            'license_number',
            'valid_from',
            'valid_upto',
            'postal_code',
        ]);

        $account = Account::find($id);

        if (!$account) {
            return redirect()->route('accounting-groups.index')
                ->with('error','Account not found!');
        }

        $account->update($data);

        $data = $request->input('license_number');

        if (!is_null($data) && is_array($data)) {
            foreach ($data as $type => $licenseInfo) {
                if (empty($licenseInfo['license_number'])) {
                    AccountLicense::where([
                        'account_id'      => $account->id,
                        'license_type_id' => $licenseInfo['license_type_id'],
                    ])->delete();
                } else {
                    AccountLicense::updateOrCreate(
                        [
                            'account_id'      => $account->id,
                            'license_type_id' => $licenseInfo['license_type_id'],
                        ],
                        [
                            'license_number'  => $licenseInfo['license_number'],
                            'valid_from'      => '',
                            'valid_upto'      => '',
                        ]
                    );
                }
            }
        }

        $address = AccountAddress::updateOrCreate([
            'account_id'    => $account->id,
            'is_default'    => '1'
        ],[
            'country_id'    => $request->country_id,
            'state_id'      => $request->state_id,
            'city_id'       => $request->city_id,
            'address_line1' => $request->address,
            'post_code'     => $request->postal_code,
        ]);

        $contact = AccountContact::updateOrCreate([
            'account_id'          => $account->id
        ],[
            'phone_no'            => $request->phone_no,
            'whatsapp_no'         => $request->whatsapp_no,
            'email'               => $request->email ?? '',
            'name'                => $request->contact ?? '',
            'country_id'          => $request->country_id,
            'state_id'            => $request->state_id,
            'city_id'             => $request->cityid,
            'address'             => $request->address,
            'pin'                 => $request->postal_code,
            'postal_code'         => $request->postal_code,
        ]);
$city = City::select('name')->where('id',$request->cityid)->first(); 
        $response = [
            'id'   => $id,
            'name' => $request->name,
            'address' => $request->address,
            'email' => $request->email,
            'phone_no' => $request->phone_no,
            'city' =>$city->name,
        ];

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Account has been updates successfully',
                'data'    => $response
            ]);
        }
        return redirect()->route('booking.create.index')
            ->with('success','Account has been updates successfully.');
    }

    //**** Products cart work ****\\

public function searchProduct(Request $request)
    {
        $searchTerm = $request->search;

        $results    = Product::select(
                'products.id',
                'products.name',
                'product_prices.sale_price as mrp',
                'product_prices.id as price_id',
                'products.grossweight',
                'products.netweight',
                'tax_masters.id as taxid',
                'tax_masters.name as tax',
            )
            ->leftjoin('product_prices', 'product_prices.product_id', 'products.id')
            ->leftjoin('tax_masters','tax_masters.id','products.tax_slab_id')
            ->where(function ($query) use ($searchTerm) {
                $query->where('products.name', 'LIKE', "%" . $searchTerm . "%")
                      ->orWhere('products.product_code', 'LIKE', "%" . $searchTerm . "%")
                      ->orWhere('product_prices.bar_code','LIKE',  "%" . $searchTerm . "%")
                      ->orWhere('products.shortcode', 'LIKE', "%" . $searchTerm . "%");
            })
            
            ->where('product_prices.status', 1)
            ->limit(15)
            ->get();

        return response()->json(['result' => $results, 'status' => true]);
    }


    public function productAddToCart(Request $request)
    {
        $data = \Session::get('products_cart') ?? [];
 
        $product = Product::select('products.id','products.name','tax_masters.name as tax','tax_masters.id as tax_id')
                    ->leftjoin('tax_masters','tax_masters.id','products.tax_slab_id')
                    ->leftjoin('product_prices','products.id','product_prices.product_id')
                    ->where('products.id', $request->search_product)
                    ->first();
       
        // Check if the product already exists in the cart
        if(isset($data['products'])){
            foreach ($data['products'] as $cart_product) {
                if ($cart_product['product_id'] == $request->search_product) {
                    return response()->json(['success' => true, 'data' => $data]);
                }
            }
        }
        $amount        =  $request->product_price;

      $tax_paid_by = TaxPaidBy::select('id','code')->where('id',$request->taxpaidby)->first();
     
        $rate_cal_type_name = RateCalculationType::select('name')->where('id',$request->rate_calculation_type)->first();
 
        $item_qty = $request->item_qty ;
        $item_hours = $request->hours  ;
        $item_distance = $request->distance  ;
        $gross_weight =$request->gross_weight;
        
        if($rate_cal_type_name->name ==  'Weight') {
             $amount = $gross_weight * $amount;
        }
        elseif ($rate_cal_type_name->name==  'Quantity') {
               $amount = $item_qty * $amount;
        }
        elseif ($rate_cal_type_name->name ==  'Hours') {
               $amount = $item_hours * $amount;
        }
        elseif ($rate_cal_type_name->name ==  'Distance') {
               $amount = $item_distance * $amount;
        }
        else{
             $amount;
        }
        $taxable_amount = $amount;

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

        if($tax_paid_by->code ==  'TRANSPORTER') {
        $amount = $amount + $tax;
        }
     
        $amount        = number_format($amount, 2, '.', '');

        $weight_type_code =  PrimaryUnit::select('code')->where('id',$request->weight_type)->first();
        
        $data_amount = $data['amount'] ?? 0 ;
        $data['amount'] = $data_amount + $amount;
        $data['products'][] = [
            'item_qty'                    => $item_qty ?? '',
            'price_id'                      => $request->price_id ?? '',
            'product_id'                 => $request->search_product ?? '',
            'product'                      => $product->name ?? '',
            'product_price'           => $request->product_price ?? '',
            'amount'                        => $amount ?? '',
            'taxable_amount'     => $taxable_amount  ?? '',
            'tax_per'                        => $tax_per,
            'tax_flat'                        => $tax,
            'tax_id'                           =>$product->tax_id,
            'taxpaidby'                    =>$tax_paid_by->code,
            'rate_calculation_type_id'  => $request->rate_calculation_type,
            'rate_calculation_type_name'  => $rate_cal_type_name->name,
            'actual_weight'           => $request->actual_weight,
            'gross_weight'            => $request->gross_weight,
            'hours'                           => $request->hours,
            'distance'                      => $request->distance,
            'weight_type_code'   => $weight_type_code->code,
            'weight_type_id'         => $request->weight_type,
            'vehicle_type'             => $request->vehicle_type,
        ];

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

        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();

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

  
    public function productsCart(Request $request, $id = 0)
    {
        $page = $request->page ?? '';
        $data = \Session::get('products_cart') ?? [];

        return view('booking.products-cart', compact('data', 'page', 'id'));
    }
   

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

        $amount = $data['amount'];

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

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

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

        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true ,'total' => $total,'taxable_amount' => $taxable_amount]);
    }

     public function cartProductsUpdate(Request $request)
    {

        $rate_calculation_type = RateCalculationType::select('id','name')->where('id',$request->rate_calculation_type)->first();
        $taxpaidby = TaxPaidBy::select('id','code')->where('id',$request->taxpaidby)->first();
        $data = \Session::get('products_cart') ?? [];

        if (isset($data['products'])) {
            foreach ($data['products'] as $key => $value) {

                if($rate_calculation_type->name == 'Quantity'){

                if($taxpaidby->code ==  'TRANSPORTER' ) {

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

                if ($value['product_id'] == $request->id) {
                    if (isset($request->item_qty) && $request->item_qty > 0) {
                        $data['amount'] = $data['amount'] - $value['amount'];
                        $data['products'][$key]['item_qty'] = $request->item_qty;

                        $data['products'][$key]['loose_qty'] = 0;

                        $item_qty_amount    = $request->item_qty * $value['product_price'];

                        $flat_tax           = ($value['tax_per'] / 100) * $item_qty_amount;
                        $item_qty_amount    = ($item_qty_amount + $flat_tax);

                        $data['products'][$key]['tax_flat'] = $flat_tax;
                        $data['products'][$key]['amount'] = $item_qty_amount;
                        $data['amount'] = $data['amount'] + $item_qty_amount;
                    } 
                }

                if ($value['product_id'] == $request->id && isset($request->product_price)) {
                    $data['amount'] = $data['amount'] - $value['amount'];
                    $data['products'][$key]['product_price'] = $request->product_price;

                    $item_qty = $value['item_qty'] > 0 ? $value['item_qty'] : ($value['loose_qty'] > 0 ? $value['loose_qty'] : 1);

                    $item_qty_amount = $value['product_price'] * $item_qty;
                    $flat_discount = ($value['per_discount'] / 100) * $item_qty_amount;
                    $flat_tax = ($value['tax_per'] / 100) * $item_qty_amount;
                    $item_qty_amount =  ($item_qty_amount - $flat_discount);
                    $item_qty_amount =  ($item_qty_amount + $flat_tax);
                    $data['products'][$key]['flat_discount'] = $flat_discount;
                    $data['products'][$key]['tax_flat'] = $flat_tax;
                    $data['products'][$key]['amount'] = $item_qty_amount;
                    $data['amount'] = $data['amount'] + $item_qty_amount;

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

                if ($value['product_id'] == $request->id) {
                    if (isset($request->item_qty) && $request->item_qty > 0) {
                        $data['amount'] = $data['amount'] - $value['amount'];
                        $data['products'][$key]['item_qty'] = $request->item_qty;

                        $data['products'][$key]['loose_qty'] = 0;

                        $item_qty_amount    = $request->item_qty * $value['product_price'];

                        $data['products'][$key]['amount'] = $item_qty_amount;
                        $data['amount'] = $data['amount'] + $item_qty_amount;
                    } 
                }

                if ($value['product_id'] == $request->id && isset($request->product_price)) {
                    $data['amount'] = $data['amount'] - $value['amount'];
                    $data['products'][$key]['product_price'] = $request->product_price;

                    $item_qty = $value['item_qty'] > 0 ? $value['item_qty'] : ($value['loose_qty'] > 0 ? $value['loose_qty'] : 1);

                    $item_qty_amount = $value['product_price'] * $item_qty;
                    $data['products'][$key]['amount'] = $item_qty_amount;
                    $data['amount'] = $data['amount'] + $item_qty_amount;

                }
            }
            }
            else
            {
                  if($taxpaidby->code ==  'TRANSPORTER' ) {

                if ($value['product_id'] == $request->id) {
                    if (isset($request->item_qty) && $request->item_qty > 0) {
                        $data['products'][$key]['item_qty'] = $request->item_qty;

                        $flat_tax           = ($value['tax_per'] / 100) * $request->item_qty;
                        $item_qty_amount    = ($request->item_qty + $flat_tax);

                        $data['products'][$key]['tax_flat'] = $flat_tax;
                        $data['products'][$key]['amount'] = $item_qty_amount;
                        $data['amount'] = $data['amount'] + $item_qty_amount;
                    } 
                }

                if ($value['product_id'] == $request->id && isset($request->product_price)) {
                    $data['amount'] = $data['amount'] - $value['amount'];

                    $flat_discount = ($value['per_discount'] / 100) *  $value['product_price'];
                    $flat_tax = ($value['tax_per'] / 100) * $value['product_price'];
                    $item_qty_amount =  ( $value['product_price'] + $flat_tax);

                    $data['products'][$key]['tax_flat'] = $flat_tax;
                    $data['products'][$key]['amount'] = $item_qty_amount;
                    $data['amount'] = $data['amount'] + $item_qty_amount;

                }
            } else
            {
                  if ($value['product_id'] == $request->id) {
                    if (isset($request->item_qty) && $request->item_qty > 0) {
                        $data['products'][$key]['item_qty'] = $request->item_qty;
                    } 
                }
            }
            }
            }
        }
            \Session::put('products_cart', $data);

        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true , 'data' => $data ,'total' => $total ,'taxable_amount' => $taxable_amount]);
    } 

  public function taxPaidByUpdate(Request $request)
    {
        $taxpaidby = TaxPaidBy::select('id','code')->where('id',$request->taxpaidby)->first();
        
         $data = \Session::get('products_cart') ?? [];
     
        if (isset($data['products'])) {
            foreach ($data['products'] as $key => $value) {
         $oldtaxpaidby = $value['taxpaidby'];

                if($taxpaidby->code == 'TRANSPORTER'  && $taxpaidby->code != $oldtaxpaidby   ) {

                        $data['amount'] = $data['amount'] - $value['amount'];

                        $item_qty_amount    =$value['amount'];

                        $flat_tax           = $value['tax_flat'] ;
                        $item_qty_amount    = ($item_qty_amount + $flat_tax);

                        $data['products'][$key]['amount'] = $item_qty_amount;
                        $data['amount'] = $data['amount'] + $item_qty_amount;
                       $data['products'][$key]['taxpaidby'] = $taxpaidby->code;
                    } 
                    else if ($taxpaidby->code != 'TRANSPORTER'  &&  $taxpaidby->code != $oldtaxpaidby &&  $oldtaxpaidby == 'TRANSPORTER'  ){
                        
                        $data['amount'] = $data['amount'] - $value['amount'];

                        $base_amount =   $value['amount'];

                        $flat_tax = $value['tax_flat'] ;

                        $amount_after_subtracting_tax = $base_amount - $flat_tax ;

                        $data['products'][$key]['amount'] = $amount_after_subtracting_tax;
                        $data['amount'] = $data['amount'] + $amount_after_subtracting_tax;
                        $data['products'][$key]['taxpaidby'] = $taxpaidby->code;

                    }
            }
            
        }
    
         \Session::put('products_cart', $data);
          $data1= \Session::get('charges_cart') ?? [];
        
        if (isset($data1['charges'])) {
            foreach ($data1['charges'] as $key => $value) {
         $oldtaxpaidby = $value['taxpaidby'];

                if($taxpaidby->code == 'TRANSPORTER'  && $taxpaidby->code != $oldtaxpaidby   ) {
  
                        $data1['amount'] = $data1['amount'] - $value['amount'];

                        $item_qty_amount    =$value['amount'];

                        $flat_tax           = $value['tax_flat'] ;
                        $item_qty_amount    = ($item_qty_amount + $flat_tax);

                        $data1['charges'][$key]['amount'] = $item_qty_amount;
                        $data1['amount'] = $data1['amount'] + $item_qty_amount;
                       $data1['charges'][$key]['taxpaidby'] = $taxpaidby->code;
                    } 
                    else if ($taxpaidby->code != 'TRANSPORTER'  &&  $taxpaidby->code != $oldtaxpaidby &&  $oldtaxpaidby == 'TRANSPORTER'  ){
                        
                        $data1['amount'] = $data1['amount'] - $value['amount'];
                        
                        $base_amount =   $value['amount'];

                        $flat_tax = $value['tax_flat'] ;

                        $amount_after_subtracting_tax = $base_amount - $flat_tax ;

                        $data1['charges'][$key]['amount'] = $amount_after_subtracting_tax;
                        $data1['amount'] = $data1['amount'] + $amount_after_subtracting_tax;
                        $data1['charges'][$key]['taxpaidby'] = $taxpaidby->code;

                    }
            }
            
        } 

            \Session::put('charges_cart', $data1);
        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        
        return response()->json([ 'success' => true , 'data' => $data, 'data1' => $data1 ,'total' => $total  ,'taxable_amount' => $taxable_amount]);
    } 

    //**** Charges cart work ****\\

     public function chargesCart(Request $request, $id = 0)
    {
        $page = $request->page ?? '';
        $data = \Session::get('charges_cart') ?? [];

        return view('booking.additionalcharges-cart', compact('data', 'page', 'id'));
    }

    public function searchCharge(Request $request)
    {
        $searchTerm = $request->search;

        $results    = AdditionalCharge::select(
                'additional_charges.*',
            )
            ->where(function ($query) use ($searchTerm) {
                $query->where('additional_charges.name', 'LIKE', "%" . $searchTerm . "%")
                      ->orWhere('additional_charges.voucher_type_code', 'LIKE', "%" . $searchTerm . "%");
            })
            ->where('additional_charges.status', 1)
            ->limit(15)
            ->get();

        return response()->json(['result' => $results, 'status' => true]);
    }

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

        $charge = AdditionalCharge::select('additional_charges.id','additional_charges.name','additional_charges.account_id')
                    ->where('additional_charges.id', $request->search_charge)
                    ->first();
  
        // Check if the charge already exists in the cart
        if(isset($data['charges'])){
            foreach ($data['charges'] as $cart_charge) {
                if ($cart_charge['charge_id'] == $request->search_charge) {
                    return response()->json(['success' => true, 'data' => $data]);
                }
            }
        }
        $tax_paid_by = TaxPaidBy::select('id','code')->where('id',$request->taxpaidby)->first();
        $amount      =  $request->charge_rate;

        $charge_qty = $request->charge_qty ;
        $charge_qty_amount = $charge_qty * $request->charge_rate;
        $charge_taxable_amount = $charge_qty_amount;
         $charges_tax = TaxMaster::select('id','name  as name')->where('id',$request->charge_tax)->first();

        $tax_per = $charges_tax->name == 'Tax Free' ? 0 : preg_replace('/[^0-9]/', '', $charges_tax->name);
        $tax  = ($tax_per / 100) * $charge_qty_amount;
   if($tax_paid_by->code ==  'TRANSPORTER') {
        $amount = $charge_qty_amount + $tax;
        }
        else{
             $amount        =  $charge_qty_amount;
        }

        $amount        = number_format($amount, 2, '.', '');

        $data_amount = $data['amount'] ?? 0 ;
        $data['amount'] = $data_amount + $amount;
        $data['charges'][] = [
            'charge_qty'             => $charge_qty ?? '',
            'account_id'            =>$charge->account_id ,
            'charge_id'              => $request->search_charge ?? '',
            'charge'                    => $charge->name ?? '',
            'charge_rate'            => $request->charge_rate ?? '',
            'charge_tax_id'      =>$request->charge_tax,
            'charge_taxable_amount'  =>$charge_taxable_amount,
            'tax_per'                 => $tax_per ?? '',
            'tax_flat'                  => $tax ?? '',
            'taxpaidby'              =>$tax_paid_by->code,
            'amount'                 => $amount ?? '',
        ];

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

        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true , 'data' => $data ,'total' => $total  ,'taxable_amount' => $taxable_amount]);
    }


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

        $amount = $data['amount'];

        $data['charges'] = array_filter($data['charges'], function ($charge) use ($id, &$data, &$amount) {
            if ($charge['charge_id'] == $id) {
                $amount = $data['amount'] - $charge['amount'];
            }

            return $charge['charge_id'] != $id;
        });

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

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

        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true ,'total' => $total ,'taxable_amount' => $taxable_amount]);
    }

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

        if (isset($data['charges'])) {
            foreach ($data['charges'] as $key => $value) {

                if($request->taxpaidby ==  'TRANSPORTER') {
                    if ($value['charge_id'] == $request->id) {
                    if (isset($request->charge_qty) && $request->charge_qty > 0) {
                        $data['amount'] = $data['amount'] - $value['amount'];
                        $data['charges'][$key]['charge_qty'] = $request->charge_qty;

                        $charge_qty_amount    = $request->charge_qty * $value['charge_rate'];

                        $flat_tax           = ($value['tax_per'] / 100) * $charge_qty_amount;
                        $charge_qty_amount    = ($charge_qty_amount + $flat_tax);

                        $data['products'][$key]['tax_flat'] = $flat_tax;
                        $data['charges'][$key]['amount'] = $charge_qty_amount;
                        $data['amount'] = $data['amount'] + $charge_qty_amount;
                    } 
                    }
                if ($value['charge_id'] == $request->id && isset($request->charge_rate)) {
                    $data['amount'] = $data['amount'] - $value['amount'];
                    $data['charges'][$key]['charge_rate'] = $request->charge_rate;

                    $charge_qty = $value['charge_qty'];

                    $charge_qty_amount = $value['charge_rate'] * $charge_qty;
                     $flat_discount = ($value['per_discount'] / 100) * $charge_qty_amount;
                    $flat_tax = ($value['tax_per'] / 100) * $charge_qty_amount;
                    $charge_qty_amount =  ($charge_qty_amount - $flat_discount);
                    $charge_qty_amount =  ($charge_qty_amount + $flat_tax);
                    $data['charge'][$key]['flat_discount'] = $flat_discount;
                    $data['charge'][$key]['tax_flat'] = $flat_tax;
                    $data['charge'][$key]['amount'] = $charge_qty_amount;
                    $data['amount'] = $data['amount'] + $charge_qty_amount;

                }
                }
        else{
                if ($value['charge_id'] == $request->id) {
                    if (isset($request->charge_qty) && $request->charge_qty > 0) {
                        $data['amount'] = $data['amount'] - $value['amount'];
                        $data['charges'][$key]['charge_qty'] = $request->charge_qty;

                        $charge_qty_amount    = $request->charge_qty * $value['charge_rate'];

                        $data['charges'][$key]['amount'] = $charge_qty_amount;
                        $data['amount'] = $data['amount'] + $charge_qty_amount;
                    } 
                    }
                if ($value['charge_id'] == $request->id && isset($request->charge_rate)) {
                    $data['amount'] = $data['amount'] - $value['amount'];
                    $data['charges'][$key]['charge_rate'] = $request->charge_rate;

                    $charge_qty = $value['charge_qty'];

                    $charge_qty_amount = $value['charge_rate'] * $charge_qty;

                    $data['charge'][$key]['amount'] = $charge_qty_amount;
                    $data['amount'] = $data['amount'] + $charge_qty_amount;

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

        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true , 'data' => $data ,'total' => $total ,'taxable_amount' => $taxable_amount ]);
    } 

    


     //**** Invoice cart work ****\\

     public function invoiceCart(Request $request, $id = 0)
    {
        $page = $request->page ?? '';
        $data = \Session::get('invoice_cart') ?? [];

        return view('booking.invoice-cart', compact('data', 'page', 'id'));
    }

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

       

        // Check if the charge already exists in the cart

        if(isset($data['invoice'])){

            foreach ($data['invoice'] as $cart_invoice) {

                if ($cart_invoice['bill_no'] == $request->bill_no) {
                    return response()->json(['success' => true, 'data' => $data]);
                }
            }
        }
        $amount      =  $request->invoice_value;

        $data_amount = $data['amount'] ?? 0 ;
        $data['amount'] = $data_amount + $amount;
        $data['due_balance_amount'] = round($data['amount']);
        $data['invoice'][] = [
            'bill_no'             => $request->bill_no ?? '',
            'bill_date'           => $request->bill_date ?? '',
            'invoice_value'       => $request->invoice_value ?? '',
            'way_bill_no'       => $request->way_bill_no ?? '',
            'way_bill_date'     => $request->way_bill_date ?? '',
            'way_exp_date'      => $request->way_exp_date ?? '',
            'amount'              => $amount ?? '',
        ];

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

        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true , 'data' => $data ,'total' => $total  ,'taxable_amount' => $taxable_amount]);
    }


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


        $amount = $data['amount'];

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

            return $invoice['bill_no'] != $id;
        });

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

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

         $total =$this->totalAmount();
         $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true ,'total' => $total ,'taxable_amount' => $taxable_amount]);
    }

    public function totalAmount()
    {
        $data1 = \Session::get('products_cart') ?? [];
        $data2 = \Session::get('charges_cart') ?? [];
        $data3 = \Session::get('invoice_cart') ?? [];

        $amount = ($data1['amount'] ?? 0) + ($data2['amount'] ?? 0) + ($data3['amount'] ?? 0);

        return $amount;
    }
    public function noTaxAmount()
    {
        $product = \Session::get('products_cart') ?? [];
        $charge = \Session::get('charges_cart') ?? [];
        if(count($product) > 0){
        foreach ($product['products'] as $key => $value) {
                $data1 = $value['taxable_amount'];
        } 
        }
         if(count($charge) > 0){
        foreach ($charge['charges'] as $key => $value) {
                $data2 = $value['charge_taxable_amount'];
        }
    }
        $data3 = \Session::get('invoice_cart') ?? [];

        $notaxamount = ($data1 ?? 0) + ($data2 ?? 0) + ($data3['amount'] ?? 0);
                return $notaxamount;
    }

      public function allProductAddToCart(Request $request)
    {
         \Session::get('all_products_cart');

        \Session::put('all_products_cart'," "); 

        $voucher_type_code = VoucherType::select('id','code')->where('id',$request->voucher_type)->first();

        $data['all_products'][] = [
            'consignor_id'       => $request->consignor_id ?? '',
            'consignee_id'       => $request->consignee_id ?? '',
            'vendor_id'          => $request->vendor_id ?? '',
            'voucher_type_id'       => $request->voucher_type ?? '',
            'voucher_type_code'       => $voucher_type_code->code ?? '',
            'bill_to_party'      => $request->bill_to_party ?? '',
            'from_id'            => $request->from_id ?? '',
            'to_id'              => $request->to_id ?? '',
            'tax_paid_by'          => $request->taxpaidby ?? '',
            'pickup_address'     => $request->pickup_address ?? '',
            'bill_to_address'    => $request->bill_to_address ?? '',
            'ship_to_address'    => $request->ship_to_address ?? '',
            'shipping_risk'      => $request->shipping_risk ?? '',
            'delivery_type'      => $request->delivery_type ?? '',
            'transport_type'      => $request->transport_type ?? '',
            'transportation_mode_id'      => $request->transportation_id ?? '',
            'container_no'      => $request->container_no ?? '',
            'seal_number'      => $request->seal_number ?? '',
            'do_number'      => $request->do_number ?? '',
            'do_validity_date'      => $request->do_validity_date ?? '',
            'container_return_expiry_date'      => $request->container_return_expiry_date ?? '',
            'lc_number'      => $request->lc_number ?? '',
            'lc_date'      => $request->lc_date ?? '',
            'lc_issued_by'      => $request->lc_issued_by ?? '',
            'cfs'      => $request->cfs ?? '',
        ];

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


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


 public function billings()
    {   
        $cart =\Session::get('products_cart');
        $products = $cart['products'] ?? '';
          if ($products == '')  {
            return redirect()->back()->with('error', 'Empty Product cart!');
        }
        $data = \Session::get('all_products_cart') ?? [];

        $id1 = [];
        $id2 = [];

        foreach($data['all_products'] as $value) {
            $id1[] = $value['consignor_id'];
            $id2[] = $value['consignee_id'];
            $id3[] = $value['vendor_id'];
        }

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

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

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

        $accountAddress = AccountAddress::whereIn('account_id',$id1)->orWhereIn('account_id',$id2)->where('is_default', 1)->first();

        $payment_mode = PaymentMode::where('status',1)->get();

        $consignor = [];
        $consignee = [];
        $vendor = [];
           foreach ($accounts as $item) {
            if ($item['type_code'] == 'CUSTOMER') {
                $consignor = $item;
            }
            }

            foreach ($consignees as $item) {
            if ($item['type_code'] == 'CUSTOMER') {
                $consignee = $item;
            }
            }

            foreach ($vendors as $item) {
            if ($item['type_code'] == 'CUSTOMER') {
                $vendor = $item;
            }
            }

        $accounting_group = Account::select([ 'id', 'name', 'account_category_id','accounting_group_id'])
            ->with('chart_of_account_sub_type')
            ->where(function ($query) {
                $query->whereHas('chart_of_account_sub_type', function ($accounting_group) {
                    $accounting_group->where('is_payment_mode', '1');
                });
            })
            ->get();

      $payment_terms =PaymentTerm::select('id','payment_term_name as name')->get();
      $total         = $this->totalAmount();
      $taxable_amount =$this->noTaxAmount();
      $account       = Account::select('id','name')->where('accounting_group_id',11)->get();

         $account_types     = MasterType::select(['id', 'type_name'])->where('type_code','CUSTOMER')->first();
        $accounting_groups = AccountingGroup::select(['id', 'name'])->where('code','SUNDRY_DEBTORS')->first();

        return view('booking.sale', compact([
            'data',
            'consignor',
            'consignee',
            'vendor',
            'accounting_group',
            'accounts',
            'accountAddress',
            'payment_terms',
            'taxable_amount',
            'account',
            'taxable_amount',
            'total',
            'account_types',
            'accounting_groups',
        ]));

     }
      public function bookingPrint($id)
    {
        $data = LogisticBooking::Select(
            'logistic_bookings.*',
            'consignor.name as consignor',
            'consignee.name as consignee',
            'vendor.name as vendor',
            'from_location.name as from_location',
            'to_location.name as to_location',
            'transportation_modes.name as transportation_mode',
            'shipping_address.address_line1 as shipping_address',
            'billing_address.address_line1 as billing_address',
            'despatch_from_address_id.address_line1 as pickup_address',
            'tax_paid_by.code as tax_paid_by',
            'delivery_types.name as delivery_type',
            'tax_paid_by.code as tax_paid_by',
            'payment_terms.payment_term_name as payment_term',
        )
        ->leftjoin('accounts as consignor','consignor.id','logistic_bookings.consignor_id')
        ->leftjoin('accounts as consignee','consignee.id','logistic_bookings.consignee_id')
        ->leftjoin('accounts as vendor','vendor.id','logistic_bookings.vendor_id')
        ->leftjoin('cities as from_location','from_location.id','logistic_bookings.from_location_id')
        ->leftjoin('cities as to_location','to_location.id','logistic_bookings.to_location_id')
        ->leftjoin('transportation_modes','transportation_modes.id','logistic_bookings.transportation_mode_id')
        ->leftjoin('account_addresses as shipping_address','shipping_address.id','logistic_bookings.ship_to_address_id')
        ->leftjoin('account_addresses as billing_address','billing_address.id','logistic_bookings.bill_to_address_id')
        ->leftjoin('tax_paid_by','tax_paid_by.id','logistic_bookings.tax_paid_by_id')
        ->leftjoin('delivery_types','delivery_types.id','logistic_bookings.delivery_type_id')
        ->leftjoin('account_addresses as despatch_from_address_id','despatch_from_address_id.id','logistic_bookings.despatch_from_address_id')
        ->leftjoin('payment_terms','payment_terms.id','logistic_bookings.payment_term_id')
        ->where('logistic_bookings.id',$id)
        ->get();

        $accountReceipt = AcReceipt::with('company','user','accountReceiptDetail','accountReceiptTransaction','accountReceiptTransaction.company','accountReceiptTransaction.user','accountReceiptTransaction.account','accountReceiptTransaction.module')
            // ->where(['id'=>$id])
            ->first();

        $products = LogisticBookingDetail::Select(
            'logistic_booking_details.*',
            'rate_calculation_types.code as rate_calc_on')
        ->leftjoin('rate_calculation_types','rate_calculation_types.id','logistic_booking_details.rate_calculation_on')
        ->where('booking_id',$id)
        ->get();

    return view('booking.printbooking',compact(
        'data',
        'products',
        'accountReceipt',
    ));
    }

    public function editContainer($id){

        $containerDetails = LogisticBookingContainerDetail::find($id);
        $container_sizes = ContainerSize::select('id','code')->get();
        $container_types = ContainerType::select('id','code')->get();
        $cargo_types = CargoType::select('id','code')->get();
        $custom_returns = ContainerReturnStatus::select('id','code')->get();
        $custom_clearances = CustomClearanceStatus::select('id','code')->get();
        $account          = Account::select('id','name')->where('id' , $containerDetails->lc_authority_id)
        ->first();
        $agent = Account::select('id','name')->where('id' , $containerDetails->cfs_agent_id )
        ->first();

        return view('containerDetails.edit' , compact(
            'containerDetails',
             'account' , 'agent',
             'container_sizes',
             'container_types',
             'cargo_types',
             'custom_returns',
             'custom_clearances',
         ));
    }

    public function updateContainer(Request $request,$id){

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $container = LogisticBookingContainerDetail::find($id);

        $container_return_expiry_date = $request->container_return_expiry_date != '' ? date('Y-m-d', strtotime($request->container_return_expiry_date)) : '';

        $data['container_return_expiry_date'] = $container_return_expiry_date;

        $container->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Container  Details updated successfully',
                'data'    => $data
            ]);
        }

        return redirect()->route('booking-register.index')
            ->with('success',' updated successfully');
    }

 
  public function bookingDetailsViewEdit($id)
    {
        $booking = LogisticBooking::find($id);
        $payment_terms     = PaymentTerm::select('id','payment_term_name')->get();
        $tax                              = TaxMaster::select('id','name')->get();
        $deliveries                 = DeliveryType::select('id','name')->get();
        $risks                          = ShippingRisk::select('id','name')->get();
        $transportations     = TransportationMode::select('id','code')->get();
        $transports               = TransportType::select('id','name')->get();
        $taxpaidby                = TaxPaidBy::select('id','code')->get();
        $license_types          = LicenseType::select('id','name','code')->where('is_mandatory', '1')->where('status',1)->get();
        $voucher_types       = VoucherType::select([
            'voucher_types.id as voucher_id',
            'voucher_types.code as code',
            'voucher_masters.id',
            'voucher_masters.voucher_code'])
        ->leftjoin('voucher_masters','voucher_masters.id','voucher_types.voucher_master_id')
        ->where('voucher_masters.voucher_code','SALES')
        ->get();

 $bill_to_party = [];
        if ($booking) {
            $bill_to_party['consignor'] = Account::Select('id','name')->where('id', $booking->consignor_id)->first();
            $bill_to_party['consignee'] = Account::Select('id','name')->where('id', $booking->consignee_id)->first();
            $bill_to_party['vendor'] = Account::Select('id','name')->where('id', $booking->vendor_id)->first();
        }

        return view('booking.editdetails',compact('booking',
            'transportations',
            'transports',
            'taxpaidby',
            'deliveries',
            'risks',
            'voucher_types',
            'payment_terms',
            'bill_to_party',
        ));
    } 

    public function bookingDetailsViewUpdate(Request $request,$id )
    {
       $data = $request;

        $data = [
            'voucher_type_id'                      => $data['voucher_type'],
            'tax_paid_by_id'                         => $data['taxpaidby'],
            'bill_to_account_id'                   => $data['bill_to_party'],
            'transportation_mode_id'       => $data['transportation_id'] ,
            'shipping_risk'                            => $data['shipping_risk'],
            'delivery_type_id'                      => $data['delivery_type'],
            'transport_type_id'                   => $data['transport_type']
         ];
        $booking = LogisticBooking::find($id);
        $booking->update($data);

        $voucher_type       = VoucherType::select([
            'voucher_types.id as voucher_id',
            'voucher_types.code as code',
            'voucher_masters.id',
            'voucher_masters.voucher_code'])
        ->leftjoin('voucher_masters','voucher_masters.id','voucher_types.voucher_master_id')
        ->where('voucher_masters.voucher_code','SALES')
        ->where('voucher_types.id',$request->voucher_type)
        ->first();
        $deliveries        = DeliveryType::select('id','name')->where('id',$request->delivery_type)->first();
        $risks             = ShippingRisk::select('id','name')->where('id',$request->shipping_risk)->first();
        $transportations   = TransportationMode::select('id','code')->where('id',$request->transportation_id )->first();
        $transports   = TransportType::select('id','name')->where('id',$request->transport_type)->first();
        $taxpaidby         = TaxPaidBy::select('id','code')->where('id',$request->taxpaidby)->first();
        $bill_to_party = Account::Select('id','name')->where('id', $request->bill_to_party)->first();

        $response = [
            'id'   => $id,
            'taxpaidby' => $taxpaidby->code,
            'voucher_type' => $voucher_type->code,
            'transportation_id' => $transportations->code,
            'shipping_risk' => $risks->name,
            'delivery_type' => $deliveries->name,
            'transport_type' => $transports->name,
            'bill_to_party' => $bill_to_party->name,
        ];
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Booking has been updates successfully',
                'data'    => $response
            ]);
        }
        return redirect()->route('booking.editdetails')
            ->with('success','Booking has been updates successfully.');
    }

  public function editInsurance($id)
    {
        $insurance = LogisticBookingInsurance::find($id);
        $account       = Account::select('id','name')->where('accounting_group_id',11)->get();

        return view('booking.editinsurance',compact(
            'insurance',
            'account',
        ));
    } 

    public function updateInsurance(Request $request,$id )
    {
       $data = $request;

        $data = [
            'insurance_provider'     => $data['insurance_provider'],
            'policy_no'                        => $data['policy_no'],
            'policy_amount'              => $data['policy_amount'],
            'policy_percentage'        => $data['policy_percentage'] ,
            'claim_amount'                => $data['claim_amount'],
         ];
        $Insurance = LogisticBookingInsurance::find($id); 
        $Insurance->update($data);

        $insurance_provider   = Account::select('name')->where('id',$data['insurance_provider'])->first();

        $response = [
            'id'   => $id,
            'insurance_provider' => $insurance_provider->name,
            'policy_no' => $request->policy_no,
            'policy_amount' => $request->policy_amount,
            'policy_percentage' => $request->policy_percentage,
            'claim_amount' => $request->claim_amount,
        ];

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Insurance has been updates successfully',
                'data'    => $response,
            ]);
        }
        return redirect()->route('booking-register.index')
            ->with('success','Insurance has been updates successfully.');
        }

 public function productCart(Request $request, $id = 0)
    {
        $items = LogisticBookingDetail::select(
            'logistic_booking_details.*',
            'rate_calculation_types.name  as rate_calculation_type',
            )
             ->leftjoin('rate_calculation_types','rate_calculation_types.id','logistic_booking_details.rate_calculation_on')
             ->where('booking_id',$request->booking_id)
             ->get();

            if(isset($items) && count($items) > 0 ){
              foreach ($items as $item) {
                    $amount        =  $item->rate;

                    $rate_cal_type_name = RateCalculationType::select('name')->where('id',$item->rate_calculation_on)->first();

                    $item_qty = $item->quantity ;

                    $item_hours = $item->hours  ;
                    $item_distance = $item->distance  ;
                    $gross_weight =$item->gross_weight;
                    
                    if($rate_cal_type_name->name ==  'Weight') {
                         $amount = $gross_weight * $amount;
                    }
                    elseif ($rate_cal_type_name->name==  'Quantity') {
                           $amount = $item_qty * $amount;
                    }
                    elseif ($rate_cal_type_name->name ==  'Hours') {
                           $amount = $item_hours * $amount;
                    }
                    elseif ($rate_cal_type_name->name ==  'Distance') {
                           $amount = $item_distance * $amount;
                    }
                    else{
                         $amount;
                    }

                $tax_name = TaxMaster::select('name')->where('id',$item->tax_id)->first();
                $item_tax_per = $tax_name->name == 'Tax Free' ? 0 : preg_replace('/[^0-9]/', '', $tax_name->name) ?? '';
                $item_tax_amount  = ($item_tax_per / 100) * $amount ?? '';
            }
        }
            else{
            $item_tax_per = '';
             $item_tax_amount = '';
        }

        return view('booking.edit_products-cart', compact(
            'items',
            'item_tax_per',
            'item_tax_amount',
             'id',
         ));
    }
   
     public function storeitem(Request $request)
      {
        $product = Product::select('products.id','products.name','tax_masters.name as tax','tax_masters.id as tax_id')
                    ->leftjoin('tax_masters','tax_masters.id','products.tax_slab_id')
                    ->leftjoin('product_prices','products.id','product_prices.product_id')
                    ->where('products.id', $request->search_product)
                    ->first();

        $amount        =  $request->product_price;
        $tax_paid_by = $request->taxpaidby;
        $rate_cal_type_name = RateCalculationType::select('name')->where('id',$request->rate_calculation_type)->first();
 
        $item_qty = $request->item_qty ;
        $item_hours = $request->hours  ;
        $item_distance = $request->distance  ;
        $gross_weight =$request->gross_weight;
        
        if($rate_cal_type_name->name ==  'Weight') {
             $amount = $gross_weight * $amount;
        }
        elseif ($rate_cal_type_name->name==  'Quantity') {
               $amount = $item_qty * $amount;
        }
        elseif ($rate_cal_type_name->name ==  'Hours') {
               $amount = $item_hours * $amount;
        }
        elseif ($rate_cal_type_name->name ==  'Distance') {
               $amount = $item_distance * $amount;
        }
        else{
             $amount;
        }
        $taxable_amount = $amount;

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

        if($tax_paid_by ==  'TRANSPORTER') {
        $amount = $amount + $tax;
        }
     
        $amount        = number_format($amount, 2, '.', '');

        $weight_type_code =  PrimaryUnit::select('code')->where('id',$request->weight_type)->first();
        
        $data = LogisticBookingDetail::insert([
            'booking_id'                 => $request->booking_id,
            'quantity'                      => $item_qty ?? '',
            'product_id'                 => $request->search_product ?? '',
            'item_details'               => $product->name ?? '',
            'rate'                               => $request->product_price ?? '',
            'total_amount'             => $amount ?? '',
            'tax_id'                           =>$product->tax_id,
            'rate_calculation_on' => $request->rate_calculation_type,
            'actual_weight'           => $request->actual_weight ??'',
            'gross_weight'            => $request->gross_weight,
            'hours'                           => $request->hours ??'',
            'distance'                      => $request->distance ??'',
            'weight_calculation_on'   => $weight_type_code->code,
            'weight_type_id'         => $request->weight_type,
            "created_at"                =>  \Carbon\Carbon::now(), 
            "updated_at"               => \Carbon\Carbon::now(), 
        ]);

        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();

        return response()->json([ 'success' => true , 'item' => $data ,'total' => $total ,'taxable_amount' => $taxable_amount ]);
    }
public function editItem($id)
    {
        $item = LogisticBookingDetail::find($id);
        $weights           = PrimaryUnit::select('id','name','code')->where('unit_type','Weight')->get();
        $rate_calculations = RateCalculationType::select('id','name')->get();
         $vehicles               = VehicleType::select('id','name')->get();
      
        return view('booking.edititem',compact(
            'item',
            'weights',
            'rate_calculations',
            'vehicles',
        ));
    }

public function updateitem(Request $request, $id)
    {
        $booking = LogisticBookingDetail::find($id);
        $product = Product::select('products.id','products.name','tax_masters.name as tax','tax_masters.id as tax_id')
                    ->leftjoin('tax_masters','tax_masters.id','products.tax_slab_id')
                    ->leftjoin('product_prices','products.id','product_prices.product_id')
                    ->where('products.id', $booking->product_id)
                    ->first();

        $data = $request;
        $amount        =  $data->product_price;

      $taxpaidby = LogisticBooking::select('tax_paid_by_id as taxpaidby')->where('id',$booking->booking_id)->first();
      $tax_paid_by = TaxPaidBy::select('id','code')->where('id',$taxpaidby['taxpaidby'])->first();

        $rate_cal_type_name = RateCalculationType::select('name')->where('id',$data->rate_calculation_types)->first();
 
        $item_qty = $data->item_qty ;
        $item_hours = $data->hours  ;
        $item_distance = $data->distance  ;
        $gross_weight =$data->gross_weight;
        
        if($rate_cal_type_name->name ==  'Weight') {
             $amount = $gross_weight * $amount;
        }
        elseif ($rate_cal_type_name->name==  'Quantity') {
               $amount = $item_qty * $amount;
        }
        elseif ($rate_cal_type_name->name ==  'Hours') {
               $amount = $item_hours * $amount;
        }
        elseif ($rate_cal_type_name->name ==  'Distance') {
               $amount = $item_distance * $amount;
        }
        else{
             $amount;
        }
        $taxable_amount = $amount;

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

        if($tax_paid_by->code ==  'TRANSPORTER') {
           
        $amount = $amount + $tax;
        }
        $amount        = number_format($amount, 2, '.', '');

         $weight_type_code =  PrimaryUnit::select('code')->where('id',$request->weight_type)->first();

        $data = [
            'quantity'                       => $data['item_qty'],
            'rate_calculation_on'  => $data['rate_calculation_types'],
            'actual_weight'             => $data['actual_weight'] ??'',
            'gross_weight'              => $data['gross_weight'],
            'weight_type_id'           => $data['weight_type'],
            'weight_calculation_on'           => $data['weight_type_code'],
            'rate'                                => $data['product_price'],
            'distance'                        => $data['distance'] ??'',
            'hours'                             => $data['hours'] ??'',
            'length'                            => $data['length'] ??'',
            'breadth'                         => $data['breadth'] ??'',
            'height'                            => $data['height'] ??'',
            'total_amount'               => $amount,
         ];
        
        $booking->update($data);

        $response = [
            'id'   => $id,
            'taxpaidby' => $request->taxpaidby,
            'voucher_type' => $request->voucher_type,
            'transportation_id' => $request->transportation_id,
            'shipping_risk' => $request->shipping_risk,
            'delivery_type' => $request->delivery_type,
            'transport_type' => $request->transport_type,
            'bill_to_party' => $request->bill_to_party,
        ];

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Item has been updates successfully',
                'data'    => $response
            ]);
        }
    }
   public function destroyitem(Request $request)
    { 
        $type = LogisticBookingDetail::find($request->id);
     
        $items = LogisticBookingDetail::select( \DB::raw('COUNT(id) as total_count'))
            ->where('booking_id',$type->booking_id)
            ->groupBy('booking_id')
            ->get();
           
            $count =  $items[0]['total_count'];
          
     if(isset($count) && $count > 0 ){
            return response()->json([
                'success' => false,
                'message' => ['At least one item is required.']
            ]);
        }
        else{
               $type->delete();
        }

         $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true ,'total' => $total,'taxable_amount' => $taxable_amount]);
    }
    public function storecharge(Request $request)
    {
        $charge = AdditionalCharge::select('additional_charges.id','additional_charges.name','additional_charges.account_id')
                    ->where('additional_charges.id', $request->search_charge)
                    ->first();

        $tax_paid_by = $request->taxpaidby;
        $amount      =  $request->charge_rate;
        $charge_qty = $request->charge_qty ;
        $charge_qty_amount = $charge_qty * $request->charge_rate;
        $charge_taxable_amount = $charge_qty_amount;
         $charges_tax = TaxMaster::select('id','name  as name')->where('id',$request->charge_tax)->first();
        $tax_per = $charges_tax->name == 'Tax Free' ? 0 : preg_replace('/[^0-9]/', '', $charges_tax->name);
        $tax  = ($tax_per / 100) * $charge_qty_amount;
   if($tax_paid_by ==  'TRANSPORTER') {
        $amount = $charge_qty_amount + $tax;
        }
        else{
             $amount        =  $charge_qty_amount;
        }
        $amount        = number_format($amount, 2, '.', '');

        $data = LogisticBookingCharge::insert([
        'booking_id'                 => $request->booking_id,
        'charge_quantity'       => $charge_qty ?? '',
        'charge_account_id'   =>$charge->account_id ,
        'charge_rate'                => $request->charge_rate ?? '',
        'charge_tax_id'             =>$request->charge_tax,
        'charge_amount'         => $amount ?? '',
        'created_by_user_id'  => \Auth::id( ) ?? '',
        'updated_by_user_id' => \Auth::id( ) ?? '',
         ]);
        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true , 'data' => $data ,'total' => $total  ,'taxable_amount' => $taxable_amount]);
}

public function chargeCart(Request $request, $id = 0)
    {
        
        $charges = LogisticBookingCharge::select(
            'logistic_booking_charges.*',
            'additional_charges.name  as additional_charges',
            )
             ->leftjoin('additional_charges','additional_charges.account_id','logistic_booking_charges.charge_account_id')
             ->where('booking_id',$request->booking_id)
             ->get();
        
        if(isset($charges) && count($charges) > 0 ){
             foreach ($charges as $charge) {
                $charge_amount = $charge->charge_rate*$charge->charge_quantity;
                $charge_tax_name = TaxMaster::select('name')->where('id',$charge->charge_tax_id)->first();
                $charge_tax_per = $charge_tax_name->name == 'Tax Free' ? 0 : preg_replace('/[^0-9]/', '', $charge_tax_name->name) ?? '';
                $charge_tax  = ($charge_tax_per / 100) * $charge_amount ?? '';
            }
        }
        else{
            $charge_tax_per = '';
             $charge_tax = '';
        }


        return view('booking.edit_additionalcharges-cart', compact(
            'charges',
            'charge_tax_per',
            'charge_tax',
             'id'
         ));
    }

public function editcharge($id)
    {
        $charge = LogisticBookingCharge::find($id);
        $tax               = TaxMaster::select('id','name')->get();
        return view('booking.editcharge',compact(
            'charge',
            'tax'
        ));
    }

public function updatecharge(Request $request, $id)
    {
      $booking_charge = LogisticBookingCharge::find($id);

      $taxpaidby = LogisticBooking::select('tax_paid_by_id as taxpaidby')->where('id',$booking_charge->booking_id)->first();
      $tax_paid_by = TaxPaidBy::select('id','code')->where('id',$taxpaidby['taxpaidby'])->first();

        $amount      =  $request->charge_rate;
        $charge_qty = $request->charge_quantity ;
        $charge_qty_amount = $charge_qty * $request->charge_rates;
        $charge_taxable_amount = $charge_qty_amount;
        $charges_tax = TaxMaster::select('id','name  as name')->where('id',$request->charge_tax)->first();

        $tax_per = $charges_tax->name == 'Tax Free' ? 0 : preg_replace('/[^0-9]/', '', $charges_tax->name);
        $tax  = ($tax_per / 100) * $charge_qty_amount;

   if($tax_paid_by->code ==  'TRANSPORTER') {
        $amount = $charge_qty_amount + $tax;
        }
        else{
             $amount        =  $charge_qty_amount;
        }
        $amount        = number_format($amount, 2, '.', '');
        $data = [
            'charge_quantity'            => $charge_qty ?? '',
            'charge_rate'           => $request->charge_rates ?? '',
            'charge_tax_id'         =>$request->charge_tax,
            'charge_amount'                => $amount ?? '',
         ];
        $booking_charge->update($data);
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Charge updated successfully',
                'data'    => $data
            ]);
        }
    }
    public function destroycharge(Request $request)
    {
        $charge = LogisticBookingCharge::find($request->id);
        $charge->delete();
        
         $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true ,'total' => $total,'taxable_amount' => $taxable_amount]);
    }

    public function invoicesCart(Request $request, $id = 0)
    {
        $invoice = LogisticBookingConsignorWaybill::where('booking_id',$request->booking_id)
             ->get();

        return view('booking.edit_invoice-cart', compact(
            'invoice',
         ));
    }

    public function storeinvoice(Request $request)
    { 
        $bill_date         =  $request->bill_date != '' ? date('Y-m-d', strtotime( $request->bill_date )) : '';
        $way_bill_date        =  $request->way_bill_date != '' ? date('Y-m-d', strtotime( $request->way_bill_date )) : '';
        $way_exp_date =  $request->way_bill_date != '' ? date('Y-m-d', strtotime( $request->way_exp_date )) : '';

         $data = LogisticBookingConsignorWaybill::insert([
        'booking_id'                 => $request->booking_id,
        'consignor_invoice_date'       => $bill_date,
        'consignor_invoice_no'   =>$request->bill_no,
        'consignor_invoice_value'                => $request->invoice_value,
        'way_bill_no'             =>$request->way_bill_no,
        'way_bill_date'             =>$way_bill_date,
        'way_bill_expiry_date'             =>$way_exp_date,
         ]);

        $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true , 'data' => $data ,'total' => $total  ,'taxable_amount' => $taxable_amount]);
}

public function editinvoice($id)
    {
        $invoice = LogisticBookingConsignorWaybill::find($id);

        return view('booking.editinvoice',compact(
            'invoice',
        ));

    }

public function updateinvoice(Request $request, $id)
    {
      $booking_invoice = LogisticBookingConsignorWaybill::find($id);

        $data = [
            'consignor_invoice_date'   => $request->consignor_invoice_date,
            'consignor_invoice_no'       => $request->consignor_invoice_no,
            'consignor_invoice_value' => $request->consignor_invoice_value,
            'way_bill_no'                          => $request->way_bill_no,
            'way_bill_date'                      => $request->way_bill_date,
            'way_bill_expiry_date'        => $request->way_exp_date,

         ];
        $booking_invoice->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Invoice updated successfully',
                'data'    => $data
            ]);
        }
    }

    public function destroyinvoice(Request $request)
    {
        $invoice = LogisticBookingConsignorWaybill::find($request->id);
        $invoice->delete();
        
         $total =$this->totalAmount();
        $taxable_amount =$this->noTaxAmount();
        return response()->json([ 'success' => true ,'total' => $total,'taxable_amount' => $taxable_amount]);
    }

    public function editPickupAddress($id){
        $account_id = LogisticBooking::select('despatch_from_address_id')->where('id',$id)->first();
        $pickup_address = AccountAddress::find($account_id->despatch_from_address_id);

        return view('booking.editpickupaddress' , compact(
            'pickup_address',
         ));
    }

    public function updatePickupAddress(Request $request,$id){

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $address = AccountAddress::find($id);

        $address->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => ' Pickup Address updated successfully',
                'data'    => $data
            ]);
        }

        return redirect()->route('booking-register.index')
            ->with('success',' updated successfully');
    }


    public function editBilltoAddress($id){
        $account_id = LogisticBooking::select('bill_to_address_id')->where('id',$id)->first();
        $billto_address = AccountAddress::find($account_id->bill_to_address_id);

        return view('booking.editbilltoaddress' , compact(
            'billto_address',
         ));
    }

    public function updateBilltoAddress(Request $request,$id){

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $address = AccountAddress::find($id);

        $address->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => ' Bill To Address updated successfully',
                'data'    => $data
            ]);
        }

        return redirect()->route('booking-register.index')
            ->with('success',' updated successfully');
    }


    public function editShiptoAddress($id){
        $account_id = LogisticBooking::select('ship_to_address_id')->where('id',$id)->first();
        $shipto_address = AccountAddress::find($account_id->ship_to_address_id);

        return view('booking.editshiptoaddress' , compact(
            'shipto_address',
         ));
    }

    public function updateShiptoAddress(Request $request,$id){

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $address = AccountAddress::find($id);

        $address->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Ship To Address updated successfully',
                'data'    => $data
            ]);
        }

        return redirect()->route('booking-register.index')
            ->with('success',' updated successfully');
    }


    public function editBrokerDetails($id){
        $brokers = LogisticBooking::find($id);
        $broker   =  Account::select('id','name')->where('id',$brokers->broker_id)->first();
      
        return view('booking.editbroker',compact('brokers','broker'));
    }

    public function updateBrokerDetails(Request $request,$id){

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $address = LogisticBooking::find($id);

        $address->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Booker updated successfully',
                'data'    => $data
            ]);
        }

        return redirect()->route('booking-register.index')
            ->with('success',' updated successfully');
    }

    public function editaccount(Request $request, $id)
    {
        $type = $request->type;
        $booking_id = $request->booking_id;
        $accounts = Account::select('id','name')->where('id',$id)->first();
        $account_types     = MasterType::select(['id', 'type_name'])->where('type_code','CUSTOMER')->first();
        $accounting_groups = AccountingGroup::select(['id', 'name'])->where('code','SUNDRY_DEBTORS')->first();

        return view('booking.editaccount',compact(
            'accounts',
            'type',
            'account_types',
            'accounting_groups',
            'booking_id'
        ));
    }
    public function createaccount(Request $request)
    {
        $license_types = LicenseType::select('id','name','code')->where('is_mandatory', '1')->where('status',1)->get();
        $country         = Country::select(['id','name'])->get();
        $company_address = \Session::get('company_data')['companies_addresses'] ?? '';

        $country_id = $company_address['country_id'] ?? '';
        $state_id   = $company_address['state_id'] ?? '';
        $city_id    = $company_address['city_id'] ?? '';

        $booking_id = $request->booking_id;

        return view('booking.createaccount', compact(
            'country',
            'country_id',
            'state_id',
            'city_id',
            'license_types',
            'booking_id'
        ));
    }
     public function storeaccount(Request $request)
    {
            $validator = \Validator::make($request->all(), [
            'phone_no'                 => [
                'required',
                function ($attribute, $value, $fail) use ($request) {
                    $existingContact = AccountContact::where('name', $request->name)
                        ->where('phone_no', $value)
                        ->exists();
                    if ($existingContact) {
                        $fail('This Name and Phone No combination already exists.');
                    }
                }
            ],
            'name'                     => [
                'required',
                function ($attribute, $value, $fail) use ($request) {
                    $existingContact = AccountContact::where('phone_no', $request->phone_no)
                        ->where('name', $value)
                        ->exists();
                    if ($existingContact) {
                        $fail('This Name and Phone No combination already exists.');
                    }
                }
            ],
        ], [
            'required' => 'The :attribute field is required.',
            'unique'   => 'This Name and Phone No are already taken.',
        ]);

        // Check if validation fails
        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->errors()->first());
        }

        $type = MasterType::findOrFail($request->account_type_id);

        if (isset($type) && strtolower($type->type_name) != 'student') {
            $rules['accounting_group_id'] = 'required';

        }

        $validator = \Validator::make($request->all(), $rules, [
            'unique' => 'This Name and Phone No are already taken.',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
         }
        $company_id         = \Auth::user()->company_id ?? '';

        $data = $request->except([
             '_token',
            '_method',
            'country_id',
            'state_id',
            'cityid',
            'city_id',
            'phone_no',
            'whatsapp_no',
            'address',
            'email',
            'contact',
            'license_type_id',
            'license_number',
            'valid_from',
            'valid_upto',
            'postal_code',
            'type',
            'booking_id',
        ]);
        $data['company_id'] = $company_id;
        $account = Account::create($data);
       
         $data = $request->input('license_number');

        if (!is_null($data) && is_array($data)) {
            foreach ($data as $type => $licenseInfo) {
                if (!empty($licenseInfo['license_number'])) {
                    AccountLicense::create([
                        'account_id'      => $account->id,
                        'license_number'  => $licenseInfo['license_number'],
                        'license_type_id' => $licenseInfo['license_type_id'],
                        'valid_from'      => '',
                        'valid_upto'      => '',
                    ]);
                }
            }
        }

       $address = AccountAddress::insert([
            'account_id'    => $account->id,
            'country_id'    => $request->country_id,
            'state_id'      => $request->state_id,
            'city_id'       => $request->city_id,
            'address_line1' => $request->address,
            'post_code'     => $request->postal_code,
            'is_default'    => '1'
        ]);

        $contact = AccountContact::insert([
            'account_id'          => $account->id,
            'phone_no'            => $request->phone_no,
            'whatsapp_no'         => $request->whatsapp_no,
            'email'               => $request->email ?? '',
            'name'                => $request->name ?? '',
            'country_id'          => $request->country_id,
            'state_id'            => $request->state_id,
            'city_id'             => $request->city_id,
            'pin'                 => $request->postal_code,
            'postal_code'         => $request->postal_code,
            'address'             => $request->address,
        ]);
   
        if($request->type == 'consignor'){
            $booking = LogisticBooking::find($request->booking_id);
        $data1 = [
            'consignor_id'   => $account->id,
         ];
        $booking->update($data1);
        }
        if($request->type == 'consignee'){
            $booking = LogisticBooking::find($request->booking_id);
        $data1 = [
              'consignee_id'   => $account->id,
         ];
        $booking->update($data1);
        }
        if($request->type == 'vendor'){
            $booking = LogisticBooking::find($request->booking_id);
        $data1 = [
               'vendor_id'   => $account->id,
         ];
        $booking->update($data1);
        }

        $response = [
            'id'         => $account->id,
            'name'       => $request->name,
            'address'    => $request->address,
            'country_id' => $request->country_id,
        ];
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Customer has been created successfully',
                'data'    => $response
            ]);
        }
        return redirect()->route('booking.show')
            ->with('success','Customer has been created successfully.');
    }


}   
    
