<?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\Texmaster;
use App\Models\Carvarient;
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','ob.customer_name','car_model.name as carmodel','car_varient.name as carvarient',DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name"),'inventory.allocation_count','inventory.aging_days')
                            ->leftjoin('branches as b', 'b.id', 'o.branch_id')
                            ->leftjoin('obf as ob', 'ob.id', 'o.obf_id')
                            ->leftjoin('users','users.id','o.customer_id')
                            ->leftjoin('users as us','us.id','ob.sales_person_id')
                            ->leftjoin('products','products.id','ob.product_id')
                            ->leftjoin('inventory','inventory.id','o.inventory_id')
                            ->leftjoin('car_model','car_model.id','products.car_model')
                            ->leftjoin('car_varient','car_varient.id','products.veriant')
                            ->orderBy('o.id' ,'desc')
                            ->get();
                
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('action', function($data){
                            $return = '<div class="btn-group">';

                            if(auth()->user()->can('orders-view')){
                                $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();

                            $finance_required = 'yes';
                            if($obf_data)
                            $finance_required=$obf_data->finance_required;

                            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'){
                                $return .='<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="cancled" data-id="' . base64_encode($data->id) . '">Cancelled</a></li>';

                                if($finance_required == 'yes'){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="finance_apporve" data-id="' . base64_encode($data->id) . '">Finance Apporve</a></li>';
                                }else{
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="all_payment_done" data-id="' . base64_encode($data->id) . '">All Payment Done</a></li>';
                                }    
                            }
                            elseif ($data->status == 'cancled'){
                                $return .='<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="waiting" data-id="' . base64_encode($data->id) . '">Waiting</a></li>';
                            }

                            elseif ($data->status == 'finance_apporve') {
                                $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="disbursement" data-id="' . base64_encode($data->id) . '">Disbursement</a></li>';
                            }
                            elseif ($data->status == 'disbursement') {
                               $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="all_payment_done" data-id="' . base64_encode($data->id) . '">All Payment Done</a></li>';
                            }
                            elseif ($data->status == 'all_payment_done') {
                                if ($data->invoice_date == NULL && $data->invoice_no == NULL) {
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.invoice_create', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '" >Invoice Create</a></li>'; 
                                }
                            }
                            elseif ($data->status == 'pdi_reject') {
                                $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="pdi_approve" data-id="' . base64_encode($data->id) . '">PDI Approve</a></li>';
                            }
                            elseif ($data->status == 'pdi_approve') {
                                if ($data->invoice_date == NULL && $data->invoice_no == NULL) {
                                    $return .= '<li><a class="dropdown-item" href="' . route('order.invoice_create', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '" >Invoice Create</a></li>';
                                }
                                $return .= '<li><a class="dropdown-item" href="' . route('order.get_pass_pdf', ['id' => base64_encode($data->obf_id),'order_id' => base64_encode($data->id)]) . '">Gate Pass Print</a></li>';
                                //ready_to_deliver click on Gate Pass Print
                                $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="pdi_reject" data-id="' . base64_encode($data->id) . '">PDI Reject</a></li>';
                            }
                            elseif ($data->status == 'ready_to_deliver') {
                                $return .='<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="delivered" data-id="' . base64_encode($data->id) . '">Delivered</a></li>';
                            }
                            if ($data->invoice_date != NULL && $data->invoice_no != NULL) {
                                $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>';
                                $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>';
                            }                            

                            $return .= '</ul>';   

                            $return .= '</div>';

                        }



                            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>';
                            }else{
                                return '-';
                            }
                        })
                        ->rawColumns(['action','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);
            $data = Order::where(['id' => $id])->first();

            /*var_dump($request->status);
            die('sttpo');*/

            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]);
                }elseif ($request->status == 'all_payment_done') {
                    //$request->status == 'disbursement' || 

                    $finance_discount = 0;
                    $net_disbusment = 0;
                    $trade_car_value = 0;
                    $on_road_price = 0;

                    $obf_data = OBF::where(['id' => $data->obf_id])->first();
                    if($obf_data){                    
                        $trade_car_value = (int) $obf_data->trade_car_value;                       
                        $on_road_price = (int) $obf_data->on_road_price;                       
                    }

                    $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;

                    if($total_amount_get >= $on_road_price){
                        //payment done
                        // echo "payment done";
                         $update = Order::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);   
                    }else{
                        //payment pending
                         //echo "payment pending";
                        return response()->json(['code' => 200,'obf_id' => $data->obf_id]);
                    }


                     /*echo "<br/>"; 
                    echo "finance_discount==>".$finance_discount;     
                    echo "<br/>";               
                    echo "net_disbusment==>".$net_disbusment;
                    echo "<br/>";               
                    echo "trade_car_value==>".$trade_car_value;
                    echo "<br/>";               
                    echo "cash_receipt_amount==>".$cash_receipt_amount;
                    echo "<br/>";     
                    echo "on_road_price==>".$on_road_price;
                    echo "<br/>";   
                     echo "total_amount_get==>".$total_amount_get;
                    echo "<br/>";     
                    die('stp[');*/
                    // return redirect()->route('order')->with(['error' => 'Your Payment is Pending!']);
                    
                }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)
        {   
            $pending_payment_data = [];
            if(isset($request->obf_id)){
                $finance_discount = 0;
                $net_disbusment = 0;    
                $trade_car_value = 0;
                $on_road_price = 0;

                $obf_data = OBF::where(['id' => $request->obf_id])->first();
                if($obf_data){                    
                $trade_car_value = (int) $obf_data->trade_car_value;                       
                $on_road_price = (int) $obf_data->on_road_price;                       
                }

                $finance_data = DB::table('obf_finance')->where(['obf_id' => $request->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' => $request->obf_id,'status' => 'accepted'])->sum('amount');

                $total_amount_get = $finance_discount + $net_disbusment + $trade_car_value + $cash_receipt_amount;


                if($total_amount_get >= $on_road_price){
                    //payment done
                    $pending_payment_data = array(
                        'payment_status' => 1
                    );
                }else{
                    //pending payment
                    $pending_payment = $on_road_price - $total_amount_get;

                    $pending_payment_data = array(
                        'finance_discount' => $finance_discount, 
                        'net_disbusment' => $net_disbusment, 
                        'trade_car_value' => $trade_car_value, 
                        '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
                    );                    
                }
                
            }

            /*echo "<pre>";
            var_dump($request->obf_id);
            var_dump($pending_payment_data);
            die('st[p');*/


            return view('order.payment_pending_detail')->with(['pending_payment_data' => $pending_payment_data]);
        }
    /** payment_pending_detail */

    /** 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();

            /*$cash_receipt_data = [];
            if(isset($request->cash_receipt_id) && !empty($request->cash_receipt_id)){
                $cash_receipt_id = base64_decode($request->cash_receipt_id);
                $cash_receipt_data = CashReceipt::where(['id' => $cash_receipt_id])->first();   
            }*/
            //'cash_receipt_data' => $cash_receipt_data

            if ($data) {

                $finance_name = '';
                $finance_discount = '';

                $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;
                }

                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]);
            } else {
                return view('order.invoice_create')->with('error', 'No record found!');
            }
        }
    /** 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]);
            } 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;
            
            $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,
                'sgst' => $request->sgst,
                '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' => 'pdi_approve',
                'updated_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s')
            ];
                
               /* echo "<pre>";
                print_r($crud);
                die('st');*/
            if($request->invoice_date != '' && $request->invoice_date != NULL){
                $crud['invoice_date'] = date("Y-m-d",strtotime($request->invoice_date));    
            }
            
            // \DB::enableQueryLog(); 
            $update = Order::where(['id' => $id])->update($crud);
             // dd(DB::getQueryLog());
            // die('stop');

            if ($update){
               return redirect()->route('order.invoice_pdf', ['id' => base64_encode($obf_id),'order_id' => base64_encode($id)]);
               // return redirect()->route('order')->with(['success' => 'Invoice Create successfully']);
            }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,
                'updated_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s')
            ];
            // \DB::enableQueryLog(); 
            $update = Order::where(['id' => $id])->update($crud);
             // dd(DB::getQueryLog());
            // die('stop');

            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;
        }

        // var_dump($orders_data->dealer_gst);

       

        PDF::SetAuthor('Nicola Asuni');
        PDF::SetTitle('Invoice');
        PDF::SetSubject('Invoice');
        PDF::setImageScale(PDF_IMAGE_SCALE_RATIO);
        PDF::AddPage();
        PDF::Image(public_path('assets/img/kia.jpg'), 16, 11, 40, 10, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);
        PDF::SetFont('freeserif', '', 8);
        PDF::SetTextColor(50, 50, 50);
        $content = "Savan IB Automotive Private Limited";
        PDF::SetXY(80, 12);
        PDF::Cell(0, 0, $content);
        $content = "Savan IB Cars Pvt Ltd, Revenue Survey";
        PDF::SetXY(79, 15);
        PDF::Cell(0, 0, $content);
        $content = "No. 41/1. Gondal Ahmedabad By-Pass Circle, Gondal Road,";
        PDF::SetXY(68, 18);
        PDF::Cell(0, 0, $content);
        $content = "NH-88, At: Village Vavdi, Rajkot, 360004";
        PDF::SetXY(78, 21);
        PDF::Cell(0, 0, $content);
        $content = "Ph.:        72280 80803";
        PDF::SetXY(88, 25);
        PDF::Cell(0, 0, $content);
        $content = "GST No./PAN No.: ".$orders_data->dealer_gst."/".$orders_data->dealer_pan_number;
        PDF::SetXY(70, 28);
        PDF::Cell(0, 0, $content);
        $content = "IRN No.:";
        PDF::SetXY(50, 32);
        PDF::Cell(0, 0, $content);
        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 = ':';            

        }
        
        $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;">Dealer GST / PAN No</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">24ABACS4515J1ZH/ABACS4515J</td>
                    <td style="width:100px;font-size:12px;">'.$customer_gst_label.'</td>
                    <td style="width:10px;font-size:12px;">'.$customer_gst_dot.'</td>
                    <td style="width:280px;font-size:12px;">'.$customer_gst.'</td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;">Bill To</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">'.$orders_data->bill_to.'</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;">Address</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;" rowspan="3">'.$orders_data->address.'</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;"></td>
                    <td style="width:10px;font-size:12px;"></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;"></td>
                    <td style="width:10px;font-size:12px;"></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;">'.$orders_data->phone_no.'</td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;">Ship To</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">'.$orders_data->ship_to.'</td>
                    <td style="width:100px;font-size:12px;"></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:280px;font-size:12px;"></td>
                </tr>
               <tr>
                    <td style="width:120px;font-size:12px;"></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:300px;font-size:12px;"></td>
                    <td style="width:100px;font-size:12px;"></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:280px;font-size:12px;"></td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;"></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:300px;font-size:12px;"></td>
                    <td style="width:100px;font-size:12px;"></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:280px;font-size:12px;"></td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;"></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:300px;font-size:12px;"></td>
                    <td style="width:100px;font-size:12px;"></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:280px;font-size:12px;"></td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;"></td>
                    <td style="width:10px;font-size:12px;"></td>
                    <td style="width:300px;font-size:12px;"></td>
                    <td style="width:100px;font-size:12px;">PAN No</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:280px;font-size:12px;">'.$orders_data->pan_number.'</td>
                </tr>
                <tr>
                    <td style="width:120px;font-size:12px;">Financed by/Hypo. by</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:300px;font-size:12px;">'.$orders_data->finance_name.'</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>
            </table>';

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

         PDF::SetXY(10, 110);
        
        $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) 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;">3) Net Selling Price</td>
                    <td style="text-align: center;font-size:12px;">&nbsp;&nbsp;&nbsp; '.$orders_data->selling_price.'</td>
                </tr>
                <tr>
                    <td colspan="2" style="font-size:12px;border-right:1px solid black;">4.1) CGST &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 14 %</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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 14 %</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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 20 %</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>';

            /*<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, 200);
        PDF::Cell(0, 0, $content);
        
        PDF::SetXY(10, 205);

        $tbl = '<table cellspacing="0" cellpadding="5" 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.<br />'.$orders_data->vin_number.'</td>
                    <td style="width:165px;text-align: center;border-top:1px solid black;border-right:1px solid black;border-bottom:1px solid black;font-size:12px;">Chassis No.<br />'.$orders_data->chassis_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, 225);
        PDF::Cell(0, 0, $content);

        PDF::SetFont('freeserif', '', 12);
        $content = "Applied Promotion:";
        PDF::SetXY(15, 230);
        PDF::Cell(0, 0, $content);

        PDF::SetFont('freeserif', '', 12);
        $content = "For Savan IB Automotive Private Limited";
        PDF::SetXY(110, 235);
        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');

       /* PDF::setFooterCallback(function($pdf) 
        { 
            PDF::SetFont('dejavusansb', '', 15);
            PDF::SetTextColor(50, 50, 50);
            $content = "Savan IB Automotive Private Limited";
            PDF::SetXY(20, 275);
            PDF::Cell(0, 0, $content);
            PDF::Image(public_path('assets/img/logo.jpg'), 130, 273, 20, 12, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);
            PDF::SetFont('dejavusans', '', 10);
            PDF::SetTextColor(50, 50, 50);
            $content = "No. 41/1. Gondal Ahmedabad By-Pass Circle, Gondal Road, NH-88, At: Village Vavdi, Rajkot, 360004";
            PDF::SetXY(20, 285);
            PDF::Cell(0, 0, $content);              
        });*/


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

        $crud = [     
            'status' => 'ready_to_deliver',           
            'updated_by' => auth()->user()->id,
            'updated_at' => date('Y-m-d H:i:s')
        ];
        $update = Order::where(['id' => $order_id])->update($crud);


        $data = OBF::where(['id' => $obf_id])->first();
        //notification insert
        $notification_template_master_data = DB::table('notification_template_master')->select('*')->where(['template_name' => 'gate_gass_create','status' => 'active'])->first();
        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($obf_id)]),
                'created_by' => auth()->user()->id,
            ];
            DB::table('notifications')->insert($notification_data);
        }
        //notification insert

        /*var_dump($order_id);
        die('s');*/


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

        $obf_data = [];
        $obf_data_get = DB::table('obf')->where('id',  $obf_id)->first();
        if($obf_data_get){                    
           $obf_data = $obf_data_get;
        }
        $product_id  = isset($obf_data->product_id) ? $obf_data->product_id : 0;
        $sales_person_id  = isset($obf_data->sales_person_id) ? $obf_data->sales_person_id : 0;

        $varient_name = '';
        $color_name = '';
        if($product_id > 0){
            $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')
            ->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',  $obf_data->product_id)
            ->first();

            $product_data = [];
            if($product_data_get){   
                $product_data = $product_data_get;
            }
            $varient_name  = isset($product_data->varient_name) ? $product_data->varient_name : '';
            $exterior_color  = isset($product_data->exterior_color) ? $product_data->exterior_color : '';
            $interior_color  = isset($product_data->interior_color) ? $product_data->interior_color : '';
            $color_name = $exterior_color.' | '.$interior_color;

        }


        $sales_person_name = '';
        $sales_person_contact_number = '';
        if($sales_person_id > 0){
            $user_data = [];
            $user_data_get = DB::table('users')->select('id' , 'contact_number' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active','id' => $obf_data->sales_person_id])->first();
            if($user_data_get){                    
               $user_data = $user_data_get;
            }
            $sales_person_name  = isset($user_data->sales_person_name) ? $user_data->sales_person_name : '';
            $sales_person_contact_number  = isset($user_data->contact_number) ? $user_data->contact_number : '';
        }

        PDF::SetAuthor('Nicola Asuni');
        PDF::SetTitle('Gate Pass');
        PDF::SetSubject('Gate Pass');
        PDF::setImageScale(PDF_IMAGE_SCALE_RATIO);
        PDF::AddPage();

        //PDF::Image(public_path('assets/img/logo.jpg'), 15, 18, 20, 12, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);

        PDF::Image(public_path('assets/img/new_kia.jpg'), 150, 11, 50, 19, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);

        PDF::Image(public_path('assets/img/ib_logo.jpeg'), 10, 11, 100, 15, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);

        /*PDF::SetFont('dejavusansb', '', 20);
        PDF::SetTextColor(50, 50, 50);
        $content = "MARUTI SUZUKI";
        PDF::SetXY(35, 20);
        PDF::Cell(0, 0, $content);

        PDF::SetFont('dejavusans', '', 20);
        PDF::SetTextColor(50, 50, 50);
        $content = "NEXA";
        PDF::SetXY(100, 20);
        PDF::Cell(0, 0, $content);*/

        
        PDF::SetFont('dejavusans', '', 10);
        PDF::SetXY(10, 35);
        $tbl = '
            <table cellspacing="0" cellpadding="1" border="0">
                <tr style="background-color:black;">
                        <td colspan="6" style="width:97%;font-size:14px;color:white;text-align:center"><b>DELIVERY CHALLAN</b></td>
                </tr>
                <tr>
                    <td style="width:100px;font-size:12px;">No</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:180px;font-size:12px;">DLN-'.$obf_id.'</td>
                    <td style="width:120px;font-size:12px;">Model</td>
                    <td style="width:10px;font-size:12px;">:</td>
                    <td style="width:280px;font-size:12px;">'.$varient_name.'</td>
                </tr>
                <tr>
                    <td>Date</td>
                    <td>:</td>
                    <td>'.date("d/m/Y",strtotime($orders_data->invoice_date)).'</td>
                    <td>Color</td>
                    <td>:</td>
                    <td>'.$color_name.'</td>
                </tr>
                <tr>
                    <td>Invoice No.</td>
                    <td>:</td>
                    <td>'.$orders_data->invoice_no.'</td>
                    <td>Vehicle No.</td>
                    <td>:</td>
                    <td>SSF5S6D5D21W96D5Q</td>
                </tr>
                <tr>
                    <td>Invoice Date</td>
                    <td>:</td>
                    <td>'.date("d/m/Y",strtotime($orders_data->invoice_date)).'</td>
                    <td>Chassis No.</td>
                    <td>:</td>
                    <td>'.$orders_data->chassis_number.'</td>
                </tr>
                <tr>
                    <td>Order No.</td>
                    <td>:</td>
                    <td>ORD-'.$orders_data->id.'</td>
                    <td>Engine No.</td>
                    <td>:</td>
                    <td>'.$orders_data->engine_number.'</td>
                </tr>
                <tr>
                    <td>Order Date</td>
                    <td>:</td>
                    <td>'.date("d/m/Y",strtotime($orders_data->created_at)).'</td>
                    <td>Key No.</td>
                    <td>:</td>
                    <td>'.$orders_data->key_number.'</td>
                </tr>
               <tr>
                    <td>Customer ID</td>
                    <td>:</td>
                    <td>'.$orders_data->customer_id.'</td>
                    <td>Registration No.</td>
                    <td>:</td>
                    <td>REG-'.$orders_data->id.'</td>
                </tr>
                
                <tr>
                    <td>Name</td>
                    <td>:</td>
                    <td>'.$orders_data->bill_to.'</td>
                    <td>Registration Date</td>
                    <td>:</td>
                    <td>'.date("d/m/Y",strtotime($orders_data->created_at)).'</td>
                </tr>
                <tr>
                    <td rowspan="3">Address</td>
                    <td rowspan="3">:</td>
                    <td rowspan="3">'.$orders_data->address.'</td>
                    <td>Hypothecated To</td>
                    <td>:</td>
                    <td>'.$orders_data->finance_name.'</td>
                </tr>
                <tr>
                    <td>Sales Executive</td>
                    <td>:</td>
                    <td>'.$sales_person_name.'</td>
                </tr>
                <tr>
                    <td>Phone No.(M)</td>
                    <td>:</td>
                    <td>'.$sales_person_contact_number.'</td>
                </tr>
                <tr>
                    <td>Phone No.(O)</td>
                    <td>:</td>
                    <td></td>
                    <td>Invoice</td>
                    <td>:</td>
                    <td>'.$orders_data->grand_total.'</td>
                </tr>
                <tr>
                    <td>Phone No.(R)</td>
                    <td>:</td>
                    <td></td>
                    <td>Delivery</td>
                    <td>:</td>
                    <td>'.$orders_data->grand_total.'</td>
                </tr>
                <tr>
                    <td>Phone No.(M)</td>
                    <td>:</td>
                    <td>'.$orders_data->phone_no.'</td>
                    <td>Gate Pass</td>
                    <td>:</td>
                    <td></td>
                </tr>
            </table>
            ';

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

        PDF::SetXY(10, 120);
        
        $tbl = '
            <table cellspacing="0" cellpadding="2" border="0">
                <tr>
                    <th style="font-size:14px; border-top:1px solid black;border-bottom:1px solid black;">Standard Delivery</th>
                    <th style="font-size:14px;border-top:1px solid black;border-bottom:1px solid black;">Tools and Accesories</th>
                </tr>
                <tr>
                    <td style="font-size:12px;">1. Duplicate Key</td>
                    <td style="font-size:12px;">1. CMVR Kit</td>
                </tr>
               <tr>
                    <td style="font-size:12px;">2. iCATS Key</td>
                    <td style="font-size:12px;">2. Insurance Cover Note/Policy</td>
                </tr>
                <tr>
                    <td style="font-size:12px;">3. Manual Issued</td>
                    <td style="font-size:12px;">3. PDI Copy</td>
                </tr>
                <tr>
                    <td style="font-size:12px;">4. R.C. Book</td>
                    <td style="font-size:12px;">4. POP Survey Form</td>
                </tr>
                <tr>
                    <td style="font-size:12px;">5. RTO Challan</td>
                    <td style="font-size:12px;">5. Type of Registration</td>
                </tr>
                <tr>
                    <td style="font-size:12px;">6. Sales Invoice</td>
                    <td style="font-size:12px;">6. SSI Feedback Card</td>
                </tr>
                <tr>
                    <td style="font-size:12px;">7. Sales Letter</td>
                    <td style="font-size:12px;">7. Taxi/Ambulance/Normal</td>
                </tr>
                <tr>
                    <td style="font-size:12px;">8. Tool Kit</td>
                    <td style="font-size:12px;"></td>
                </tr>
            </table>
            ';

        PDF::writeHTML($tbl, true, false, false, false, '');
        
       
        PDF::SetFont('dejavusans', '', 10);
        $content = "Terms & condition apply";
        PDF::SetXY(10, 180);
        PDF::Cell(0, 0, $content);

        PDF::SetFont('dejavusans', '', 12);
        $content = "For Mr ".$orders_data->bill_to;
        PDF::SetXY(10, 200);
        PDF::Cell(0, 0, $content);

        PDF::SetFont('dejavusans', '', 12);
        $content = "For Savan IB Automotive Private Limited";
        PDF::SetXY(110, 200);
        PDF::Cell(0, 0, $content);

       
        PDF::SetFont('dejavusans', '', 12);
        $content = "(Customer Name & Signature)";
        PDF::SetXY(10, 220);
        PDF::Cell(0, 0, $content);

        PDF::SetFont('dejavusans', '', 12);
        $content = "(Authorized Signature)";
        PDF::SetXY(110, 220);
        PDF::Cell(0, 0, $content);
            
           
        PDF::Output('get_pass_pdf.pdf', 'I');
    }
    /*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');
    }*/
}
