<?php
    
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Accessory;
use App\Models\Allocation;
use App\Models\Approval;
use App\Models\Branch;
use App\Models\CarExchange;
use App\Models\ExtandWarranty;
use App\Models\Fasttag;
use App\Models\Finance;
use App\Models\Insurance;
use App\Models\Lead;
use App\Models\OBF;
use App\Models\User;
use App\Models\Product;
use App\Models\Tax;
use App\Models\Order;
use App\Models\Inventory;
use App\Models\TransitInventory;
use App\Models\Exchange;
use App\Models\Texmaster;
use App\Models\Carvarient;
use App\Models\MakeDeal;
use Carbon\Carbon;
use PDF;
use Auth, DB, Mail, Validator, File, DataTables;

class OrderController extends Controller{
    /** construct */
    public function __construct(){
        $this->middleware('permission:orders-create', ['only' => ['create']]);
        $this->middleware('permission:orders-edit', ['only' => ['edit']]);
        $this->middleware('permission:orders-view', ['only' => ['view']]);
        $this->middleware('permission:orders-delete', ['only' => ['delete']]);
    }
    /** construct */

    /** index */
    public function index(Request $request){
        if($request->ajax()){
            // $data = DB::table('orders as o')->select(
            //     'o.id', 
            //     'o.order_id', 
            //     'o.status',
            //     'o.obf_id', 
            //     'b.name as branch_name',
            //     'ob.status as obf_status',
            //     // 'o.invoice_no',
            //     'o.invoice_date',
            //     'o.dealer_id',
            //     DB::raw("COALESCE(ob.customer_name, dealer_management.dealer_name) AS customer_name"),
            //     'car_model.name as carmodel',
            //     'car_varient.name as carvarient',
            //     'inventory.allocation_count',
            //     'inventory.aging_days',
            //     DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name"),
            //     // 'o.vin_number',
            //     // DB::raw('(SELECT vin_number FROM inventory WHERE inventory.status IN ("allocated", "allocatedDealer") AND inventory.vin_number = o.vin_number AND inventory.branch_id = o.branch_id) as vin_number'),
            //     DB::raw('(SELECT vin_number FROM inventory WHERE inventory.vin_number = o.vin_number AND inventory.branch_id = o.branch_id ORDER BY inventory.id DESC LIMIT 1) as vin_number'),
            //     'ob.on_road_price',
            //     'obf_finance.finance_discount',
            //     'obf_finance.net_disbusment',
            //     'ob.way_off',
            //     'ob.offer_ib_amount',
            //     'ob.offer_kin_amount',
            //     'ob.foc_accessories',
            //     DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = ob.id AND cash_receipt.receipt_type = "booking_receipt" AND cash_receipt.status != "rejected") as booking_amount'),
            //     DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = ob.id AND cash_receipt.receipt_type = "downpayment_receipt" AND cash_receipt.status != "rejected") as dp_amount'),
            //     DB::raw('(SELECT total_exchange_amount FROM exchange_purchase WHERE exchange_purchase.obf_id = ob.id AND exchange_purchase.status = "active" LIMIT 1) as total_exchange_amount'),
            //     DB::raw("CASE WHEN o.invoice_no IS NOT NULL AND o.invoice_date IS NOT NULL THEN o.invoice_no ELSE '---' END as invoice_no"),
            //     'ob.number_plate as number_plate',
            //     'obf_insurance.company_name as insurance_company_name',
            //     'obf_insurance.status as insurance_status',
            //     'ob.branch_id'
            // )    
            // ->leftjoin('branches as b', 'b.id', 'o.branch_id')
            // ->leftjoin('obf as ob', 'ob.id', 'o.obf_id')
            // ->leftjoin('obf_finance', 'obf_finance.obf_id', 'ob.id')
            // ->leftjoin('obf_insurance', 'obf_insurance.obf_id', 'ob.id')
            // ->leftjoin('exchange_purchase','exchange_purchase.obf_id','=','ob.id')
            // ->leftjoin('dealer_management', 'dealer_management.id', 'o.dealer_id')
            // ->leftjoin('users','users.id','o.customer_id')
            // ->leftjoin('products','products.id','ob.product_id')
            // ->leftjoin('car_model','car_model.id','products.car_model')
            // ->leftjoin('users as us','us.id','ob.sales_person_id')
            // ->leftjoin('car_varient','car_varient.id','products.veriant')
            // // ->leftjoin('inventory','inventory.vin_number','o.vin_number')     
            // ->leftJoin("inventory", function ($join) {
            //     $join->on("inventory.vin_number", "=", "o.vin_number");
            //     $join->on("inventory.branch_id", "=", "o.branch_id");
            // })
            // ->leftjoin('cash_receipt','cash_receipt.obf_id','=','ob.id');
            // ->where(function($query) {
            //     $query->whereNotNull('cash_receipt.id')
            //           ->orWhereNotNull('cash_receipt.amount')
            //           ->orWhereNull('ob.id');
            // });
            // $data->groupBy('o.id');
            // $data->orderBy('o.id', 'desc');
            
            $exchangeSummary = DB::table('exchange_purchase')
                    ->select('obf_id', DB::raw('total_exchange_amount'))
                    ->whereIn('status', ['active','sell']);
            
            $data = DB::table('orders as o')
            ->select(
                'o.id', 
                'o.order_id', 
                'o.status',
                'o.obf_id', 
                'b.name as branch_name',
                'ob.status as obf_status',
                'o.invoice_date',
                'o.dealer_id',
                DB::raw("COALESCE(ob.customer_name, dealer_management.dealer_name) AS customer_name"),
                'car_model.name as carmodel',
                'car_varient.name as carvarient',
                'inventory.allocation_count',
                'inventory.aging_days',
                DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name"),
                DB::raw("CASE WHEN o.invoice_no IS NOT NULL AND o.invoice_date IS NOT NULL THEN o.invoice_no ELSE '---' END as invoice_no"),
                // DB::raw("COALESCE(MAX(o.invoice_date), '--') as invoice_date"),
                DB::raw("COALESCE(booking.booking_amount, 0) as booking_amount"),
                DB::raw("COALESCE(dp.dp_amount, 0) as dp_amount"),
                // DB::raw("COALESCE(ex.total_exchange_amount, 0) as total_exchange_amount"),
                DB::raw('(ex.total_exchange_amount) as total_exchange_amount'),
                DB::raw("COALESCE(dis.net_disbusment, 0) as net_disbusment"),
                'ob.on_road_price',
                'obf_finance.finance_discount',
                'ob.way_off',
                'ob.offer_ib_amount',
                'ob.offer_kin_amount',
                'ob.foc_accessories',
                'ob.number_plate as number_plate',
                'obf_insurance.company_name as insurance_company_name',
                'ob.branch_id',
                'ob.booking_date',
                'ob.insurance_status',
                'ob.rto_status',
                'ob.municipal_tax_status',
                'o.vin_number',
                DB::raw('ROUND(SUM(cash_receipt.amount)) as received_amount'),
                DB::raw("ROUND(COALESCE(ob.on_road_price, 0) - COALESCE(booking.booking_amount, 0) - COALESCE(dp.dp_amount, 0) - COALESCE(dis.net_disbusment, 0) - COALESCE(ex.total_exchange_amount, 0) - COALESCE(obf_finance.finance_discount, 0) - COALESCE(ob.way_off, 0) - COALESCE(ob.tl_discount, 0) - COALESCE(ob.sm_discount, 0) - COALESCE(ob.gm_discount, 0) - COALESCE(ob.bh_discount, 0) - COALESCE(ob.ceo_discount, 0) - COALESCE(ob.md_discount, 0) - COALESCE(ob.foc_accessories, 0) - COALESCE(ob.offer_ib_amount, 0) - COALESCE(ob.offer_kin_amount, 0), 2) as due_amount"),
                'ob.tl_discount',
                'ob.sm_discount',
                'ob.gm_discount',
                'ob.bh_discount',
                'ob.ceo_discount',
                'ob.md_discount',
                'us.contact_number as sales_person_number',
                'ob.contact_number as customer_number',
            )
            // Joins
            ->leftJoin('branches as b', 'b.id', '=', 'o.branch_id')
            ->leftJoin('obf as ob', 'ob.id', '=', 'o.obf_id')
            ->leftJoin('cash_receipt', 'cash_receipt.obf_id', '=', 'ob.id')
            ->leftJoin('obf_finance', 'obf_finance.obf_id', '=', 'ob.id')
            ->leftJoin('obf_insurance', 'obf_insurance.obf_id', '=', 'ob.id')
            ->leftJoin('dealer_management', 'dealer_management.id', '=', 'o.dealer_id')
            ->leftJoin('users as us', 'us.id', '=', 'ob.sales_person_id')
            ->leftJoin('products', 'products.id', '=', 'ob.product_id')
            ->leftJoin('car_model', 'car_model.id', '=', 'products.car_model')
            ->leftJoin('car_varient', 'car_varient.id', '=', 'products.veriant')
            ->leftJoin("inventory", function ($join) {
                $join->on("inventory.vin_number", "=", "o.vin_number");
                $join->on("inventory.branch_id", "=", "o.branch_id");
            })
        
            // Optimized subqueries as joins
            ->leftJoin(DB::raw("(
                SELECT obf_id, SUM(amount) as booking_amount
                FROM cash_receipt
                WHERE receipt_type = 'booking_receipt' AND status != 'rejected'
                GROUP BY obf_id
            ) as booking"), 'booking.obf_id', '=', 'ob.id')
        
            ->leftJoin(DB::raw("(
                SELECT obf_id, SUM(amount) as dp_amount
                FROM cash_receipt
                WHERE receipt_type = 'downpayment_receipt' AND status != 'rejected'
                GROUP BY obf_id
            ) as dp"), 'dp.obf_id', '=', 'ob.id')
        
            /*->leftJoin(DB::raw("(
                SELECT obf_id, total_exchange_amount
                FROM exchange_purchase
                WHERE status = 'active'
                GROUP BY obf_id
            ) as ex"), 'ex.obf_id', '=', 'ob.id')*/
            
            ->leftJoinSub($exchangeSummary, 'ex', 'ex.obf_id', '=', 'ob.id')
            
            ->leftJoin(DB::raw("(
                SELECT obf_id, SUM(amount) as net_disbusment
                FROM cash_receipt
                WHERE receipt_type = 'disbusment_receipt' AND status != 'rejected'
                GROUP BY obf_id
            ) as dis"), 'dis.obf_id', '=', 'ob.id');
            
            
            if(!empty(auth()->user()->branch)){
                $data =$data->whereRaw('FIND_IN_SET(o.branch_id ,"'.auth()->user()->branch.'")');
            }
            
            if(auth()->user()->roles && auth()->user()->roles[0]['name'] == 'Gatepass Coordinator') {
                $data = $data
                ->whereNotNull('o.invoice_no')
                ->where('o.status', '!=', 'invoice_cancel')
                ->where(function ($query) {
                    $query->whereRaw('
                        (ob.on_road_price - 
                         (COALESCE(booking.booking_amount, 0) + 
                          COALESCE(dp.dp_amount, 0) + 
                          COALESCE(dis.net_disbusment, 0) + 
                          COALESCE(ex.total_exchange_amount, 0)) - 
                         (COALESCE(obf_finance.finance_discount, 0) + 
                          COALESCE(ob.way_off, 0) + 
                          COALESCE(obf.tl_discount, 0) + 
                          COALESCE(obf.sm_discount, 0) + 
                          COALESCE(obf.gm_discount, 0) + 
                          COALESCE(obf.bh_discount, 0) + 
                          COALESCE(obf.ceo_discount, 0) + 
                          COALESCE(obf.md_discount, 0) + 
                          COALESCE(ob.foc_accessories, 0) + 
                          COALESCE(ob.offer_ib_amount, 0) + 
                          COALESCE(ob.offer_kin_amount, 0))
                        ) = 0
                    ')
                    ->orWhere(function ($query) {
                        $query->whereRaw('
                            (ob.on_road_price - 
                             (COALESCE(booking.booking_amount, 0) + 
                              COALESCE(dp.dp_amount, 0) + 
                              COALESCE(dis.net_disbusment, 0) + 
                              COALESCE(ex.total_exchange_amount, 0)) - 
                              (COALESCE(obf_finance.finance_discount, 0) + 
                              COALESCE(ob.way_off, 0) +
                              COALESCE(obf.tl_discount, 0) + 
                              COALESCE(obf.sm_discount, 0) + 
                              COALESCE(obf.gm_discount, 0) + 
                              COALESCE(obf.bh_discount, 0) + 
                              COALESCE(obf.ceo_discount, 0) + 
                              COALESCE(obf.md_discount, 0) + 
                              COALESCE(ob.foc_accessories, 0) + 
                              COALESCE(ob.offer_ib_amount, 0) + 
                              COALESCE(ob.offer_kin_amount, 0))
                            ) != 0
                            AND ob.approval_status = "obf_accountant_accepted"
                        ');
                    });
                });
            }
            
            $data->groupBy('o.id');
            $data->orderBy('o.id', 'desc');
            
            
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($data){
                        $return = '<div class="btn-group">';

                        if(auth()->user()->can('orders-view') && $data->obf_id != null){
                            $return .= '<a href="'.route('order.view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                            <i class="fa fa-eye"></i>
                                        </a> &nbsp;';
                        }   

                        $obf_data = DB::table('obf_finance')->select('finance_required')->where('obf_id',$data->obf_id)->first();

                        if($obf_data)
                        $finance_required=$obf_data->finance_required;
                        $not_coordinator = auth()->user()->roles && auth()->user()->roles[0]['name'] == 'Gatepass Coordinator';

                        if($data->status != 'delivered'){
                                              

                            $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                         <i class="fa fa-bars"></i>
                                     </a> &nbsp;
                                     <ul class="dropdown-menu">';

                                     //|| $data->status == 'cancled'



                            if($data->status == 'waiting' || $data->status == 'deal_generated'){
                                if(auth()->user()->can('orders-cancel')){
                                    $return .='<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="cancled" data-id="' . base64_encode($data->id) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Cancelled</a></li>';
                                }    
                                if($finance_required == 'yes'){
                                    if(auth()->user()->can('orders-finance-approve')){
                                        $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="finance_apporve" data-id="' . base64_encode($data->id) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Finance Apporve</a></li>';
                                    }
                                } else {
                                    if(auth()->user()->can('orders-all-payment-done')){
                                        $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="payment_details(this);" data-status="all_payment_done" data-id="' . base64_encode($data->id) . '"  data-obf-id="' . base64_encode($data->obf_id) . '">All Payment Done</a></li>';
                                    }       
                                }  
                            } elseif ($data->status == 'cancled'){
                                if(auth()->user()->can('orders-cancel')){
                                    $return .='<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="waiting" data-id="' . base64_encode($data->id) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Waiting</a></li>';
                                }        
                            } elseif ($data->status == 'finance_apporve') {
                                if(auth()->user()->can('orders-finance-approve')){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="disbursement" data-id="' . base64_encode($data->id) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Disbursement</a></li>';
                                }
                            } elseif ($data->status == 'disbursement') {
                                if(auth()->user()->can('orders-all-payment-done')){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="payment_details(this);" data-status="all_payment_done" data-id="' . base64_encode($data->id) . '" data-obf-id="' . base64_encode($data->obf_id) . '">All Payment Done</a></li>';
                                }
                            } else if($data->dealer_id != NULL && $data->status == 'all_payment_done') {
                                if(auth()->user()->can('orders-invoice-create')){
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.dealer_invoice_create', ['id' => base64_encode($data->id)]) . '">Create Dealer Invoice</a></li>'; 
                                }
                            } else if($data->dealer_id != NULL && $data->status == 'invoice_create'){
                                if(auth()->user()->can('invoice_print')){
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.invoice_dealer_pdf', ['id' => base64_encode($data->id)]) . '" >Invoice Dealer Print</a></li>';
                                }
                                if(auth()->user()->can('gate-pass-print')){
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.dealer_get_pass_pdf', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '">Dealer Gate Pass Print</a></li>';
                                }    
                            } elseif ($data->status == 'all_payment_done') {
                                if(auth()->user()->can('orders-invoice-create')){
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.invoice_create', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Create Invoice</a></li>'; 
                                }
                            } elseif ($data->status == 'pdi_reject') {
                                if(auth()->user()->can('orders-pdi-approve')){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="pdi_approve" data-id="' . base64_encode($data->id) . '" data-obf-id="' . base64_encode($data->obf_id) . '">PDI Approve</a></li>';
                                }        
                            } elseif ($data->status == 'pdi_approve') {
                                if(auth()->user()->can('orders-invoice-create')){
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.invoice_create', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Invoice Create</a></li>';
                                }    
                                if(auth()->user()->can('gate-pass-print')){
                                    if(($data->number_plate != NULL || $data->number_plate != '') && ($data->insurance_company_name != NULL || $data->insurance_company_name != '') && ($data->insurance_status == 1 || $data->insurance_status == "1")){
                                        $return .= '<li><a class="dropdown-item" href="' . route('order.get_pass_pdf', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Gate Pass Print</a></li>';
                                    }        
                                }
                                if(auth()->user()->can('orders-pdi-approve')){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="pdi_reject" data-id="' . base64_encode($data->id) . '" data-obf-id="' . base64_encode($data->obf_id) . '">PDI Reject</a></li>';
                                }        
                            } elseif ($data->status == 'ready_to_deliver') {
                                if(auth()->user()->can('orders-pdi-approve')){
                                    $return .='<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="delivered" data-id="' . base64_encode($data->id) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Delivered</a></li>';
                                }        
                            }  else if ($data->invoice_date != NULL && $data->invoice_no != NULL) {
                                if(auth()->user()->can('invoice_print')){
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.invoice_pdf', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '" >Invoice Print</a></li>';
                                
                                    $url = route('order.invoice_pdf', ['order_id' => base64_encode($data->id)]);
                                    $message = urlencode("Dear Customer, your car invoice is ready. Download here: ".$url);
                                    $message_kec = urlencode("Dear Sales Person, your customer car invoice is ready. Download here: ".$url);
                                    
                                    if ($data->customer_number) {
                                        $return .= '<li>
                                            <a class="dropdown-item" href="https://wa.me/91'.$data->customer_number.'?text='.$message.'" target="_blank">
                                                Send Customer Invoice
                                            </a>
                                        </li>';
                                    }
                                    
                                    if ($data->sales_person_number) {
                                        $return .= '<li> 
                                            <a class="dropdown-item" href="https://wa.me/91'.$data->sales_person_number.'?text='.$message_kec.'" target="_blank">
                                                Send KEC Invoice
                                            </a>
                                        </li>';
                                    }
                                }    
                                if(auth()->user()->can('orders-edit')){
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.invoice_edit', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '" >Invoice Edit</a></li>';
                                }   
                                if(auth()->user()->can('gate-pass-print')){
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.get_pass_pdf', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Gate Pass Print</a></li>';
                                }
                                if(auth()->user()->can('orders-cancel')){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="invoice_cancel_status(this);" data-status="invoice_cancel" data-id="' . base64_encode($data->id) . '">Invoice Cancel</a></li>';
                                }
                            }  

                            $return .= '</ul>';   

                            $return .= '</div>';

                        } else {
                            if(auth()->user()->can('gate-pass-print')){
                                if ($data->dealer_id !== null && $data->status === 'delivered') {
                                    $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                                    <i class="fa fa-bars"></i>
                                                </a> &nbsp;
                                                <ul class="dropdown-menu">';
                                
                                    // DEALER: Only show Dealer-related options
                                    if (auth()->user()->can('invoice_print')) {
                                        $return .= '<li>
                                                        <a class="dropdown-item" href="' . route('order.invoice_dealer_pdf', [
                                                            'id' => base64_encode($data->id)
                                                        ]) . '">Invoice Dealer Print</a>
                                                    </li>';
                                    }
                                
                                    if (auth()->user()->can('gate-pass-print')) {
                                        $return .= '<li>
                                                        <a class="dropdown-item" href="' . route('order.dealer_get_pass_pdf', [
                                                            'id' => base64_encode($data->obf_id),
                                                            'order_id' => base64_encode($data->id)
                                                        ]) . '">Dealer Gate Pass Print</a>
                                                    </li>';
                                    }
                                
                                    $return .= '</ul>';
                                }
                                elseif ($data->dealer_id === null && $data->status === 'delivered') {
                                    $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                                    <i class="fa fa-bars"></i>
                                                </a> &nbsp;
                                                <ul class="dropdown-menu">';
                                
                                    // CUSTOMER: Show customer-related options
                                    if (auth()->user()->can('invoice_print')) {
                                        $return .= '<li>
                                                        <a class="dropdown-item" href="' . route('order.invoice_pdf', [
                                                            'id' => base64_encode($data->obf_id),
                                                            'order_id' => base64_encode($data->id)
                                                        ]) . '">Invoice Print</a>
                                                    </li>';
                                    }
                                
                                    if (auth()->user()->can('gate-pass-print')) {
                                        $return .= '<li>
                                                        <a class="dropdown-item" href="' . route('order.get_pass_pdf', [
                                                            'id' => base64_encode($data->obf_id),
                                                            'order_id' => base64_encode($data->id)
                                                        ]) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Gate Pass Print</a>
                                                    </li>';
                                    }
                                
                                    $return .= '</ul>'; 
                                }

                                elseif($data->obf_id != NULL){
                                    $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                                     <i class="fa fa-bars"></i>
                                                </a> &nbsp;
                                                <ul class="dropdown-menu">
                                                    <li>
                                                        <a class="dropdown-item" href="' . route('order.get_pass_pdf', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '" data-obf-id="' . base64_encode($data->obf_id) . '">Gate Pass Print</a>
                                                    </li>
                                                </ul>';
                                }
                                
                            } 
                        }


                        if($data->obf_id != null) {
                            if (auth()->user()->can('cash_receipt-generate_gate_pass')) {
                               $return .= '<a title="Add Cash" href="' . route('cash_receipt.create', ['id' => base64_encode($data->obf_id),'page' => 'order']) . '" class="btn btn-default btn-xs">
                                <i class="fas fa-file-medical"></i>
                                </a> &nbsp;';
                            }
                            if (auth()->user()->can('cash_receipt-generate_gate_pass') && $data->obf_status == 'account_accepted') {
                                $return .= '<a title="Generate Cash Receipt" href="' . route('cash_receipt.generate_cash_receipt', ['id' => base64_encode($data->obf_id),'page' => 'order']) . '" class="btn btn-default btn-xs">
                                <i class="fas fa-receipt"></i> 
                                </a> &nbsp;';
                            }   
                        }

                        return $return;
                    })
                    ->editColumn('status', function ($data) {
                        if ($data->status == 'delivered') {
                            return '<span class="badge badge-pill badge-success">Delivered</span>';
                        } else if ($data->status == 'waiting') {
                            return '<span class="badge badge-pill badge-warning">Waiting</span>';
                        } else if ($data->status == 'cancled') {
                            return '<span class="badge badge-pill badge-danger">Cancelled</span>';
                        }else if($data->status == 'direct_delivery'){
                            return '<span class="badge badge-pill badge-success">direct Delivery</span>';
                        }else if($data->status == 'finance_apporve'){
                            return '<span class="badge badge-pill badge-success">Finance Apporve</span>';
                        }else if($data->status == 'disbursement'){
                            return '<span class="badge badge-pill badge-success">Disbursement</span>';
                        }else if($data->status == 'all_payment_done'){
                            return '<span class="badge badge-pill badge-success">All Payment Done</span>';
                        }else if($data->status == 'ready_to_deliver'){
                            return '<span class="badge badge-pill badge-success">Ready to Deliver</span>';
                        }else if($data->status == 'pdi_approve'){
                            return '<span class="badge badge-pill badge-success">PDI Approve</span>';
                        }else if($data->status == 'pdi_reject'){
                            return '<span class="badge badge-pill badge-danger">PDI Reject</span>';
                        }else if($data->status == 'delivered'){
                            return '<span class="badge badge-pill badge-success">Delivered</span>';
                        }elseif ($data->status == 'deal_generated') {
                            return '<span class="badge badge-pill badge-success">Deal Generated</span>';
                        }elseif ($data->status == 'invoice_create'){
                            return '<span class="badge badge-pill badge-success">Invoice Created</span>';
                        }elseif ($data->status == 'invoice_cancel'){
                            return '<span class="badge badge-pill badge-danger">Invoice Cancelled</span>';
                        }else{
                            return '-';
                        }
                    }) 
                    ->editColumn('booking_date', function($data) {
                            return (!empty($data->booking_date)) ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y') : '--';
                        })
                    ->editColumn('received_amount', function ($data) {
                        $finance_dis = ($data->finance_discount ?? 0) + ($data->way_off ?? 0) + ($data->tl_discount ?? 0) + ($data->gm_discount ?? 0) + ($data->sm_discount ?? 0) + ($data->bh_discount ?? 0) + ($data->ceo_discount ?? 0) + ($data->md_discount ?? 0) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                        $net_amt = $data->on_road_price - $finance_dis;
                        return $net_amt;
                    })
                    ->editColumn('due_amount',function($data){
                        // $finance_dis = ($data->finance_discount ?? 0) + ($data->way_off ?? 0) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                        // $book_amt = $data->booking_amount + $data->dp_amount + $data->net_disbusment + $data->total_exchange_amount;
                        // $due_amount = $data->on_road_price - $book_amt - $finance_dis;
                        // return $due_amount;
                        
                        $finance_dis = ($data->finance_discount ?? 0) + ($data->way_off ?? 0) + ($data->tl_discount ?? 0) + ($data->gm_discount ?? 0) + ($data->sm_discount ?? 0) + ($data->bh_discount ?? 0) + ($data->ceo_discount ?? 0) + ($data->md_discount ?? 0) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                        $book_amt = $data->booking_amount + $data->dp_amount + $data->net_disbusment + $data->total_exchange_amount;
                        
                        $total_amt = $book_amt + $finance_dis;
                        $on_road_amount = $data->on_road_price;
                        $due_amount = $on_road_amount - $total_amt;
                        if ($total_amt < $on_road_amount) {
                            $due_amount -= ($data->access_sort_amount ?? 0);
                        } else {
                            $due_amount += ($data->access_sort_amount ?? 0);
                        }
                        return $due_amount;
                    })
                    ->rawColumns(['action','status'])
                    ->filter(function ($query) {
                        if ($dateRange = request()->get('booking_date', false)) {
                                $dates = explode(' to ', $dateRange);
                                if (count($dates) === 2) {
                                    try {
                                        $start = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[0]))->startOfDay()->format('Y-m-d');
                                        $end = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[1]))->endOfDay()->format('Y-m-d');
                                        $query->whereBetween('ob.booking_date', [$start, $end]);
                                    } catch (\Exception $e) {
                                        \Log::error('Invalid date range format for booking_date filter', [
                                            'input' => $dateRange,
                                            'error' => $e->getMessage()
                                        ]);
                                    }
                                }
                            }
                        if (request()->get('branch_name', false)) {
                            $query->where('b.name', "like", "%" . request()->get("branch_name") . "%");
                        }
                        if (request()->get('customer_name', false)) {
                            // $query->where('ob.customer_name', 'like', "%" . request()->get("customer_name") . "%");
                            $query->havingRaw("customer_name LIKE ?", ["%" . request()->get("customer_name") . "%"]);
                        }
                        if (request()->get('kec_name', false)) {
                            $query->whereRaw("CONCAT(us.first_name, ' ', us.last_name) LIKE ?", ["%" . request()->get("kec_name") . "%"]);
                        }
                        if (request()->get('carmodel', false)) {
                            $query->where('car_model.name', 'like', "%" . request()->get("carmodel") . "%");
                        }
                        if (request()->get('carvarient', false)) { 
                            $query->where('car_varient.name', 'like', "%" . request()->get("carvarient") . "%");
                        }
                        if (request()->get('allocation_count', false)) {
                            $query->where('inventory.allocation_count', request()->get("allocation_count"));
                        }
                        if (request()->get('aging_days', false)) {
                            $query->where('inventory.aging_days', request()->get("aging_days"));
                        }
                        if (request()->get('vin_number', false)) {
                            $query->where('o.vin_number', 'like', "%" . request()->get("vin_number") . "%");
                        }
                        if (request()->get('on_road_price', false)) {
                            $query->where('ob.on_road_price', 'like', "%" . request()->get("on_road_price"). "%");
                        }
                        if ($received = request()->get('received_amount')) {
                            $query->havingRaw('CAST(received_amount AS CHAR) LIKE ?', ["%{$received}%"]);
                        }
                        
                        if ($dueAmount = request()->get('due_amount')) {
                            $query->havingRaw("due_amount = ?", [(float) $dueAmount]);
                        }

                        if (request()->get('invoice_no',false)) {
                                $query->where('o.invoice_no', "like", "%".request()->get("invoice_no")."%");
                            }
                        if (request()->get('invoice_date',false)) {
                                $query->where('o.invoice_date', "like", "%".request()->get("invoice_date")."%");
                            }
                        if (request()->get('status', false)) {
                            $query->where('o.status', 'like', "%" . request()->get("status") . "%");
                        }
                    })

                    ->make(true);
        }
        
        return view('order.index');
    }
    /** index */

    /** view */
    public function view(Request $request){
        if(isset($request->id) && $request->id != '' && $request->id != null)
            $id = base64_decode($request->id);
        else
            return redirect()->back()->with('error', 'Something went wrong');

        $path = URL('/uploads/kyc').'/';

        $sales = User::role('sales')->select('id', DB::raw("CONCAT(first_name ,' ', last_name) AS sales_person_name"))->where(['status' => 'active'])->get();
        $product = Product::select('id', 'name', 'veriant')->where(['status' => 'active'])->get();
        $tax_1 = Tax::select('id', 'name', 'percentage')->where(['status' => 'active', 'name' => 'registration_tax'])->first();
        $tax_2 = Tax::select('id', 'name', 'percentage')->where(['status' => 'active', 'name' => 'municipal_tax'])->first();
        $tax_3 = Tax::select('id', 'name', 'percentage')->where(['status' => 'active', 'name' => 'tcs_tax'])->first();
        $accessory = Accessory::select('id', 'name', 'price')->where(['status' => 'active'])->get();
        $extanded_warranty = ExtandWarranty::select('id', 'years', 'amount')->where(['status' => 'active'])->get();
        $fasttag = Fasttag::select('id', 'brand_name', 'amount')->where(['status' => 'active'])->get();
        $branch = Branch::select('id', 'name', 'city')->where(['status' => 'active'])->get();
        $insurance = Insurance::select('id', 'name')->where(['status' => 'active'])->get();
        $finance = Finance::select('finance.id', 'finance.name', 'branches.name AS branch_name', 'branches.id AS branch_id')->leftjoin('branches', 'finance.branch_id', 'branches.id')->where(['finance.status' => 'active'])->get();
        $lead = Lead::select('id', 'name')->where(['status' => 'active'])->get();
        $car_exchange = CarExchange::select('car_exchange.id', 'car_exchange.price', 'cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id', 'cep.id')->get();

        $data = DB::table('orders as o')
                    ->select('o.id', 'o.order_id', 'b.name as branch_name',
                            'obf.id as obf_id', 'obf.sales_person_id', 'obf.temporary_id', 'obf.booking_date', 'obf.customer_name', 'obf.customer_type', 
                            'branches.name AS branch_name', 'branches.id AS branch_id', 'obf.company_name', 'obf.gst', 'obf.address', 'obf.registration',
                            'obf.email', 'obf.pan_number', 'obf.adhar_number', 'obf.licance_number', 'obf.contact_number', 'obf.dob', 'obf.nominee_name',
                            'obf.nominee_reletion', 'obf.nominee_age', 'obf.occupation', 'products.name AS product_name', 'obf.product_id', 'products.veriant',
                            'products.is_applicable_for_mcp', 'obf.ex_showroom_price', 'registration_tax.percentage AS registration_tax',
                            'insurance.name AS insurance', 'obf.insurance_id', 'municipal_tax.percentage AS municipal_tax', 'tcs_tax.percentage AS tcs_tax', 
                            'accessories.name AS accessory_name', 'obf.accessory_id', 'obf.extanded_warranty_id', 'extand_warranties.years AS extand_warranties_years',
                            'extand_warranties.amount AS extand_warranties_amount', 'fasttags.brand_name AS brand_name', 'fasttags.amount AS fasttag_amount', 'fasttags.id AS fasttag_id',
                            'obf.trad_in_value', 'obf.on_road_price', 'obf.on_road_price_word', 'obf.on_road_price_word', 'obf.finance_id', 'finance.name AS finance_name',
                            'finance_branch.name AS finance_branch_name', 'lead.name AS lead_name', 'obf.lead_id', 'obf.booking_amount', 'obf.mode_of_payment', 'obf.status',
                            'obf.created_by', 'obf.updated_by', 'obf.created_at', 'obf.updated_at',
                            'car_model.name AS car_model_name',
                            'car_varient.name AS car_varient_name',
                            'interiorcolor.name AS interiorcolor_name',
                            'exteriorcolor.name AS exteriorcolor_name','obf.other_documents','obf.sub_lead_id',
                            DB::raw("CONCAT(users.first_name, ' ', users.last_name) AS sales_person_name"),
                            'obf.pan_image','obf.adhar_image','obf.licance_image',

                            //'fasttags.id AS fasttag_id',
                            
                            /*DB::Raw("CASE
                                        WHEN ".'pan_image'." != '' THEN CONCAT("."'".$path."'".", ".'pan_image'.")
                                        ELSE CONCAT("."'".$path."'".", 'default.jpg')
                                    END as pan_image"),
                            DB::Raw("CASE
                                        WHEN ".'adhar_image'." != '' THEN CONCAT("."'".$path."'".", ".'adhar_image'.")
                                        ELSE CONCAT("."'".$path."'".", 'default.jpg')
                                    END as adhar_image"),
                            DB::Raw("CASE
                                        WHEN ".'licance_image'." != '' THEN CONCAT("."'".$path."'".", ".'licance_image'.")
                                        ELSE CONCAT("."'".$path."'".", 'default.jpg')
                                    END as licance_image")*/
                        )
                    ->leftjoin('branches as b', 'b.id', 'o.branch_id')
                    ->leftjoin('obf', 'obf.id', 'o.obf_id')
                    ->leftjoin('users', 'obf.sales_person_id', 'users.id')
                    ->leftjoin('branches', 'obf.branch_id', 'branches.id')
                    ->leftjoin('products', 'obf.product_id', 'products.id')
                    ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                    ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                    ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                    ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                    ->leftjoin('taxes AS registration_tax', 'obf.registration_tax_id', 'registration_tax.id')
                    ->leftjoin('taxes AS municipal_tax', 'obf.municipal_tax_id', 'municipal_tax.id')
                    ->leftjoin('taxes AS tcs_tax', 'obf.tcs_tax_id', 'tcs_tax.id')
                    ->leftjoin('insurance', 'obf.insurance_id', 'insurance.id')
                    ->leftjoin('accessories','obf.accessory_id', 'accessories.id')
                    ->leftjoin('extand_warranties', 'obf.extanded_warranty_id', 'extand_warranties.id')
                    ->leftjoin('fasttags', 'obf.fasttag_brand_name', 'fasttags.id')
                    ->leftjoin('finance', 'obf.finance_id', 'finance.id')
                    ->leftjoin('branches AS finance_branch', 'obf.finance_branch_id', 'finance_branch.id')
                    ->leftjoin('lead', 'obf.lead_id', 'lead.id')
                    ->where(['o.id' => $id])
                    ->first();

        return view('order.view')
            ->with(['data' => $data, 'sales' => $sales, 'product' => $product, 'taxOne' => $tax_1, 'taxTwo' => $tax_2, 'taxThree' => $tax_3, 
                    'accessory' => $accessory, 'extanded_warranty' => $extanded_warranty, 'fasttag' => $fasttag, 'branch' => $branch,
                    'insurance' => $insurance, 'car_exchange' => $car_exchange, 'finance' => $finance, 'lead' => $lead]);
    }
    /** view */

    /** change-status */
    public function change_status(Request $request){
            if (!$request->ajax()) { exit('No direct script access allowed'); }
        $id = base64_decode($request->id);
        $obf_id = base64_decode($request->obf_id);
        $data = Order::where(['id' => $id])->first();
        view()->share('id',$id);
        view()->share('obf_id',$obf_id);
        if (!empty($data)) {
            if($request->status == 'pdi_reject'){
                $update = Order::where(['id' => $id])->update(['status' => $request->status, 'pdi_reject_reason' => $request->reason,'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
                $crud = [
                    'module_nm' => 'order',
                    'module_id' => $data->obf_id,
                    'status' => $request->status,
                    'remark' => $request->reason,
                    'created_at' => date('Y-m-d H:i:s'),
                    'created_by' => auth()->user()->id,
                ];
                \DB::table('logs')->insert($crud);
            }elseif ($request->status == 'all_payment_done') {
                $finance_discount = 0;
                $net_disbusment = 0;
                $trade_car_value = 0;
                $on_road_price = 0;
                $way_off = 0;

                $obf_data = OBF::where(['id' => $data->obf_id])->first();
                $exchange_value = exchange::where(['obf_id' => $obf_data->id])->first();
                if($obf_data){  
                    if($exchange_value != '' || $exchange_value != null){
                        $trade_car_value = (int) $exchange_value->total_exchange_amount;    
                    }else{
                        $trade_car_value = '0';    
                    }
                    $on_road_price = (int) $obf_data->on_road_price;
                    $way_off = $obf_data->way_off ?? 0; 
                }

                $finance_data = DB::table('obf_finance')->where(['obf_id' => $data->obf_id])->first();                    
                if($finance_data){                    
                    $finance_discount = (int) $finance_data->finance_discount;                        
                    $net_disbusment = (int) $finance_data->net_disbusment;                        
                }                                     
                $cash_receipt_amount = DB::table('cash_receipt')->where(['obf_id' => $data->obf_id,'status' => 'accepted'])->sum('amount');

                $total_amount_get = $finance_discount + $net_disbusment + $trade_car_value + $cash_receipt_amount + $way_off;
                
                if($total_amount_get >= $on_road_price){
                     $update = Order::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]); 
                     $crud = [
                        'module_nm' => 'order',
                        'module_id' => $data->obf_id,
                        'status' => $request->status,
                        'remark' => NULL,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => auth()->user()->id,
                    ];
                    \DB::table('logs')->insert($crud);
                    
                }else{
                    return response()->json(['code' => 200,'obf_id' => $data->obf_id]);
                }
                
            }else{
                $update = Order::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);    
            }


           
            //notification insert

            $data = OBF::where(['id' => $id])->first();

            $tamplate_name = '';
            if($request->status == 'finance_apporve'){
                $tamplate_name = 'finance_apporve';
            }elseif ($request->status == 'disbursement') {
                $tamplate_name = 'disbursement';
            }elseif ($request->status == 'all_payment_done') {
                $tamplate_name = 'all_payment_done';
            }elseif ($request->status == 'cancled') {
                $tamplate_name = 'Cancelled';
            }elseif ($request->status == 'pdi_approve') {
                $tamplate_name = 'pdi_approve';
            }elseif ($request->status == 'pdi_reject') {
                $tamplate_name = 'pdi_reject';
            }
            

            if($tamplate_name != ''){
                // DB::enableQueryLog();
                $notification_template_master_data = DB::table('notification_template_master')->select('*')->where(['template_name' => $tamplate_name,'status' => 'active'])->first();
                // dd(DB::getQueryLog());

                // var_dump($notification_template_master_data);

                if(!empty($notification_template_master_data)){
                    $customer_name = $data->customer_name ?? null;
                    
                    $car_name_get = '';
                    $product_id = 0;
                    if($data->product_id != null && $data->product_id != ''){
                        $product_id = $data->product_id;
                    }

                    if($product_id != null){
                        $Cardata_get = Product::select('car_model.name as car_name','products.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
                     ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                      ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                      ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                      ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                      ->where('products.status', '=', 'active')
                      ->where('products.id', '=', $product_id)  
                      ->first();
                        
                        if(!empty($Cardata_get)){
                            if(!empty($Cardata_get->car_name) && $Cardata_get->car_name != '' && $Cardata_get->car_name != NULL){
                                $car_name_get .= '('.$Cardata_get->car_name;    
                                $car_name_get .= ' , '.$Cardata_get->varient_name.')';   
                            }
                        }    
                    }

                    $customer_name_with_car_detail = '';     

                    if($customer_name != null){
                        $customer_name_with_car_detail = $customer_name;
                    }   

                    if($customer_name != null){
                        $customer_name_with_car_detail .= ' '.$car_name_get;
                    }                  
                    
                    $data_new = str_replace("[customer_name_with_car_detail]",$customer_name_with_car_detail,$notification_template_master_data->template_data);

                    $notification_data = [
                        'user_id' => auth()->user()->id,
                        'notification_text' => $data_new,
                        'notification_link' => route('obf_approval.view', ['id' => base64_encode($id)]),
                        'created_by' => auth()->user()->id,
                    ];
                    DB::table('notifications')->insert($notification_data);

                    // var_dump($notification_data);
                }
            }
            
            //notification insert
          

            // die('sss--');

             // die('ssss000');
            if ($update) {
                return response()->json(['code' => 200]);
            } else {
                return response()->json(['code' => 201]);
            }
        } else {
            return response()->json(['code' => 201]);
        }
        
    }
    /** change-status */

    /** payment_pending_detail */
    public function payment_pending_detail(Request $request)
    {   
        $order = Order::where('obf_id',$request->obf_id)->first();
        
        $obf_id = base64_decode($request->obf_id);
        view()->share('obf_id',$obf_id);
        $id = base64_decode($request->id);
        view()->share('id',$id);
        $status = $request->status;
        view()->share('status',$status);
        
        $pending_payment_data = [];
        $trade_car_value_get = [];
        if(isset($request->obf_id)){
            $finance_discount = 0;
            $net_disbusment = 0;    
            $trade_car_value = 0;
            $on_road_price = 0;
            $total_discount = 0;

            $obf_data = OBF::where(['id' => $obf_id])->first();
            $trade_car_value_get = Exchange::where(['obf_id' => $obf_id])->first();
            if($obf_data){                    
                if($trade_car_value_get && $trade_car_value_get->total_exchange_amount){
                    $trade_car_value = (int)  $trade_car_value_get->total_exchange_amount;
                } else {
                    $trade_car_value = 0;
                }
                                  
                $on_road_price = (int) $obf_data->on_road_price;                       
            }

            $finance_data = DB::table('obf_finance')->where(['obf_id' => $obf_id])->first();                    
            if($finance_data){                    
                $finance_discount = (int) $finance_data->finance_discount ?? 0; 
                $way_off = (int) $obf_data->way_off ?? 0;
                $tl_discount = (int) $obf_data->tl_discount ?? 0;
                $sm_discount = (int) $obf_data->sm_discount ?? 0;
                $gm_discount = (int) $obf_data->gm_discount ?? 0;
                $bh_discount = (int) $obf_data->bh_discount ?? 0;
                $ceo_discount = (int) $obf_data->ceo_discount ?? 0;
                $md_discount = (int) $obf_data->md_discount ?? 0;
                $foc_accessories = (int) $obf_data->foc_accessories ?? 0;
                $offer_amount = ((int) ($obf_data->offer_ib_amount ?? 0)) + ((int) ($obf_data->offer_kin_amount ?? 0)); 
                $total_discount = $finance_discount + $way_off + $tl_discount + $sm_discount + $gm_discount + $bh_discount + $ceo_discount + $md_discount + $foc_accessories + $offer_amount; 
                $net_disbusment = (int) $finance_data->net_disbusment;
            }                                     
            $cash_receipt_amount = DB::table('cash_receipt')->where(['obf_id' => $obf_id,'status' => 'accepted'])->sum('amount');
            
            $total_amount_get = $total_discount + ($trade_car_value ?? '0') + $cash_receipt_amount;

            if($total_amount_get >= $on_road_price){
                //payment done
                $pending_payment = $on_road_price - $total_amount_get;
                $pending_payment_data = array(
                    'finance_discount' => $total_discount, 
                    'net_disbusment' => $net_disbusment, 
                    'trade_car_value' => ($trade_car_value ?? '0'), 
                    'cash_receipt_amount' => $cash_receipt_amount, 
                    'on_road_price' => $on_road_price, 
                    'total_amount_get' => $total_amount_get,
                    'pending_payment' => $pending_payment,
                    'payment_status' => 1
                );
            }else{
                //pending payment
                $pending_payment = $on_road_price - $total_amount_get;

                $pending_payment_data = array(
                    'finance_discount' => $total_discount, 
                    'net_disbusment' => $net_disbusment, 
                    'trade_car_value' => ($trade_car_value ?? '0'), 
                    'cash_receipt_amount' => $cash_receipt_amount, 
                    'on_road_price' => $on_road_price, 
                    'total_amount_get' => $total_amount_get,
                    'pending_payment' => $pending_payment,
                    'payment_status' => 0
                );                    
            }
            $obfRecords = OBF::from('obf as o')
                ->select(
                    'Team_master.team_name',
                    'o.customer_name',
                    'branches.name AS branch_name',
                    DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name")
                )
                ->leftJoin('branches', 'o.branch_id', '=', 'branches.id')
                ->leftJoin('users as us', 'us.id', '=', 'o.sales_person_id')
                ->leftJoin('Team_master', 'Team_master.id', '=', 'us.team_name')
                ->where('o.id', $obf_id)
                ->first();
            
        }

        return view('order.payment_pending_detail')->with([
            'pending_payment_data' => $pending_payment_data,
            'id' => $id,
            'obf_id' => $obf_id,
            'status' => $status,
            'obfRecords' => $obfRecords
        ]);
        // return view('order.payment_pending_detail')->with(['pending_payment_data' => $pending_payment_data]);
    }
    /** payment_pending_detail */
    
    /** Update All Payment Status Done */
    public function update_payment_status(Request $request){
        $id = $request->id;
        $obf_id = $request->obf_id;
        $status = $request->status;
    
        $update = Order::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]); 
        
        if ($update) {
            $crud = [
                'module_nm' => 'order',
                'module_id' => $obf_id,
                'status' => $request->status,
                'remark' => $request->remark,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
            ];
            \DB::table('logs')->insert($crud);
            return response()->json(['code' => 200]);
        } else {
            return response()->json(['code' => 201]);
        }
    }

    /** Create */
    public function invoice_create(Request $request)
    {
        $obf_id = base64_decode($request->id);
        $order_id = base64_decode($request->order_id);

        $data = OBF::where(['id' => $obf_id])->first();
        $deal_data = MakeDeal::where(['obf_id'=>$data->id])->first();
        if($data->approval_status == 'obf_gm_accepted' || $data->approval_status == 'obf_accountant_accepted'){
            if($data->status == 'deal_generated'){
                if ($data) {
                    $finance_name = '';
                    $finance_discount = '';
                    $branch_id = $data->branch->id ?? null;
                    $obf_finance = [];
                    $obf_finance_data = DB::table('obf_finance')->where(['obf_id' => $obf_id])->first();
                    if($obf_finance_data){                    
                        $obf_finance = $obf_finance_data;
                        $finance_discount = $obf_finance_data->finance_discount;
                        if($obf_finance->finance_name != NULL && $obf_finance->finance_name > 0){
                            $finance_data = DB::table('finance')->where(['id' => $obf_finance->finance_name])->first();
                            $finance_name = $finance_data->name;
                        }
                    }
                    $current_date = Carbon::now()->format('d-m-Y');
        
                    
                    $product_name_get = '';
                    $hsn_code = '';
                    $tex_master_gst = 1;
                    $tex_master_compensation_cess = 1;
        
                    $product_data_get = Product::select('products.*','car_model.name as car_name', 'exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color', 'car_varient.name as varient_name' , 'car_varient.hsn_code as hsn_code')
                        ->leftJoin('car_model','car_model.id','=','products.car_model')
                        ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
                        ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
                        ->leftJoin('car_varient','car_varient.id','=','products.veriant')
                        ->where('products.status', 'active')
                        ->where('products.id',  $data->product_id)
                        ->first(); 
        
                       /* var_dump($product_data_get->car_name);
                        die('st');*/
        
                    if($product_data_get){                    
                       $product_name_get = 'Price of One  '.$product_data_get->car_name.' ** '.$product_data_get->varient_name.' '.$product_data_get->exterior_color.' '.$product_data_get->interior_color;
        
                       $hsn_code = $product_data_get->hsn_code;
                        
                       $veriant_id = 0;
                       if($product_data_get->veriant != NULL)
                           $veriant_id = $product_data_get->veriant;
                        
                       $Carvarient_data = Carvarient::where(['id' => $veriant_id,'status' => 'active'])->first();
        
                       $tex_master_id = 0;
                       if($Carvarient_data)
                           $tex_master_id = $Carvarient_data->tex_master_id;
        
                       if($tex_master_id > 0){
                           $Texmaster_data = Texmaster::where(['id' => $tex_master_id,'status' => 'active'])->first();  
                           if($Texmaster_data->gst != null) 
                                $tex_master_gst = $Texmaster_data->gst;
                           if($Texmaster_data->compensation_cess != null) 
                           $tex_master_compensation_cess = $Texmaster_data->compensation_cess;                       
                       }
        
                    }
        
                    $inventory_data = [];
                    $inventory_get = DB::table('inventory')->where('id',  $data->inventory_id)->first();
                    if($inventory_get){                    
                       $inventory_data = $inventory_get;
                    }
        
                    $orders_data = [];
                    $orders_data_get = DB::table('orders')->where('id',  $order_id)->first();
                    if($orders_data_get){                    
                       $orders_data = $orders_data_get;
                    }
                    // $invoice_prefix = (in_array($branch_id, [1, 2, 4])) ? 'SALLP/2425/00' : 'SIBAPL/2425/00';
                    $invoice_prefix = (in_array($branch_id, [1, 2, 4, 6])) ? 'SIBAPL/2526/' : 'SALLP/2526/';
            
                    // Fetch the last created invoice number with the same prefix
                    $last_invoice = Order::where('invoice_no', 'like', $invoice_prefix . '%')
                                         ->orderBy('invoice_no', 'desc')
                                         ->first();
                    
                    // Extract the last incremented number or start from 1
                    if ($last_invoice) {
                        $last_number = (int) substr($last_invoice->invoice_no, -2); // Get the last 2 digits
                        $new_number = str_pad($last_number + 1, 2, '0', STR_PAD_LEFT); // Increment and pad with zero
                    } else {
                        $new_number = '01'; // Start from 01 if no previous invoice exists
                    }
                    
                    // Generate the new invoice number
                    $invoice_no = $invoice_prefix . $new_number;
                    
                    $price_list_name = DB::table('pricelist_master')->select('basic','price_list_name','gst_percentage','gst_amount','cess_percentage','cess_amount')->where('id',  $data->pricelist_id)->first();

                    $make_deal_gst_amt = $deal_data->gst_tax_deal; 
                    $make_deal_gst_percentage = $price_list_name->gst_percentage;
                    
        
                    return view('order.invoice_create')->with(['inventory_data' => $inventory_data,'product_name_get' => $product_name_get,'current_date' => $current_date,'finance_name' => $finance_name,'finance_discount' => $finance_discount,'hsn_code' => $hsn_code,'orders_data' => $orders_data,'data' => $data,'order_id' => $order_id,'tex_master_gst' => $tex_master_gst,'tex_master_compensation_cess' => $tex_master_compensation_cess, 'invoice_prefix' => $invoice_no,'deal_data'=>$deal_data,'make_deal_gst_amt'=>$make_deal_gst_amt,'make_deal_gst_percentage'=>$make_deal_gst_percentage,'data'=>$data]);
                } else {
                    return view('order')->with('error', 'No record found!');
                }
                        
            } else {
                return redirect()->route('order')->with('error', "Make Deal Not Created...");
            }    
        } else {
            return redirect()->route('order')->with('error', "General manager's approval pending for this OBF...");
        }  
    }
    /** Create */

    /** edit */
    public function invoice_edit(Request $request)
    {
        $obf_id = base64_decode($request->id);
        $order_id = base64_decode($request->order_id);

        $orders_data = [];
        $orders_data_get = DB::table('orders')->where('id',  $order_id)->first();
        if($orders_data_get){                    
           $orders_data = $orders_data_get;
        }

        $tex_master_gst = 1;
        $tex_master_compensation_cess = 1;

        $data = OBF::where(['id' => $obf_id])->first();
        
        if($data){
            $product_data_get = Product::select('products.*')
             ->where('products.status', 'active')
             ->where('products.id',  $data->product_id)
             ->first();
            $veriant_id = 0;
            if($product_data_get->veriant != NULL)
                $veriant_id = $product_data_get->veriant;
             
            $Carvarient_data = Carvarient::where(['id' => $veriant_id,'status' => 'active'])->first();

            $tex_master_id = 0;
            if($Carvarient_data)
                $tex_master_id = $Carvarient_data->tex_master_id;

            if($tex_master_id > 0){
                $Texmaster_data = Texmaster::where(['id' => $tex_master_id,'status' => 'active'])->first();  
                if($Texmaster_data->gst != null) 
                     $tex_master_gst = $Texmaster_data->gst;
                if($Texmaster_data->compensation_cess != null) 
                $tex_master_compensation_cess = $Texmaster_data->compensation_cess;                       
            }
        }
        

        if ($orders_data) {
            return view('order.invoice_edit')->with(['orders_data' => $orders_data,'tex_master_gst' => $tex_master_gst,'tex_master_compensation_cess' => $tex_master_compensation_cess, 'data'=>$data]);
        } else {
            return view('order.invoice_edit')->with('error', 'No record found!');
        }
    }
    /** edit */

    /** insert */
    public function insert(Request $request){
        
        if($request->ajax()) { return true; }
        
        $id = $request->order_id;
        $obf_id = $request->id;
        
        // $status = $request->payment_done_status;
        
        $crud = [
            'dealer_gst' => $request->dealer_gst,
            'dealer_pan_number' => $request->dealer_pan_number,
            'bill_to' => $request->bill_to,
            'address' => $request->address,
            'ship_to' => $request->ship_to,
            'finance_name' => $request->finance_name,
            'customer_gst' => $request->customer_gst ?? null,
            'customer_id' => $request->customer_id,
            'invoice_no' => $request->invoice_no,
            'phone_no' => $request->phone_no,
            'pan_number' => $request->pan_number,
            'place_of_supply' => $request->place_of_supply,
            'product_name' => $request->product_name,
            'on_road_price' => $request->on_road_price,
            'discount' => $request->discount,
            'selling_price' => $request->selling_price,
            'cgst' => $request->cgst ?? null,
            'sgst' => $request->sgst ?? null,
            'igst' => $request->igst ?? null,
            'compensation_cess' => $request->compensation_cess,
            'total' => $request->total,
            'tcs_tax' => $request->tcs_tax,
            'grand_total' => $request->grand_total,
            'vin_number' => $request->vin_number,
            'chassis_number' => $request->chassis_number,
            'engine_number' => $request->engine_number,
            'key_number' => $request->key_number,
            'hsn_code' => $request->hsn_code,
            'status' => $request->status,
            'updated_by' => auth()->user()->id,
            'updated_at' => date('Y-m-d H:i:s')
        ];
            
        if($request->invoice_date != '' && $request->invoice_date != NULL){
            $crud['invoice_date'] = date("Y-m-d",strtotime($request->invoice_date));    
        }
        $inventory_data_get = OBF::where('id',$obf_id)->first();
        $update = Order::where(['id' => $id])->update($crud);
        $logs_crud = [
            'module_nm' => 'order',
            'module_id' => $obf_id,
            'status' => $request->status,
            'remark' => NULL,
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
        ];
        \DB::table('logs')->insert($logs_crud);
        
        $update_status = Inventory::where('id',$inventory_data_get->inventory_id)->update(['status'=>'invoice_create']);
        if ($update){
           return redirect()->route('order');
        }else{
            return redirect()->back()->with(['error'=>'Faild Invoice Create!'])->withInput();
        }
    }
    /** insert */

    /** update */
    public function update(Request $request){
        if($request->ajax()) { return true; }

        $id = $request->order_id;
        $obf_id = $request->id;
        
        $crud = [                
            'bill_to' => $request->bill_to,
            'address' => $request->address,
            'ship_to' => $request->ship_to,
            'remark'  => $request->remark,
            'updated_by' => auth()->user()->id,
            'updated_at' => date('Y-m-d H:i:s')
        ];
        // \DB::enableQueryLog(); 
        $update = Order::where(['id' => $id])->update($crud);
        $logs_crud = [
            'module_nm' => 'order',
            'module_id' => $obf_id,
            'status' => $request->status,
            'remark' => $request->remark,
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
        ];
        \DB::table('logs')->insert($logs_crud);

        if ($update){                
            // $this->invoice_pdf($request);
            return redirect()->route('order.invoice_pdf', ['id' => base64_encode($obf_id),'order_id' => base64_encode($id)]);
        }else{
            return redirect()->back()->with(['error'=>'Faild Invoice Create!'])->withInput();
        }
    }
    /** update */


    // this function directly downloads the PDF. 
    public function pdf_sample()
    {
        // die('stp[');


        ini_set('memory_limit', '2048M');


        $html_content = '<h1>Generate a PDF using TCPDF in laravel </h1>
         <h4>by<br/>Learn Infinity</h4>';
      
 
        PDF::SetTitle('Sample PDF');
        PDF::AddPage();

       PDF::writeHTML($html_content, true, false, true, false, '');

        /*$guest_view = \View::make('pdf/guest_pdf', ['site_details'=>$site_details]);

        PDF::writeHTML($html_content, true, false, true, false, '');

        /*$guest_view = \View::make('guest_pdf', ['site_details'=>$site_details]);

        $guest_html = $guest_view->render();
        $heading_title = "Guest Post";
        PDF::AddPage('P','A4');
        PDF::SetFont('dejavusans', '', 10);
        PDF::SetTextColor(0, 0, 0);
        PDF::setCellPaddings(0, 1.5, 0, 1.5);
        PDF::SetLeftMargin(7);
        PDF::writeHTML($guest_html, true, false, true, false, '');*/
        
 
        //PDF::Output(uniqid().'_SamplePDF.pdf', 'D');
        PDF::Output(uniqid().'_SamplePDF.pdf');
        
    }

    public function invoice_pdf(Request $request)
    {       
        /*$path = public_path('assets\img\kia.jpg');

        var_dump($path);
        die('stp');*/

        ini_set('memory_limit', '2048M');

        $obf_id = base64_decode($request->id);
        $order_id = base64_decode($request->order_id);

        $orders_data = [];
        $orders_data_get = DB::table('orders')->where('id',  $order_id)->first();
        if($orders_data_get){                    
           $orders_data = $orders_data_get;
        }
        
        $data = OBF::select('obf.id','obf.sales_person_id',

        DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type','obf.customer_type_new' ,'obf.booking_date','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' , 'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id','products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'obf.fasttag_brand_name AS fasttag_brand_name','registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount_new' ,'fasttags.id AS fasttag_id','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','allocation.tentetive_delivery_date','Team_master.team_name','obf.other_accesssories_prise','obf.ship_to_customer_name','obf.ship_to_address'

        ,'obf.state_id','obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status', 'obf.gst',

        'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.pricelist_id','obf.registration_tax_id','obf.municipal_tax_id','obf.municipal_tax_applicable','obf.tcs_tax_id','obf.nominee_dob','convinience_program',

        'obf.step1_remarks','obf.step3_remarks','obf.step4_remarks','obf.step5_remarks','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id',

        'obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.rsa_master_obf',

        'car_model.name AS car_model_name','car_varient.name AS car_varient_name','interiorcolor.name AS interiorcolor_name','exteriorcolor.name AS exteriorcolor_name','inventory.key_number','inventory.engine_number','inventory.chassis_number','inventory.vin_number', 'obf_insurance.company_name AS insurance_company_name','obf_insurance.ncb_amount','obf.offer_ib_amount','obf.offer_kin_amount','obf.offer_amount','inventory.purchase_price','inventory.aging_days','inventory.remark',
        
        'make_deal.obf_id','make_deal.purchase_gst_tax_deal','make_deal.final_deal_amt','make_deal.deal_amt','make_deal.gst_tax_deal','make_deal.cess_tax_deal','make_deal.tcs_tax_deal','make_deal.municipal_tax_deal','make_deal.rto_deal','make_deal.insurance_deal','make_deal.created_by')

        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
        ->leftjoin('products', 'obf.product_id', 'products.id')
        ->leftjoin('car_model', 'car_model.id', 'products.car_model')
        ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
        ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
        ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
        ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
        ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
        ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
        ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
        ->leftjoin('allocation' ,'obf.id' ,'allocation.obf_id')
        ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
        ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
        ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
        ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
        ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
        ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
        ->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')
        ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
        ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
        ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
        ->leftjoin('Team_master','Team_master.id','users.team_name')
        ->leftjoin('make_deal','obf.id','make_deal.obf_id')
        ->where(['obf.id' => $obf_id])->first(); 

        $branch = Branch::select('start_value1', 'end_value1', 'tax_percentage1', 'start_value2', 'end_value2', 'tax_percentage2')->where(['status' => 'active','id' => $data->branch_id])->first();
       
        $price_list_name = DB::table('pricelist_master')->select('basic','price_list_name','gst_percentage','gst_amount','cess_percentage','cess_amount')->where('id',  $data->pricelist_id)->first();

        $rto_data = DB::table('rto_master')->select('rto_type', 'rto_tax_individual', 'rto_tax_company', 'totali_individual_charges','totalcharges')->Where('rto_type', 'like', $data->customer_type . '%')->orderBy('id', 'DESC')->first();

        $accessory_sum = 0;

        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){
            $accessory_id_arr = explode(' ,', $data->accessory_id);
            if(!empty($accessory_id_arr)){
                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');           
            }
        }
        
        $order_branch_nm = Branch::select('name', 'address','manager_contact_number')
        ->where('status', 'active')
        ->where('id', $orders_data->branch_id)
        ->first();
    
       $img = DB::table('global_configuration')->select('*')->where('status','active')->where('branch_id',$data->branch_id)->first();
       $img1 = $img->invoice_logo1 ?? '';
       $img2 = $img->invoice_logo2 ?? '';
       
        $path1 = public_path('uploads/global_configuration/invoice_logo_one/'.$img1);
        $path2 = public_path('uploads/global_configuration/invoice_logo_two/'.$img2);

        PDF::SetAuthor('Nicola Asuni');
        PDF::SetTitle('Invoice');
        PDF::SetSubject('Invoice');
        PDF::setImageScale(PDF_IMAGE_SCALE_RATIO);
        PDF::AddPage();
        /*PDF::Image(public_path('uploads/global_configuration/invoice_logo_two/'.$img2), 18, 12, 45, 20, 'PNG');
        PDF::Image(public_path('uploads/global_configuration/invoice_logo_one/'.$img1), 155, 16, 40, 10, 'PNG');*/
        if (!empty($img2) && file_exists($path2) && is_file($path2)) {
            PDF::Image($path2, 18, 12, 45, 20, 'PNG');
        }
        
        if (!empty($img1) && file_exists($path1) && is_file($path1)) {
            PDF::Image($path1, 155, 16, 40, 10, 'PNG');
        }
        PDF::SetFont('freeserif', 'B', 10);
        PDF::SetTextColor(50, 50, 50);
        $content = $order_branch_nm->name ?? '';
        PDF::SetXY(0, 12);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        PDF::SetFont('freeserif', ' ', 8);
        PDF::SetTextColor(50, 50, 50);
        $content = wordwrap($order_branch_nm->address, 45, "\n", true);
        PDF::SetXY(0, 16);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        $content = "Ph.: " . ($order_branch_nm->manager_contact_number ?? '');
        PDF::SetXY(0, 28);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        $content = "GST No./PAN No.: ".$orders_data->dealer_gst."/".$orders_data->dealer_pan_number;
        PDF::SetXY(0, 31);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        $content = "IRN No.:";
        PDF::SetXY(0, 34);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        PDF::SetXY(10, 39);

        $customer_gst_label = '';
        $customer_gst = '';
        $customer_gst_dot = '';

        if($orders_data->customer_gst != NULL){
            $customer_gst_label = 'Customer GST No.';
            $customer_gst = $orders_data->customer_gst;
            $customer_gst_dot = ':';            

        }
        
        $logoFile = $img1 = $img->invoice_logo1 ?? '';
        $watermarkPath = public_path('uploads/global_configuration/gatepass_logo_one/' . $logoFile);
        
        if (!empty($logoFile) && file_exists($watermarkPath)) {
            PDF::SetAlpha(0.08);
        
            // Image size
            $imageWidth = 50;
            $imageHeight = 20;
            
            // Page size
            $pageWidth = PDF::getPageWidth();
            $pageHeight = PDF::getPageHeight();
            
            // Center of the page
            $xCenter = $pageWidth / 2;
            $yCenter = $pageHeight / 2;
        
            // Offsets
            $offsetX = 40;
            $offsetY = 30;
        
            // Adjusted to be more to the left and higher vertically
            $firstX = $xCenter - $imageWidth - 40; 
            $firstY = $yCenter - ($imageHeight / 2) - 60; 
        
            // 1st
            PDF::Image($watermarkPath, $firstX, $firstY, $imageWidth, $imageHeight, '', '', '', false, 100, '', false, false, 0);
        
            // 2nd
            $secondX = $firstX + $offsetX;
            $secondY = $firstY + $offsetY;
            PDF::Image($watermarkPath, $secondX, $secondY, $imageWidth, $imageHeight, '', '', '', false, 100, '', false, false, 0);
        
            // 3rd
            $thirdX = $secondX + $offsetX;
            $thirdY = $secondY + $offsetY;
            PDF::Image($watermarkPath, $thirdX, $thirdY, $imageWidth, $imageHeight, '', '', '', false, 100, '', false, false, 0);
        
            // 4th
            $fourthX = $thirdX + $offsetX;
            $fourthY = $thirdY + $offsetY;
            PDF::Image($watermarkPath, $fourthX, $fourthY, $imageWidth, $imageHeight, '', '', '', false, 100, '', false, false, 0);
        
            PDF::SetAlpha(1); 
        }

        // dd($logoFile);
        $tbl = '<table cellspacing="0" cellpadding="1" border="0">
                <tr>
                    <th colspan="6" align="center" style="border-top:1px solid black;border-bottom:1px solid black;font-size:14px;"><b>Vehicle Tax Invoice</b></th>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;"><b><u>Bill To</u></b></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:300px;font-size:12px;"></td>
                    <td style="width:100px;font-size:12px;">Customer Id</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:280px;font-size:12px;">'.$orders_data->customer_id.'</td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;">Customer Name</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">'.$data->customer_name.'</td>
                    
                    <td style="width:100px;font-size:12px;">Invoice No</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">'.$orders_data->invoice_no.'</td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;">Address</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">'.$data->registration.'</td>
                    <td style="width:100px;font-size:12px;">Invoice Date</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:280px;font-size:12px;">'.date("d/m/Y",strtotime($orders_data->invoice_date)).'</td> 
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;">GST / PAN No</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">' . ($data->gst ?? 'N/A') . ' / ' . ($orders_data->pan_number ?? 'N/A') . '</td>
                    <td style="width:100px;font-size:12px;">Phone No</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:280px;font-size:12px;">'.$data->contact_number.'</td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;"><b><u>Ship To</u></b></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:300px;font-size:12px;"></td>
                    <td style="width:100px;font-size:12px;">Place of Supply</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:280px;font-size:12px;">GUJARAT</td>
                </tr>
               <tr>
                    <td style="width:120px;font-size:12px;">Customer Name</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">'.$data->ship_to_customer_name.'</td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;">Address</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">'.$data->ship_to_address.'</td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;">Hypo. by</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">'.$orders_data->finance_name.'</td>
                </tr>
            </table>';

        PDF::writeHTML($tbl, true, false, false, false, '');

         PDF::SetXY(10, 100);
         
         
        if($data->state_id == 7 || $data->state_id == 'Gujarat'){
            $make_deal_gst_percentage = $price_list_name->gst_percentage / 2;    
            $make_deal_gst_amt = $data->gst_tax_deal / 2;
        } else {
            $make_deal_gst_percentage = $price_list_name->gst_percentage;    
            $make_deal_gst_amt = $data->gst_tax_deal;
        }
        
        $total_before_tcs = $data->deal_amt + $data->gst_tax_deal + $data->cess_tax_deal;
        $total_after_tcs = $total_before_tcs + $data->tcs_tax_deal;
        
        $tbl = '<table cellspacing="0" cellpadding="5" border="0" nobr="true">
                <tr>
                    <th align="center" colspan="2" style="width:450px;border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:14px;"><b>PARTICULARS</b></th>
                    <th style="border-top:1px solid black;border-bottom:1px solid black;text-align: center;font-size:14px;"><b>&nbsp;&nbsp;&nbsp; AMOUNT(Rs)</b></th>

                </tr>
                <tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">1) '.$orders_data->product_name.'</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$data->deal_amt.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">3) Net Selling Price</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$data->deal_amt.'</td>
                </tr>';
                if($data->state_id == 7 || $data->state_id == 'Gujarat'){
                    $tbl .= '<tr>
                        <td colspan="2" style="font-size:12px;border-right:1px solid black;">4.1) CGST &nbsp; '.$make_deal_gst_percentage.' %</td>
                        <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$make_deal_gst_amt.'</td>
                    </tr>
                    <tr>
                        <td colspan="2" style="font-size:12px;border-right:1px solid black;">4.2) SGST &nbsp; '.$make_deal_gst_percentage.' %</td>
                        <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$make_deal_gst_amt.'</td>
                    </tr>';
                }else{ 
                    $tbl .= '<tr>
                        <td colspan="2" style="font-size:12px;border-right:1px solid black;">4.2) IGST &nbsp; '.$make_deal_gst_percentage.' %</td>
                        <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$make_deal_gst_amt.'</td>
                    </tr>';
                }
                $tbl .= '<tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">4.3) Compensation Cess &nbsp; '.$price_list_name->cess_percentage.' %</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$data->cess_tax_deal.'</td>
                </tr>                 
                <tr>
                    <td colspan="2" style="border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:14px;"><b>TOTAL</b></td>
                    <td style="text-align: center;border-top:1px solid black;border-bottom:1px solid black;font-size:14px;">&nbsp;&nbsp;&nbsp; '.$total_before_tcs.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:14px;"><b>TCS @1%</b></td>
                    <td style="text-align: center;border-top:1px solid black;border-bottom:1px solid black;font-size:14px;">&nbsp;&nbsp;&nbsp; '.$data->tcs_tax_deal.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:14px;"><b>GRAND TOTAL</b></td>
                    <td style="text-align: center;border-top:1px solid black;border-bottom:1px solid black;font-size:14px;">&nbsp;&nbsp;&nbsp; '.$total_after_tcs.'</td>
                </tr>
            </table>';

            /*<tr>
                    <td colspan="2"  style="font-size:12px;border-right:1px solid black;"></td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; 0.00</td>
                </tr>*/

        PDF::writeHTML($tbl, true, false, false, false, '');
        PDF::SetFont('freeserif', '', 10);
        $content = "Vehicle Particulars";
        PDF::SetXY(15, 180);
        PDF::Cell(0, 0, $content);
        
        PDF::SetXY(10, 185);

        $tbl = '<table cellspacing="0" cellpadding="4" border="0" nobr="true">
                <tr>
                    <td style="width:165px;text-align: center;border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:12px;border-left:1px solid black;">Vin No./Chassis No.<br />'.$orders_data->vin_number.'</td>
                    
                    <td style="width:120px;text-align: center;border-top:1px solid black;border-right:1px solid black;border-bottom:1px solid black;font-size:12px;">Engine No.<br />'.$orders_data->engine_number.'</td>
                    <td style="width:110px;text-align: center;border-top:1px solid black;border-right:1px solid black;border-bottom:1px solid black;font-size:12px;">Key No.<br />'.$orders_data->key_number.'</td>
                    <td style="width:110px;text-align: center;border-top:1px solid black;border-right:1px solid black;border-bottom:1px solid black;font-size:12px;">HSN No<br />'.$orders_data->hsn_code.'</td>
                </tr>
                
        </table>';

        PDF::writeHTML($tbl, true, false, false, false, '');

        PDF::SetFont('freeserif', '', 8);
        $content = "“Terms & condition apply “";
        PDF::SetXY(15, 199);
        PDF::Cell(0, 0, $content);

        PDF::SetFont('freeserif', '', 12);
        $content = 'For ' . ($order_branch_nm->name ?? '');
        PDF::SetXY(125, 225);
        PDF::Cell(0, 0, $content);

        PDF::SetXY(10, 255);

        $tbl = '<table cellspacing="0" cellpadding="8" border="0" nobr="true">
                <tr>
                    <td style="border-top:1px solid black;font-size:14px;">Signature of Customer</td>
                    <td></td>
                    <td style="border-top:1px solid black;font-size:14px;">Authorised Signatory</td>
                </tr>
                
        </table>';
        
        PDF::writeHTML($tbl, true, false, false, false, '');
        
        $invoice_no = preg_replace('/[^\w\- ]/', '', $orders_data->invoice_no); // allows letters, numbers, underscores, hyphens and spaces
        $file_name = $data->customer_name . " " . $invoice_no . " " . $orders_data->invoice_date;

        PDF::Output($file_name. '.pdf', 'I');
    }
    
    
    public function invoice_dealer_pdf(Request $request)
    {       
        ini_set('memory_limit', '2048M');
        
        $order_id = base64_decode($request->id);

        $orders_data = [];
        $orders_data_get = DB::table('orders')->where('id',  $order_id)->first();
        if($orders_data_get){                    
           $orders_data = $orders_data_get;
        }
        
        $inventory = Inventory::where('id',$orders_data->inventory_id)->first();
        $from_branch_nm = Branch::where('id',$inventory->branch_id)->first();
        
        $gst_pan = (in_array($inventory->branch_id, [1, 2, 4, 6])) ? '"GST No./PAN No.: 24ABACS4515J1ZH/ABACS4515J"' : '"GST No./PAN No.: 24AEXFS9331R1ZU/AEXFS9331R"';
        
        $img = DB::table('global_configuration')->select('*')->where('status','active')->first();
        $img1 = $img->invoice_logo1 ?? '';
        $img2 = $img->invoice_logo2 ?? '';


        PDF::SetAuthor('Nicola Asuni');
        PDF::SetTitle('Invoice');
        PDF::SetSubject('Invoice');
        PDF::setImageScale(PDF_IMAGE_SCALE_RATIO);
        PDF::AddPage();
        PDF::Image(public_path('uploads/global_configuration/invoice_logo_two/'.$img2), 18, 12, 45, 20, 'PNG');
        PDF::Image(public_path('uploads/global_configuration/invoice_logo_one/'.$img1), 155, 16, 40, 10, 'PNG');
        PDF::SetFont('freeserif', '', 8);
        PDF::SetTextColor(50, 50, 50);
        $content = $from_branch_nm->name;
        PDF::SetXY(0, 12);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        PDF::SetFont('freeserif', ' ', 8);
        PDF::SetTextColor(50, 50, 50);
        $content = wordwrap($from_branch_nm->address, 45, "\n", true);
        PDF::SetXY(0, 16);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        $content = "Ph.: " . ($from_branch_nm->contact_number ?? '');
        PDF::SetXY(0, 28);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        $content = $gst_pan;
        PDF::SetXY(0, 31);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        $content = "IRN No.:";
        PDF::SetXY(0, 34);
        PDF::MultiCell(0, 0, $content, 0, 'C');
        PDF::SetXY(10, 39);
        
        $logoFile = $img1 = $img->invoice_logo1 ?? '';
        $watermarkPath = public_path('uploads/global_configuration/gatepass_logo_one/' . $logoFile);
        
        if (!empty($logoFile) && file_exists($watermarkPath)) {
            PDF::SetAlpha(0.08);
        
            // Image size
            $imageWidth = 50;
            $imageHeight = 20;
            
            // Page size
            $pageWidth = PDF::getPageWidth();
            $pageHeight = PDF::getPageHeight();
            
            // Center of the page
            $xCenter = $pageWidth / 2;
            $yCenter = $pageHeight / 2;
        
            // Offsets
            $offsetX = 40;
            $offsetY = 30;
        
            // Adjusted to be more to the left and higher vertically
            $firstX = $xCenter - $imageWidth - 40; 
            $firstY = $yCenter - ($imageHeight / 2) - 60; 
        
            // 1st
            PDF::Image($watermarkPath, $firstX, $firstY, $imageWidth, $imageHeight, '', '', '', false, 100, '', false, false, 0);
        
            // 2nd
            $secondX = $firstX + $offsetX;
            $secondY = $firstY + $offsetY;
            PDF::Image($watermarkPath, $secondX, $secondY, $imageWidth, $imageHeight, '', '', '', false, 100, '', false, false, 0);
        
            // 3rd
            $thirdX = $secondX + $offsetX;
            $thirdY = $secondY + $offsetY;
            PDF::Image($watermarkPath, $thirdX, $thirdY, $imageWidth, $imageHeight, '', '', '', false, 100, '', false, false, 0);
        
            // 4th
            $fourthX = $thirdX + $offsetX;
            $fourthY = $thirdY + $offsetY;
            PDF::Image($watermarkPath, $fourthX, $fourthY, $imageWidth, $imageHeight, '', '', '', false, 100, '', false, false, 0);
        
            PDF::SetAlpha(1); 
        }
        $tbl = '<table cellspacing="0" cellpadding="1" border="0">
                <tr>
                    <th colspan="6" align="center" style="border-top:1px solid black;border-bottom:1px solid black;font-size:14px;"><b>Dealer Vehicle Tax Invoice</b></th>
                </tr>
                
                <tr>
                    <td style="width:80px;font-size:12px;">Bill To</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:260px;font-size:12px;">'.$orders_data->bill_to.'</td>
                    
                    <td style="width:80px;font-size:12px;">Ship To</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:260px;font-size:12px;">'.$orders_data->ship_to.'</td>
                </tr>
                
                <tr>
                    <td style="width:80px;font-size:12px;">Address</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:260px;font-size:12px;">'.$orders_data->address.'</td>
                    
                    <td style="width:80px;font-size:12px;">Address</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:260px;font-size:12px;">'.$orders_data->address.'</td>
                </tr>

                <tr>
                    <td style="width:80px;font-size:12px;">Phone No</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:260px;font-size:12px;">'.$orders_data->phone_no.'</td>
                    
                    <td style="width:80px;font-size:12px;">Invoice No</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:260px;font-size:12px;">'.$orders_data->invoice_no.'</td>
                </tr>
                <tr>
                    <td style="width:80px;font-size:12px;">GST No</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:260px;font-size:12px;">'.$orders_data->dealer_gst.'</td>
                    
                    <td style="width:80px;font-size:12px;">Invoice Date</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:260px;font-size:12px;">'.date("d/m/Y",strtotime($orders_data->invoice_date)).'</td>
                </tr>

            </table>';

        PDF::writeHTML($tbl, true, false, false, false, '');

        PDF::SetXY(10, 90);
        
        $label_discount = 'Discount ( + / - )';
        if($orders_data->discount_type == 'discount_plus'){
            $label_discount = 'Discount ( + )';
        } else if($orders_data->discount_type == 'discount_minus'){
            $label_discount = 'Discount ( - )';
        }
         
        
        $tbl = '<table cellspacing="0" cellpadding="5" border="0" nobr="true">
                <tr>
                    <th align="center" colspan="2" style="width:450px;border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:14px;"><b>PARTICULARS</b></th>
                    <th style="border-top:1px solid black;border-bottom:1px solid black;text-align: center;font-size:14px;"><b>&nbsp;&nbsp;&nbsp; AMOUNT(Rs)</b></th>

                </tr>
                <tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">1) '.$orders_data->product_name.'</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$orders_data->on_road_price.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">2) '.$label_discount.'</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$orders_data->discount.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">4.1) IGST &nbsp; %</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$orders_data->igst.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">4.1) CGST &nbsp; %</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$orders_data->cgst.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">4.2) SGST &nbsp; %</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$orders_data->sgst.'</td>
                </tr>
                
                <tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">4.3) Compensation Cess &nbsp; %</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$orders_data->compensation_cess.'</td>
                </tr>                 
                <tr>
                    <td colspan="2" style="border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:14px;"><b>TOTAL</b></td>
                    <td style="text-align: center;border-top:1px solid black;border-bottom:1px solid black;font-size:14px;">&nbsp;&nbsp;&nbsp; '.$orders_data->total.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:14px;"><b>TCS @1%</b></td>
                    <td style="text-align: center;border-top:1px solid black;border-bottom:1px solid black;font-size:14px;">&nbsp;&nbsp;&nbsp; '.$orders_data->tcs_tax.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:14px;"><b>GRAND TOTAL</b></td>
                    <td style="text-align: center;border-top:1px solid black;border-bottom:1px solid black;font-size:14px;">&nbsp;&nbsp;&nbsp; '.$orders_data->grand_total.'</td>
                </tr>
            </table>';

        PDF::writeHTML($tbl, true, false, false, false, '');
        PDF::SetFont('freeserif', '', 10);
        $content = "Vehicle Particulars";
        PDF::SetXY(15, 185);
        PDF::Cell(0, 0, $content);
        
        PDF::SetXY(10, 190);

        $tbl = '<table cellspacing="0" cellpadding="4" border="0" nobr="true">
                <tr>
                    <td style="width:165px;text-align: center;border-top:1px solid black;border-bottom:1px solid black;border-right:1px solid black;font-size:12px;border-left:1px solid black;">Vin No./Chassis No.<br />'.$orders_data->vin_number.'</td>
                    
                    <td style="width:120px;text-align: center;border-top:1px solid black;border-right:1px solid black;border-bottom:1px solid black;font-size:12px;">Engine No.<br />'.$orders_data->engine_number.'</td>
                    <td style="width:110px;text-align: center;border-top:1px solid black;border-right:1px solid black;border-bottom:1px solid black;font-size:12px;">Key No.<br />'.$orders_data->key_number.'</td>
                    <td style="width:110px;text-align: center;border-top:1px solid black;border-right:1px solid black;border-bottom:1px solid black;font-size:12px;">HSN No<br />'.$orders_data->hsn_code.'</td>
                </tr>
                
        </table>';

        PDF::writeHTML($tbl, true, false, false, false, '');

        PDF::SetFont('freeserif', '', 8);
        $content = "“Terms & condition apply “";
        PDF::SetXY(15, 205);
        PDF::Cell(0, 0, $content); 

        PDF::SetFont('freeserif', '', 12);
        $content = 'For ' . ($from_branch_nm->name ?? '');
        PDF::SetXY(140, 225);
        PDF::Cell(0, 0, $content);

        PDF::SetXY(10, 265);

        $tbl = '<table cellspacing="0" cellpadding="8" border="0" nobr="true">
                <tr>
                    <td style="border-top:1px solid black;font-size:14px;">Signature of Customer</td>
                    <td></td>
                    <td style="border-top:1px solid black;font-size:14px;">Authorised Signatory</td>
                </tr>
                
        </table>';
        
        PDF::writeHTML($tbl, true, false, false, false, '');

        PDF::Output('example_009.pdf', 'I');
    }
    
    
    public function get_pass_pdf(Request $request)
    {       
        ini_set('memory_limit', '48M');
    
        $obf_id = base64_decode($request->id);
        $order_id = base64_decode($request->order_id);

        $orders_data = [];
        $orders_data_get = DB::table('orders')->where('id',  $order_id)->first();
        if($orders_data_get){                    
           $orders_data = $orders_data_get;
        }

        $inventory = DB::table('inventory')->where('id',$orders_data->inventory_id)->first();
        $branch = DB::table('branches')->where('id',$orders_data->branch_id)->first();
        
        $product_data = Product::select(
            'car_model.name as car_name',
            'car_varient.name as varient_name',
            'car_varient.hsn_code as hsn_code',
            'exteriorcolor.name as exterior_color', 
            'interiorcolor.name as interior_color',
        )
        ->leftJoin('car_model', 'car_model.id', '=', 'products.car_model')
        ->leftJoin('car_varient', 'car_varient.id', '=', 'products.veriant')
        ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
        ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
        ->where('products.id', $inventory->name)
        ->where('products.status', 'active')
        ->first();
        
        $obf_data = [];
        $obf_data_get = DB::table('obf')->where('id',  $obf_id)->first();
        if($obf_data_get){                    
           $obf_data = $obf_data_get;
        }
        
        $salesPersonData = DB::table('users')
        ->selectRaw("CONCAT(users.first_name, ' ', users.last_name) AS sales_person_name, Team_master.team_name AS team_leader_name")
        ->leftJoin('Team_master', 'Team_master.id', '=', 'users.team_name')
        ->where('users.id', $obf_data->sales_person_id) // assuming $obf->sales_person_id is the value you have
        ->first();

        
        $dealer_data = DB::table('dealer_management')->select([
            'id', 
            'dealer_name', 
            'dealer_email', 
            'dealer_mobile_no',
            'dealer_address', 
            'state', 
            'city', 
            'gst', 
            'remark'
        ])->where('id', $orders_data->dealer_id)
        ->first();

        $color_name = $product_data->exterior_color .'/'. $product_data->interior_color;

        $images = DB::table('global_configuration')->select('gatepass_logo1','gatepass_logo2')->where('branch_id',$inventory->branch_id)->first();
        $update_inventory_status = Inventory::where('id',$orders_data->inventory_id)->update(['status'=>'sold']);
        $update_order_status = Order::where('id',$order_id)->update(['status'=>'delivered']);

        if($obf_data->insurance_status == 'insurance_completed'){ 
            if($obf_data->rto_status == 'rto_completed'){
                if($obf_data->municipal_tax_applicable == 1){
                    if($obf_data->municipal_tax_status == 'municiple_tax_completed'){
                        return view('order.gate_pass_print')->with(['obf_data' => $obf_data,'orders_data' => $orders_data,'images'=>$images,'product_data'=>$product_data,'color_name'=>$color_name,'branch'=>$branch,'dealer_data'=>$dealer_data,'inventory'=>$inventory,'salesPersonData'=>$salesPersonData]);
                    } else {
                        return redirect()->route('order')->with('error', "Municipal Tax Process Not Completed...");
                    }     
                } else if($obf_data->municipal_tax_applicable == 2) {
                    return view('order.gate_pass_print')->with(['obf_data' => $obf_data,'orders_data' => $orders_data,'images'=>$images,'product_data'=>$product_data,'color_name'=>$color_name,'branch'=>$branch,'dealer_data'=>$dealer_data,'inventory'=>$inventory,'salesPersonData'=>$salesPersonData]);
                }
            } else {
                return redirect()->route('order')->with('error', "RTO Process Not Completed...");
            }          
        }else{
            return redirect()->route('order')->with('error', "Insurance Process Not Completed...");
        }    
    }


    /*public function delivery_receipt_pdf()
    {       
        ini_set('memory_limit', '2048M');

            PDF::SetAuthor('ATUL MOTORS JAM LLP');
            PDF::SetTitle('DELIVERY RECEIPT');
            PDF::SetSubject('DELIVERY RECEIPT');
            PDF::setImageScale(PDF_IMAGE_SCALE_RATIO);
            PDF::AddPage('L', 'A4');
            PDF::Image(public_path('assets/img/atul-logo.jpg'), 15, 18, 23, 24, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);
            PDF::Image(public_path('assets/img/maruti-suzuki-logo.jpg'), 220, 20, 60, 17, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);
            $tbl = '<div style="border:1px solid black;">
                        <h1 align="center" style="font-size:26px;">ATUL MOTORS JAM LLP</h1>
                        <p align="center"><b>( Authorised Dealer :- Maruti Suzuki India Ltd.)</b></p>
                        <table cellspacing="0" cellpadding="1" border="0">
                            <tr>
                                <th style="width:420px;border-bottom:3px solid black;font-size:14px;"><b>E-mail:- sales@atulmotors.com - service@atulmotors.com</b></th>
                                <th style="width:280px;border-bottom:3px solid black;font-size:14px;"><b>Toll Free  1800 3000 3838</b></th>
                                <th style="width:280px;border-bottom:3px solid black;font-size:14px;"><b>Website:- atulmotors.com</b></th>
                            </tr>
                        </table>
                        <table cellspacing="0" cellpadding="5" border="0">
                        <tr>
                            <th colspan="3" style="text-align:center; border-bottom:2px solid black;font-size:14px;"><b>Delivery Receipt</b></th>
                        </tr>
                            <tr>
                                <td colspan="2" style="width:70%;"><b>Invoice Number :- </b>NXA/22-23/0056<br><b>Invoice Date : </b>16/05/2022<br><b>Name : </b>ZEEL VIMALBHAI PATEL<br><b>Mobile No. : </b>96876 12560 <br><b>Address :- </b><br> 401 SHRINIVAS COLONY-1 SUMERCLUB ROAD Jamnagar<br><b>Delivery Location :- </b>Jamnagar NEXA Showroom</td>
                                <td ><b>Gatepass Number :- </b>JMJ/INT?/02519<br><b>Delivery  Time:- </b>16/05/2022<br><b>Current Time:-</b>  
                                </td>
                            </tr>
                           
                        </table>
                        <table cellspacing="0" cellpadding="5" border="0">
                        <tr>
                            <th colspan="3" style="text-align:center; "><b>Tools & Accesories</b></th>
                        </tr>
                            <tr>
                                <td style="width:30%;">
                                    <b>PARTICULARS OF VEHICLE</b><br>
                                    <b>MODEL :- </b>Baleno Alpha Petrol Autometic<br>
                                    <b>Color :- </b>Celestial Blue<br>
                                    <b>CHASSIS NO. :-</b>147142<br>
                                    <b>Engine No. :-</b>7043526<br>
                                    <b>Key No. :-</b>
                                </td>
                                <td>
                                    Mamory Card
                                    Rear Side View Mirror<br>
                                    Warranty & Service Booklet<br>
                                    Remote For MP3 <br>
                                    Invoice <br>
                                    Insurance Policy <br>
                                    SSI/CSI Feedback Card<br>
                                    Service Booklet
                                </td>
                                <td style="width:30%;">
                                    Carpet With Padding<br>
                                    First Aid Kit & Tool Kit<br>
                                    Jack & Jack Handle<br>
                                    Spare Type<br>
                                    Duplicate Key<br>
                                    Owners Manual<br>
                                    Antina<br>
                                    Extended Warrenty Book<br>
                                </td>
                            </tr>
                           
                            
                            <tr>
                                <td style="width:70%;"><br><br>(Customer`s Signature)</td>
                                <td style="width:30%;"><br><br>Customer Signature</td>
                            </tr>
                            
                        </table>
                    </div>';

            PDF::writeHTML($tbl, true, false, false, false, '');

            
        PDF::Output('delivery_receipt.pdf', 'I');
    }*/
    
    public function getOrderData(Request $request)
    {
        $branchCounts = DB::table('branches')
            ->select('name AS branch_name', DB::raw('COUNT(*) as count'))
            ->groupBy('name')
            ->get();
        
        $modelCounts = DB::table('car_model')
            ->select('name AS model_name', DB::raw('COUNT(*) as count'))
            ->where('status', 'active')
            ->groupBy('name')
            ->get();
        
        $statusCounts = DB::table('orders')
            ->select('status AS order_status', DB::raw('COUNT(*) as count'))
            ->groupBy('status')
            ->get();
        
        $varientCounts = DB::table('car_varient')
            ->select('name AS varient_name', DB::raw('COUNT(*) as count'))
            ->groupBy('name')
            ->get();
        
        // Prepare the data for frontend
        $data = [
            'branch' => [
                'branchLabels' => $branchCounts->pluck('branch_name')->toArray(),
                'branchCounts' => $branchCounts->pluck('count')->toArray(),
            ],
            'model' => [
                'modelLabels' => $modelCounts->pluck('model_name')->toArray(),
                'modelCounts' => $modelCounts->pluck('count')->toArray(),
            ],
            'status' => [
                'statusLabels' => $statusCounts->pluck('order_status')->toArray(),
                'statusCounts' => $statusCounts->pluck('count')->toArray(),
            ],
            'varient' => [
                'varientLabels' => $varientCounts->pluck('varient_name')->toArray(),
                'varientCounts' => $varientCounts->pluck('count')->toArray(),
            ],
        ];
        
        return response()->json($data);
    }
    
    public function dealer_get_pass_pdf(Request $request)
    {       
        ini_set('memory_limit', '48M');

        $obf_id = base64_decode($request->id);
        $order_id = base64_decode($request->order_id);

        $orders_data = [];
        $orders_data_get = DB::table('orders')->where('id',  $order_id)->first();
        if($orders_data_get){                    
           $orders_data = $orders_data_get;
        }

        $inventory = DB::table('inventory')->where('id',$orders_data->inventory_id)->first();
        
        $branch = DB::table('branches')->where('id',$inventory->branch_id)->first();
        
        $product_data = Product::select(
            'car_model.name as car_name',
            'car_varient.name as varient_name',
            'car_varient.hsn_code as hsn_code',
            'exteriorcolor.name as exterior_color', 
            'interiorcolor.name as interior_color',
        )
        ->leftJoin('car_model', 'car_model.id', '=', 'products.car_model')
        ->leftJoin('car_varient', 'car_varient.id', '=', 'products.veriant')
        ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
        ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
        ->where('products.id', $inventory->name)
        ->where('products.status', 'active')
        ->first();
        
        $dealer_data = DB::table('dealer_management')->select([
            'id', 
            'dealer_name', 
            'dealer_email', 
            'dealer_mobile_no',
            'dealer_address', 
            'state', 
            'city', 
            'gst', 
            'remark'
        ])->where('id', $orders_data->dealer_id)
        ->first();
        
        $update_inventory_status = Inventory::where('id',$orders_data->inventory_id)->update(['status'=>'sold']);
        
        $get_inventory_details = Inventory::where('id',$orders_data->inventory_id)->first();
        
        $allowedBranches = [1,2,3,4,6,9];
        $allowedDealers  = [2,3];
        
        if (in_array($orders_data->branch_id, $allowedBranches) && in_array($orders_data->dealer_id, $allowedDealers)) {
        
            $inventory_crud = [
                'delear_id' => '',
                'name' => $get_inventory_details->name,
                'branch_id' => $get_inventory_details->to_branch,
                'to_branch' => '',
                'key_number' => $get_inventory_details->key_number,
                'engine_number' => $get_inventory_details->engine_number,
                'chassis_number' => $get_inventory_details->chassis_number,
                'vin_number' => $get_inventory_details->vin_number,
                'basic_price' => $get_inventory_details->basic_price,
                'ex_showroom_price' => $get_inventory_details->ex_showroom_price,
                'allocation_count' => $get_inventory_details->allocation_count,
                'aging_days' => $get_inventory_details->aging_days,
                'purchase_price' => $get_inventory_details->purchase_price,
                'kin_margin' => $get_inventory_details->kin_margin,
                'fuel_type' => $get_inventory_details->fuel_type,
                'veriant' => $get_inventory_details->veriant,
                'interior_color' => $get_inventory_details->interior_color,
                'exterior_color' => $get_inventory_details->exterior_color,
                'kin_invoice_no' => $get_inventory_details->kin_invoice_no,
                'kin_invoice_date' => $get_inventory_details->kin_invoice_date,
                'manufacturing_year' => $get_inventory_details->manufacturing_year,
                'inventory_type' => $get_inventory_details->inventory_type,
                'remark' => $get_inventory_details->remark,
                'offer_applicable' => $get_inventory_details->offer_applicable,
                'status' => 'active',
                'allocation_date' => '',
                'created_at' => now(),
                'updated_at' => '',
                'created_by' => auth()->id(),
                'updated_by' => '',
                'fsc_code' => $get_inventory_details->fsc_code,
            ]; 
            
            TransitInventory::create($inventory_crud);
        }    
        
        $update_order_status = Order::where('id',$order_id)->update(['status'=>'delivered']);

        $color_name = $product_data->exterior_color .'/'. $product_data->interior_color;

        $images = DB::table('global_configuration')->select('gatepass_logo1','gatepass_logo2')->where('branch_id',$inventory->branch_id)->first();

        return view('order.dealer_gate_pass')->with(['orders_data' => $orders_data,'images'=>$images,'product_data'=>$product_data,'color_name'=>$color_name,'branch'=>$branch,'dealer_data'=>$dealer_data,'inventory'=>$inventory]);
    }
    
    public function dealer_invoice_create(Request $request){
        $order_id = base64_decode($request->id);
        $data = Order::where('id',$order_id)->first();
  
        if ($data) {
            
            
            $inventory_data = Inventory::where('id',$data->inventory_id)->where('status','allocatedDealer')->first();
            
        
            $product_data = Product::select(
                'car_model.name as car_name',
                'car_varient.name as varient_name',
                'car_varient.hsn_code as hsn_code',
                'car_varient.tex_master_id',
                'exteriorcolor.name as exterior_color', 
                'interiorcolor.name as interior_color',
            )
            ->leftJoin('car_model', 'car_model.id', '=', 'products.car_model')
            ->leftJoin('car_varient', 'car_varient.id', '=', 'products.veriant')
            ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
            ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
            ->where('products.id', $inventory_data->name)
            ->where('products.status', 'active')
            ->first();
            
            $tex_data = Texmaster::where('id', $product_data->tex_master_id)->where('status','active')->first();
            $cess_tax_percentage = $tex_data->compensation_cess ?? 0;
            $gst_tax_percentage = $tex_data->gst ?? 0;
            
            $branch_nm = Branch::where('id',$inventory_data->branch_id)->first();

            $invoice_prefix = (in_array($inventory_data->branch_id, [1, 2, 4, 6])) ? 'SIBAPL/2526/' : 'SALLP/2526/';

            // Fetch the last created invoice number with the same prefix
            $last_invoice = Order::where('invoice_no', 'like', $invoice_prefix . '%')->orderBy('invoice_no', 'desc')->first();
            
            // Extract the last incremented number or start from 1
            if ($last_invoice) {
                $last_number = (int) substr($last_invoice->invoice_no, -2); // Get the last 2 digits
                $new_number = str_pad($last_number + 1, 2, '0', STR_PAD_LEFT); // Increment and pad with zero
            } else {
                $new_number = '01'; // Start from 01 if no previous invoice exists
            }
            
            // Generate the new invoice number
            $invoice_no = $invoice_prefix . $new_number;
            
            $state = \DB::table('common_state')->where('status', 'active')->pluck('name', 'id')->toArray();
  
            return view('order.dealer_invoice_create')->with(['data' => $data,'invoice_no'=>$invoice_no,'inventory_data'=>$inventory_data,'branch_nm'=>$branch_nm,'state'=>$state,'cess_tax_percentage'=>$cess_tax_percentage,'gst_tax_percentage'=>$gst_tax_percentage]);
        } else {
            return view('order.dealer_invoice_create')->with('error', 'No record found!');
        }
    }
    
    public function dealer_invoice_insert(Request $request){
        if($request->ajax()) { return true; }
        
        $id = $request->id;
        $crud = [
            'invoice_no' => $request->invoice_no,
            'invoice_date' => $request->invoice_date,
            'status' => 'invoice_create',
            'remark' => $request->remark,
            'updated_by' => auth()->user()->id,
            'updated_at' => date('Y-m-d H:i:s')
        ];
            
        if($request->invoice_date != '' && $request->invoice_date != NULL){
            $crud['invoice_date'] = date("Y-m-d",strtotime($request->invoice_date));    
        }
         
        $update = Order::where(['id' => $id])->update($crud);
        

        if ($update){
            $orders_data_get = DB::table('orders')->where('id',  $id)->first();
            if($orders_data_get){                    
               $orders_data = $orders_data_get;
            }
            $update_inventory_status = Inventory::where('id',$orders_data->inventory_id)->update(['status'=>'invoice_create']);
           return redirect()->route('order')->with('success', 'Order created successfully!');;
        }else{
            return redirect()->back()->with(['error'=>'Faild Invoice Create!'])->withInput();
        }
    }
    
    public function invoice_cancel(Request $request){
        $order_id = base64_decode($request->record_id);
        $status = $request->status;

        $crud = [
            'remark' => $request->cancel_remark,
            'status' => $request->status,
        ];
        
        $crud_logs = [
            'module_nm' => 'order',
            'module_id' => $order_id,
            'status' => $request->status,
            'remark' => $request->cancel_remark,
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
        ];
        
        $updated = DB::table('orders')->where('id', $order_id)->update($crud);
        \DB::table('logs')->insert($crud_logs);
        
        if ($updated) {
            return response()->json(['success' => true, 'message' => 'Invoice cancelled successfully.']);
        } else {
            return response()->json(['success' => false, 'message' => 'Failed to update record.'], 500);
        }
    }

    public function liquidationprocess(Request $request)
    {
        try {
            $orders_id = base64_decode($request->encoded_id);
    
            $exists = DB::table('orders')->where('id', $orders_id)->exists();
            if (!$exists) {
                return response()->json(['success' => false, 'message' => 'Record not found.']);
            }
    
            $crud = [
                'refund_remark' => $request->refund_remark,
                'refund_amount' => $request->refund_amount,
                'status'        => 'refund_process',
                'updated_at'    => now(), 
            ];
    
            $updated = DB::table('orders')->where('id', $orders_id)->update($crud);
    
            $crud_logs = [
                'module_nm'  => 'orders',
                'module_id'  => $orders_id,
                'status'     => 'refund_process',
                'remark'     => $request->remark,
                'created_at' => now(),
                'created_by' => auth()->id(),
            ];
    
            DB::table('logs')->insert($crud_logs);
    
            return response()->json(['success' => true, 'message' => 'Liquidation processed successfully.']);
    
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ], 500);
        }
    }
}
