<?php

namespace App\Http\Controllers;

use App\Exports\ExportInventory;
use App\Http\Requests\InventoryAcceptRequest;
use App\Http\Requests\InventoryDealerAcceptRequest;
use App\Http\Requests\InventoryRequest;
use App\Imports\ImportInventory;
use App\Models\Branch;
use App\Models\Carmodel;
use App\Models\Carvarient;
use App\Models\Category;
use App\Models\Dealer;
use App\Models\Exteriorcolor;
use App\Models\Fuletype;
use App\Models\Interiorcolor;
use App\Models\Inventory;
use App\Models\Texmaster;
use App\Models\OBF;
use App\Models\Order;
use App\Models\Product;
use Auth, DB, Mail, Validator, File, DataTables;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Illuminate\Validation\Rule;

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

    /** index */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            /*$data = DB::table('inventory as i')
                ->select('i.id',  'i.name', 'b.name as branch', 'i.veriant', 'i.ex_showroom_price', 'i.status','i.aging_days', 'cv.name as varient_name', 'cm.name as car_name','i.vin_number')
                ->leftjoin('branches as b', 'b.id', 'i.branch_id')
                ->leftjoin('products', 'i.name', 'products.id')
                ->leftjoin('car_model as cm', 'cm.id', 'products.car_model')
                ->leftjoin('car_varient as cv', 'cv.id', 'products.veriant')
                ->orderBy('i.id', 'desc')
                ->where('i.status','!=','deleted')->get();*/
            
            $data = DB::table('inventory as i')->select(
                'i.id',  
                'i.name', 
                'b.name as branch', 
                'i.veriant',
                'i.inventory_type',
                'i.ex_showroom_price', 
                'i.status',
                'i.aging_days', 
                // 'cv.name as varient_name', 
                DB::raw("CONCAT(cv.name, ' - ', tex_master.gst, ' - ',tex_master.compensation_cess,  ' %') AS varient_name"),
                'cm.name as car_name',
                'i.vin_number',
                'i.remark',
                'obb.booking_date',
                DB::raw('count(obb.id) as obf_count'),
                DB::raw('MAX(obf.id) as obf'),
                DB::raw("CASE WHEN orders.invoice_no IS NOT NULL AND orders.invoice_date IS NOT NULL THEN orders.invoice_no ELSE '---' END as invoice_no"),
                DB::raw("COALESCE(MAX(orders.invoice_date), '--') as invoice_date"),
                // DB::raw('(CASE WHEN i.status = "allocated" THEN obf.customer_name END) AS customer_name'),
                'obf.customer_name as customer_name',
                'i.purchase_price',
                'i.kin_margin',
                'i.manufacturing_year', 
                'fule_type.title as fuel_type'
            )
                
                ->leftjoin('branches as b', 'b.id', 'i.branch_id')
                
                ->leftjoin('products', 'i.name', 'products.id')
                ->leftjoin('car_model as cm', 'cm.id', 'products.car_model')
                ->leftjoin('car_varient as cv', 'cv.id', 'products.veriant')
                ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
                ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
                ->leftJoin("obf as obb", function($join) {
                    $join->on("obb.product_id","=","i.name");
                    $join->whereNotIn('obb.status', ['deleted', 'delete', 'cancel']);
                })
                
                ->leftJoin('obf','i.id','obf.inventory_id')
                ->leftjoin('orders','orders.inventory_id','=','i.id')
                ->leftjoin('fule_type','fule_type.id','=','i.fuel_type')
                ->leftjoin('tex_master', 'cv.tex_master_id', '=', 'tex_master.id')
                ->groupBy('i.id')//->groupBy('i.name')
                ->orderBy('i.id', 'desc')
                ->whereNotIn('i.status', ['allocatedDealer','inactive', 'deleted','sold']);


            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($data) {
                    $return = '<div class="btn-group">';

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

                    if (auth()->user()->can('inventory-edit')) {
                        if ($data->status == 'allocated') {
                            $return .= '';
                        }else{
                            $return .= '<a href="' . route('inventory.edit', ['id' => base64_encode($data->id)]) . '" class="btn btn-default btn-xs">
                                <i class="fa fa-edit"></i>
                                </a> &nbsp;';

                        }
                    }

                    if (auth()->user()->can('inventory-delete')) {
                        if ($data->status == 'pdi_hold') {
                            $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">';

                            $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                                                        <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                                                        <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                                                    </ul>';
                        } else if ($data->status == 'allocated') {
                            //$return .= '';

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


                                $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Deallocated</a></li>';
                                    //Active
                              
                             $return .= '</ul>';

                        } else {
                            $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">';
                            $return .= '<li><a class="dropdown-item" href="' . route('inventory.viewlogs', ['id' => $data->id]) . '">View Logs</a></li>';
                            
                            
                            if ($data->status != 'invoice_create'){
                                if ($data->status == 'active' || $data->status == 'deal_generated') {
                                    $return .= '<li><a class="dropdown-item" href="' . route('inventory.accept', ['id' => base64_encode($data->id)]) . '">AllocateCustomer</a></li>';
                                    $return .= '<li><a class="dropdown-item" href="' . route('dealer.accept', ['id' => base64_encode($data->id)]) . '">AllocateDealer</a></li>';
                                }
    
                                $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                                <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                                <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>';
                            }
                       $return .= '</ul>';
                        }
                    }

                    $return .= '</div>';

                    return $return;
                })
                ->editColumn('booking_date', function($data) {
                            return (!empty($data->booking_date))
                                ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y')
                                : '--';
                        })
                ->editColumn('status', function ($data) {
                    if ($data->status == 'active') {
                        return '<span class="badge badge-pill badge-success">Active</span>';
                    } else if ($data->status == 'inactive') {
                        return '<span class="badge badge-pill badge-warning">Inactive</span>';
                    } else if ($data->status == 'deleted') {
                        return '<span class="badge badge-pill badge-danger">Deleted</span>';
                    } else if ($data->status == 'pdi_hold') {
                        return '<span class="badge badge-pill badge-info">PDI Hold</span>';
                    } else if ($data->status == 'sold') {
                        return '<span class="badge badge-pill badge-danger">Sold</span>';
                    } else if ($data->status == 'allocated') {
                        return '<span class="badge badge-pill badge-info">AllocatedCustomer</span>';
                    }else if ($data->status == 'allocatedDealer') {
                        return '<span class="badge badge-pill badge-info">AllocatedDealer</span>';
                    }  else if ($data->status == 'deallocated') {
                        return '<span class="badge badge-pill badge-info">Deallocated</span>';
                    } elseif ($data->status == 'invoice_create') {
                        return '<span class="badge badge-pill badge-success">Invoice Created</span>';
                    }else {
                        return '-';
                    }
                })
                ->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('obb.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('car_name', false)) {
                        $query->where('cm.name', 'like', "%" . request()->get("car_name") . "%");
                    }
                    if (request()->get('varient_name', false)) {
                        $query->where('cv.name', 'like', "%" . request()->get("varient_name") . "%");
                    }
                    if (request()->get('branch', false)) {
                        $query->where('b.name', 'like', "%" . request()->get("branch") . "%");
                    }
                    if (request()->get('ex_showroom_price', false)) {
                        $query->where('i.ex_showroom_price', 'like', "%" . request()->get("ex_showroom_price") . "%");
                    }
                    if (request()->get('purchase_price', false)) {
                        $query->where('i.purchase_price', 'like', "%" . request()->get("purchase_price") . "%");
                    }
                    if (request()->get('kin_margin', false)) {
                        $query->where('i.kin_margin', 'like', "%" . request()->get("kin_margin") . "%");
                    }
                    if (request()->get('fuel_type', false)) {
                        $query->where('fule_type.title', 'like', "%" . request()->get("fuel_type") . "%");
                    }
                    if (request()->get('vin_number', false)) {
                        $query->where('i.vin_number', 'like', "%" . request()->get("vin_number") . "%");
                    }
                    if ($obfCount = request()->get('obf_count')) {
                        $query->havingRaw('count(obb.id) = ?', [$obfCount]);
                    }
                    if (request()->get('customer_name', false)) {
                        $query->where('obf.customer_name', 'like', "%" . request()->get("customer_name") . "%");
                    }
                    if (request()->get('remark', false)) {
                        $query->where('i.remark', 'like', "%" . request()->get("remark") . "%");
                    }
                    if (request()->get('aging_days', false)) {
                        $query->where('i.aging_days', 'like', "%" . request()->get("aging_days") . "%");
                    }
                    if (request()->get('inventory_type', false)) {
                        $query->where('i.inventory_type', 'like', "%" . request()->get("inventory_type") . "%");
                    }
                    if (request()->get('invoice_no',false)) {
                        $query->where('orders.invoice_no', "like", "%".request()->get("invoice_no")."%");
                    }
                    if (request()->get('invoice_date',false)) {
                        $query->where('orders.invoice_date', "like", "%".request()->get("invoice_date")."%");
                    }
                    if (request()->get('status', false)) {
                        $query->where('i.status', 'like', "%" . request()->get("status") . "%");
                    }
                })
                ->make(true);
        }
        return view('inventory.index');
    }
    /** index */
    public function car_allocate_delearlist(Request $request)
    {
        if ($request->ajax()) {
            
            $data = DB::table('inventory as i')
                ->select('i.id', 'i.delear_id','i.name', 'b.name as branch', 'i.veriant','i.inventory_type','i.ex_showroom_price', 'i.status','i.aging_days', 'cv.name as varient_name', 'cm.name as car_name','i.vin_number',DB::raw('count(obf.id) as obf_id'),DB::raw('(CASE 
                        WHEN i.status = "allocated" THEN obf.customer_name                         
                        END) AS customer_name'),'delears.dealer_name as delear_name','i.purchase_price','i.kin_margin','i.manufacturing_year', 'fule_type.title as fuel_type', DB::raw("CASE WHEN orders.invoice_no IS NOT NULL AND orders.invoice_date IS NOT NULL THEN orders.invoice_no ELSE '---' END as invoice_no"))
                ->leftjoin('branches as b', 'b.id', 'i.branch_id')
                ->leftjoin('products', 'i.name', 'products.id')
                ->leftjoin('dealer_management as delears', 'delears.id', 'i.delear_id')
                ->leftjoin('car_model as cm', 'cm.id', 'products.car_model')
                ->leftjoin('car_varient as cv', 'cv.id', 'products.veriant')
                ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
                ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
                ->leftJoin('obf','obf.product_id','=','i.name')
                // ->leftjoin('orders','orders.obf_id','=','obf.id')
                ->leftjoin('orders','orders.inventory_id','=','i.id')
                ->leftjoin('fule_type','fule_type.id','=','i.fuel_type')
                ->groupBy('i.id')
                ->where('i.status',"allocatedDealer")
                ->orderBy('i.id', 'desc');
                // ->get();    
         
            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($data) {
                    $return = '<div class="btn-group">';

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

                    if (auth()->user()->can('inventory-edit')) {
                        if ($data->status == 'allocated') {
                            $return .= '';
                        }else{
                            $return .= '<a href="' . route('inventory.edit', ['id' => base64_encode($data->id)]) . '" class="btn btn-default btn-xs">
                                <i class="fa fa-edit"></i>
                                </a> &nbsp;';

                        }
                    }

                    if (auth()->user()->can('inventory-delete')) {
                        if ($data->status == 'pdi_hold') {
                            $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">';

                            $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                                                        <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                                                        <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                                                    </ul>';
                        } else if ($data->status == 'allocated' || $data->status == 'allocatedDealer') {
                            //$return .= '';

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


                                $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Deallocated</a></li>';
                                    //Active
                              
                             $return .= '</ul>';

                        } else {
                            $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">';

                            if ($data->status == 'active') {
                                $return .= '<li><a class="dropdown-item" href="' . route('inventory.accept', ['id' => base64_encode($data->id)]) . '">AllocateCustomer</a></li>';
                                $return .= '<li><a class="dropdown-item" href="' . route('dealer.accept', ['id' => base64_encode($data->id)]) . '">AllocateDealer</a></li>';
                            }

                            $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                            <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                            <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                        </ul>';
                        }
                    }

                    $return .= '</div>';

                    return $return;
                })
                ->editColumn('status', function ($data) {
                    if ($data->status == 'active') {
                        return '<span class="badge badge-pill badge-success">Active</span>';
                    } else if ($data->status == 'inactive') {
                        return '<span class="badge badge-pill badge-warning">Inactive</span>';
                    } else if ($data->status == 'deleted') {
                        return '<span class="badge badge-pill badge-danger">Deleted</span>';
                    } else if ($data->status == 'pdi_hold') {
                        return '<span class="badge badge-pill badge-info">PDI Hold</span>';
                    } else if ($data->status == 'sold') {
                        return '<span class="badge badge-pill badge-danger">Sold</span>';
                    } else if ($data->status == 'allocatedCustomer') {
                        return '<span class="badge badge-pill badge-info">AllocatedCustomer</span>';
                    }else if ($data->status == 'allocatedDealer') {
                        return '<span class="badge badge-pill badge-info">AllocatedDealer</span>';
                    }  else if ($data->status == 'deallocated') {
                        return '<span class="badge badge-pill badge-info">Deallocated</span>';
                    } else {
                        return '-';
                    }
                })
                ->rawColumns(['action', 'status'])
                ->filter(function ($query) {
                    if (request()->get('car_name', false)) {
                        $query->where('cm.name', 'like', "%" . request()->get("car_name") . "%");
                    }
                    if (request()->get('varient_name', false)) {
                        $query->where('cv.name', 'like', "%" . request()->get("varient_name") . "%");
                    }
                    if (request()->get('branch', false)) {
                        $query->where('b.name', 'like', "%" . request()->get("branch") . "%");
                    }
                    if (request()->get('ex_showroom_price', false)) {
                        $query->where('i.ex_showroom_price', 'like', "%" . request()->get("ex_showroom_price") . "%");
                    }
                    if (request()->get('purchase_price', false)) {
                        $query->where('i.purchase_price', 'like', "%" . request()->get("purchase_price") . "%");
                    }
                    if (request()->get('kin_margin', false)) {
                        $query->where('i.kin_margin', 'like', "%" . request()->get("kin_margin") . "%");
                    }
                    if (request()->get('fuel_type', false)) {
                        $query->where('fule_type.title', 'like', "%" . request()->get("fuel_type") . "%");
                    }
                    if (request()->get('vin_number', false)) {
                        $query->where('i.vin_number', 'like', "%" . request()->get("vin_number") . "%");
                    }
                    if (request()->get('delear_name', false)) {
                        $query->where('delears.dealer_name', 'like', "%" . request()->get("delear_name") . "%");
                    }
                    if (request()->get('aging_days', false)) {
                        $query->where('i.aging_days', 'like', "%" . request()->get("aging_days") . "%");
                    }
                    if (request()->get('inventory_type', false)) {
                        $query->where('i.inventory_type', 'like', "%" . request()->get("inventory_type") . "%");
                    }
                    if (request()->get('invoice_no',false)) {
                        $query->where('orders.invoice_no', "like", "%".request()->get("invoice_no")."%");
                    }
                    if (request()->get('status', false)) {
                        $query->where('i.status', 'like', "%" . request()->get("status") . "%");
                    }
                })
                ->make(true);
        }
        return view('inventory.car_allocate_delearlist');
    }
    
    /** create */
    public function create(Request $request)
    {
        $categories = Category::select('id', 'name')->where(['status' => 'active'])->get();
        // $branches = Branch::select('id', 'name')->where(['status' => 'active'])->get();

        //branch selection
        $branch = Branch::select('*');
        if(!empty(auth()->user()->branch) && auth()->user()->branch != '' && auth()->user()->branch != NULL){
            $branch_arr = explode(',', auth()->user()->branch);
            if(!empty($branch_arr)){
                $branch = $branch->whereIn('id',$branch_arr);    
            }
        }                        
        $branch = $branch->where(['status' => 'active'])->get(); 
        //branch selection
        $fuel_type = Fuletype::where(['status'=>'active'])->get();
        // $data = Carmodel::select('car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
        //             ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
        //             ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
        //             ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
        //             ->where('car_model.status', '=', 'active')
        //             ->get();

        $data = 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')
                        ->get();

        $Carmodel_arr = Carmodel::where(['status' => 'active'])->get();  

        return view('inventory.create')->with(['categories' => $categories, 'branches' => $branch, 'data'=>$data,'Carmodel_arr'=>$Carmodel_arr,'fuel_type'=>$fuel_type]);
    }
    /** create */
    
    /**carvarient */
    public function carvarient(Request $request){ 
            $id = ($request->id);

        //   $data = Carmodel::select('car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
        //             ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
        //             ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
        //             ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
        //             ->where('car_model.id', '=', $id)
        //             ->get();

             $data = 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', 'pm.basic as ex_showroom_price', 'pm.created_at')
                    ->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('pricelist_master', 'pricelist_master.car_variant', 'products.veriant')
                    ->leftJoin('pricelist_master as pm', function($join){
                        $join->on('pm.car_variant', '=', 'products.veriant')
                             ->where('pm.status', 'active');
                    }) 
                    ->where('products.status', '=', 'active')
                    ->where('products.id', '=', $id)
                    ->orderBy('pm.created_at', 'desc') // Order by created_at in descending order
                    ->get();             
            return json_encode(array('status'=> true ,'data' => $data));
    }
    /** carvarient */
    
    /** insert */
    public function insert(InventoryRequest $request)
    {
        if ($request->ajax()) {
            return true;
        }

        // $validate = Validator::make($request->all(),[
        //     'vin_number' => 'required|string|string|unique:inventory',
        // ]);
        // $validate = Validator::make($request->all(), [
        //     'vin_number' => [
        //         'required',
        //         'string',
        //         'unique:inventory,vin_number,NULL,id,branch_id,' . $request->branch_id // Check uniqueness per branch
        //     ],
        // ]);
        $validate = Validator::make($request->all(), [
            'vin_number' => [
                'required',
                'string',
                Rule::unique('inventory', 'vin_number')
                    ->where(function ($query) use ($request) {
                        return $query->where('branch_id', $request->branch_id)
                                     ->where('status', '!=', 'sold'); // only block non-sold
                    }),
            ],
        ]);
        if ($validate->fails())
        {
            return redirect()->back()->withErrors($validate);
        }
        
        $dateFrom = Carbon::parse($request->kin_invoice_date); 
        //dd($dateFrom);
        $dateTo = Carbon::now();
        //dd($dateTo); 
        $days = $dateFrom->diffInDays($dateTo);    
        //dd($days);
        /*$data = [
            'name' => $request->name ?? NULL,
            'branch_id' => $request->branch_id ?? NULL,
            'key_number' => $request->key_number ?? NULL,
            'engine_number' => $request->engine_number ?? NULL,
          //  'chassis_number' => $request->chassis_number ?? NULL,
            'vin_number' => $request->vin_number ?? NULL,
            'ex_showroom_price' => $request->ex_showroom_price ?? NULL,
            'kin_invoice_date' => $request->kin_invoice_date ?? NULL,
             'manufacturing_year' => $request->manufacturing_year ?? NULL,
            'aging_days'=> $days ?? NULL,
            'purchase_price' =>$request->purchase_price ?? NULL,
            'kin_margin' =>$request->kin_margin ?? NULL,
            'fuel_type' =>$request->fuel_type ?? NULL,
            'inventory_type' =>$request->inventory_type ?? NULL,
            'remark' =>$request->remark ?? NULL,
            'status' => 'active',
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id
        ];*/
        $data = [
            'branch_id' => $request->branch_id ?? NULL,
            'fuel_type' =>$request->fuel_type ?? NULL,
            'veriant' =>$request->veriant ?? NULL,
            'name' => $request->name ?? NULL,
            'exterior_color' =>$request->exterior_color ?? NULL,
            'interior_color' =>$request->interior_color ?? NULL,
            'kin_invoice_no' =>$request->kin_invoice_no ?? NULL,
            'kin_invoice_date' => $request->kin_invoice_date ?? NULL,
            'manufacturing_year' => $request->manufacturing_year ?? NULL,
            'key_number' => $request->key_number ?? NULL,
            'engine_number' => $request->engine_number ?? NULL,
            'vin_number' => $request->vin_number ?? NULL,
            'ex_showroom_price' => $request->ex_showroom_price ?? NULL,
            'purchase_price' =>$request->purchase_price ?? NULL,
            'kin_margin' =>$request->kin_margin ?? NULL,
            'inventory_type' =>$request->inventory_type ?? NULL,
            'remark' =>$request->remark ?? NULL,
            'offer_applicable' => $request->offer_applicable ?? Null,
            'status' => 'active',
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id,
            'aging_days'=> $days ?? NULL,  
        ];

        $last_id = Inventory::insertGetId($data);
        
        $crud = [
            'module_nm' => 'inventory',
            'module_id' => $last_id,
            'status' => 'Inventory Create',
            'remark' => $request->remark,
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
        ];
        \DB::table('logs')->insert($crud);

        if ($last_id)
            return redirect()->route('inventory')->with('success', 'Record inserted successfully');
        else
            return redirect()->back()->with('error', 'Failed to insert record')->withInput();
    }
    /** insert */

    /** view */
    public function view(Request $request)
    {
        $id = base64_decode($request->id);

        $categories = Category::select('id', 'name')->where(['status' => 'active'])->get();
        $branches = Branch::select('id', 'name')->where(['status' => 'active'])->get();
        $icolor = Interiorcolor::select('id', 'name')->where(['status' => 'active'])->get();
        $ecolor = Exteriorcolor::select('id', 'name')->where(['status' => 'active'])->get();
        $carvarient = Carvarient::select('id', 'name')->where(['status' => 'active'])->get();
        //$carmodel = Carmodel::select('id', 'name')->where(['status' => 'active'])->get();
        
        $fuel_type = Fuletype::where(['status'=>'active'])->get();
        $data = Inventory::select('inventory.*','fule_type.title')->leftjoin('fule_type','fule_type.id','=','inventory.fuel_type')->where(['inventory.id' => $id])->first();

            $carmodel = 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')
                ->get();
                
            $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.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','=','obf.product_id')
                    ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
                    ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
                    ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
                    ->where('obf.id', '=', $id)  
                    ->first();

        return view('inventory.view')->with(['data' => $data, 'branches' => $branches, 'categories' => $categories, 'icolor' => $icolor, 'ecolor' => $ecolor, 'Cardata' => $Cardata, 'carmodel' => $carmodel,'fuel_type'=>$fuel_type]);
    }
    /** view */

    /** edit */
    public function edit(Request $request)
    {
        $id = base64_decode($request->id);
        $categories = Category::select('id', 'name')->where(['status' => 'active'])->get();
        // $branches = Branch::select('id', 'name')->where(['status' => 'active'])->get();

        //branch selection
        $branch = Branch::select('*');
        if(!empty(auth()->user()->branch) && auth()->user()->branch != '' && auth()->user()->branch != NULL){
            $branch_arr = explode(',', auth()->user()->branch);
            if(!empty($branch_arr)){
                $branch = $branch->whereIn('id',$branch_arr);    
            }
        }                        
        $branch = $branch->where(['status' => 'active'])->get(); 
        //branch selection
        
        $fuel_type = Fuletype::where(['status'=>'active'])->get();
        $data = Inventory::select('inventory.*','fule_type.title','fule_type.id as fuel_id')->leftjoin('fule_type','fule_type.id','=','inventory.fuel_type')->where(['inventory.id' => $id])->first();

        // $Carmodel = Carmodel::select('car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
        //             ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
        //             ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
        //             ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
        //             ->where('car_model.status', '=', 'active')
        //             ->get();

        $Carmodel = 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')
                ->get();
                
        $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.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','=','obf.product_id')
                    ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
                    ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
                    ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
                    ->where('obf.id', '=', $id)  
                    ->first();

        $Product_data = Product::select('products.*','fule_type.id','fule_type.title')->leftjoin('car_varient','car_varient.id','=','products.veriant')->leftjoin('fule_type','fule_type.id','=','car_varient.fule_type')->where('products.id',$data->name)->where('products.status', '=', 'active')->first(); 
        /*if($Product_data == null){
            return redirect()->back()->with('error', 'Failed to edit record');
        }*/
        $Carmodel_arr = Carmodel::where(['status' => 'active'])->get();  
        // $Carvarient = Carvarient::where(['status' => 'active','car_model'=>$Product_data->car_model,'fule_type'=>$data->fuel_id])->get(); 
        
        $Carvarient = Carvarient::where([
            'car_model' => $Product_data->car_model ?? '',
            'fule_type'=>$data->fuel_id,
            'car_varient.status' => 'active'
        ])
        ->leftJoin('tex_master', 'car_varient.tex_master_id', '=', 'tex_master.id')
        ->where('tex_master.status', 'active')
        ->select('car_varient.id', 'car_varient.name', 'tex_master.gst')
        ->get();
        
        return view('inventory.edit')->with(['data' => $data, 'branches' => $branch, 'categories' => $categories, 'Carmodel'=>$Carmodel, 'Cardata' => $Cardata,'Carmodel_arr' => $Carmodel_arr,'Product_data' => $Product_data,'fuel_type'=>$fuel_type,'Carvarient'=>$Carvarient]);
    }
    /** edit */
    
    
    /** branchwisestock */
    public function BranchWiseStock($branch,Request $request)
    {
        if ($request->ajax()) {
            $data = DB::table('inventory as i')
                ->select('i.id', 'i.name', 'b.name as branch', 'i.veriant', 'i.ex_showroom_price', 'i.status')
                ->where('b.name',$branch)
                ->leftjoin('branches as b', 'b.id', 'i.branch_id')
                ->orderBy('i.id', 'desc')
                ->get();

            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($data) {
                    $return = '<div class="btn-group">';

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

                    if (auth()->user()->can('inventory-edit')) {
                        if ($data->status == 'sold') {
                            $return .= '';
                        }else{
                            $return .= '<a href="' . route('inventory.edit', ['id' => base64_encode($data->id)]) . '" class="btn btn-default btn-xs">
                                <i class="fa fa-edit"></i>
                                </a> &nbsp;';

                        }
                    }

                    if (auth()->user()->can('inventory-delete')) {
                        if ($data->status == 'pdi_hold') {
                            $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">';

                            $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                                                        <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                                                        <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                                                    </ul>';
                        } else if ($data->status == 'sold') {
                            $return .= '';
                        } else {
                            $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">';

                            if ($data->status == 'active') {
                                $return .= '<li><a class="dropdown-item" href="' . route('inventory.accept', ['id' => base64_encode($data->id)]) . '">Assign</a></li>';
                            }

                            $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                            <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                            <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                        </ul>';
                        }
                    }

                    $return .= '</div>';

                    return $return;
                })
                ->editColumn('status', function ($data) {
                    if ($data->status == 'active') {
                        return '<span class="badge badge-pill badge-success">Active</span>';
                    } else if ($data->status == 'inactive') {
                        return '<span class="badge badge-pill badge-warning">Inactive</span>';
                    } else if ($data->status == 'deleted') {
                        return '<span class="badge badge-pill badge-danger">Deleted</span>';
                    } else if ($data->status == 'pdi_hold') {
                        return '<span class="badge badge-pill badge-info">PDI Hold</span>';
                    } else if ($data->status == 'sold') {
                        return '<span class="badge badge-pill badge-danger">Sold</span>';
                    } else {
                        return '-';
                    }
                })
                ->rawColumns(['action', 'status'])
                ->make(true);
        }
        return view('inventory.branchwiseinventory');
    }
    /** branchwisestock */
    
    
    /** inventorystock */
    public function inventorystock(Request $request)
    {
        if ($request->ajax()) {
            $data = DB::table('inventory as i')
                
                ->select('b.name as branch',DB::raw('count(i.id) as total_stock'))
                ->join('branches as b', 'b.id', 'i.branch_id')
               
                ->groupby('b.id')
               
                ->get();

            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($data) {
                    $return = '<div class="btn-group">';

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

                    // if (auth()->user()->can('inventory-edit')) {
                    //     if ($data->status == 'sold') {
                    //         $return .= '';
                    //     }else{
                    //         $return .= '<a href="' . route('inventory.edit', ['id' => base64_encode($data->id)]) . '" class="btn btn-default btn-xs">
                    //             <i class="fa fa-edit"></i>
                    //             </a> &nbsp;';

                    //     }
                    // }

                    // if (auth()->user()->can('inventory-delete')) {
                    //     if ($data->status == 'pdi_hold') {
                    //         $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">';

                    //         $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                    //                                     <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                    //                                     <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                    //                                 </ul>';
                    //     } else if ($data->status == 'sold') {
                    //         $return .= '';
                    //     } else {
                    //         $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">';

                    //         if ($data->status == 'active') {
                    //             $return .= '<li><a class="dropdown-item" href="' . route('inventory.accept', ['id' => base64_encode($data->id)]) . '">Assign</a></li>';
                    //         }

                    //         $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                    //         <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                    //         <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                    //     </ul>';
                    //     }
                    // }

                    $return .= '</div>';

                    return $return;
                })
                // ->editColumn('status', function ($data) {
                //     if ($data->status == 'active') {
                //         return '<span class="badge badge-pill badge-success">Active</span>';
                //     } else if ($data->status == 'inactive') {
                //         return '<span class="badge badge-pill badge-warning">Inactive</span>';
                //     } else if ($data->status == 'deleted') {
                //         return '<span class="badge badge-pill badge-danger">Deleted</span>';
                //     } else if ($data->status == 'pdi_hold') {
                //         return '<span class="badge badge-pill badge-info">PDI Hold</span>';
                //     } else if ($data->status == 'sold') {
                //         return '<span class="badge badge-pill badge-danger">Sold</span>';
                //     } else {
                //         return '-';
                //     }
                // })
                // ->rawColumns(['action', 'status'])
                ->make(true);
        }
        return view('inventory.branchstock');
    }
    /** inventorystock */

    /** update */
    public function update(InventoryRequest $request)
    {
        if ($request->ajax()) {
            return true;
        }
        //dd($request->all());
        // $data = [
        //     'name' => $request->name ?? NULL,
        //     'branch_id' => $request->branch_id ?? NULL,
        //     'key_number' => $request->key_number ?? NULL,
        //     'engine_number' => $request->engine_number ?? NULL,
        //     //'chassis_number' => $request->chassis_number ?? NULL,
        //     'vin_number' => $request->vin_number ?? NULL,
        //     'ex_showroom_price' => $request->ex_showroom_price ?? NULL,
        //     'kin_invoice_date' => $request->kin_invoice_date ?? NULL,
        //     'manufacturing_year' => $request->manufacturing_year?? NULL,
        //     'purchase_price' =>$request->purchase_price ?? NULL,
        //     'kin_margin' =>$request->kin_margin ?? NULL,
        //     'fuel_type' =>$request->fuel_type ?? NULL,
        //     'inventory_type' =>$request->inventory_type ?? NULL,
        //     'remark' =>$request->remark ?? NULL,
        //     'updated_at' => date('Y-m-d H:i:s'),
        //     'updated_by' => auth('sanctum')->user()->id
        // ];
        $dateFrom = Carbon::parse($request->kin_invoice_date);
        $dateTo = Carbon::now();
        $days = $dateFrom->diffInDays($dateTo); 
        $data = [
            'branch_id' => $request->branch_id ?? NULL,
            'fuel_type' =>$request->fuel_type ?? NULL,
            'veriant' =>$request->veriant ?? NULL,
            'name' => $request->name ?? NULL,
            'exterior_color' =>$request->exterior_color ?? NULL,
            'interior_color' =>$request->interior_color ?? NULL,
            'kin_invoice_no' =>$request->kin_invoice_no ?? NULL,
            'kin_invoice_date' => $request->kin_invoice_date ?? NULL,
            'manufacturing_year' => $request->manufacturing_year ?? NULL,
            'key_number' => $request->key_number ?? NULL,
            'engine_number' => $request->engine_number ?? NULL,
            'vin_number' => $request->vin_number ?? NULL,
            'ex_showroom_price' => $request->ex_showroom_price ?? NULL,
            'purchase_price' =>$request->purchase_price ?? NULL,
            'kin_margin' =>$request->kin_margin ?? NULL,
            'inventory_type' =>$request->inventory_type ?? NULL,
            'remark' =>$request->remark ?? NULL,
            'offer_applicable' => $request->offer_applicable ?? Null,
            'status' => 'active',
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id,
            'aging_days'=> $days ?? NULL,  
        ];
        
        $update = Inventory::where(['id' => $request->id])->update($data);
        
        $crud = [
            'module_nm' => 'inventory',
            'module_id' => $request->id,
            'status' => 'Inventory Update',
            'remark' => $request->remark,
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
        ];
        \DB::table('logs')->insert($crud);

        if ($update)
            return redirect()->route('inventory')->with('success', 'Record updated successfully');
        else
            return redirect()->back()->with('error', 'Failed to update record')->withInput();
    }
    /** update */

    /** change-status */
    public function change_status(Request $request)
    {
        if (!$request->ajax()) {
            exit('No direct script access allowed');
        }

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

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

        if (!empty($data)) {
            // DB::enableQueryLog();
           
            $update = Inventory::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
            $crud = [
                'module_nm' => 'inventory',
                'module_id' => $id,
                'status' => $request->status,
                'remark' => 'Status Updated',
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
            ];
            \DB::table('logs')->insert($crud);
            OBF::select('id')->where(['inventory_id' => $data->id])->update(['inventory_id' => null]); 
                // dd(DB::getQueryLog());


            if($request->status == 'active'){
               /* $inventory = Inventory::where(['id' => $id])->update(['status' => 'active', 'updated_by' => auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]);

                if (!$inventory)
                    return redirect()->back()->with(['error' => 'something went wrong, please try later1']);*/

                $obf_data = OBF::select('id')->where(['inventory_id' => $id])->first();

                // var_dump($obf_data->id);

                if(!empty($obf_data)){
                    if($obf_data->id != NULL){
                        $obf = OBF::where(['id' => $obf_data->id])->update(['status' => 'account_accepted', 'updated_by' => auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]);
                        $crud = [
                            'module_nm' => 'inventory',
                            'module_id' => $id,
                            'status' => 'account_accepted',
                            'remark' => 'Car Allocation - Update Status',
                            'created_at' => date('Y-m-d H:i:s'),
                            'created_by' => auth()->user()->id,
                        ];
                        \DB::table('logs')->insert($crud);

                        if (!$obf)
                            return redirect()->back()->with(['error' => 'something went wrong, please try later']);

                        $order = Order::where(['obf_id' => $obf_data->id])->update(['status' => 'waiting', 'updated_by' => auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]);
                        
                        $crud = [
                            'module_nm' => 'inventory',
                            'module_id' => $id,
                            'status' => 'waiting',
                            'remark' => 'Car Allocation - Update Status',
                            'created_at' => date('Y-m-d H:i:s'),
                            'created_by' => auth()->user()->id,
                        ];
                        \DB::table('logs')->insert($crud);
                        
                        if (!$order)
                            return redirect()->back()->with(['error' => 'something went wrong, please try later3']);    
                    }
                }
                
            }

           /* var_dump($update);

            die('stop');*/


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

    /** accept */
    public function accept(Request $request, $id = '')
    {   
      
        $id_2 = base64_decode($id);

        if (isset($id) && $id != '' && $id != null){
            $id = base64_decode($id);
        }else{
            return redirect()->back()->with('error', 'something went wrong');
        }
        
        $product = Inventory::select('inventory.id as i_id','inventory.name as i_name','inventory.vin_number as vin_number','inventory.manufacturing_year as manufacturing_year','car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
            ->leftJoin('products','products.id','=','inventory.name')
            ->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('inventory.id', '=', $id)
            ->first();

        if (!empty($product)) {
            $product = $product->toArray();

            $obf_data_product = Obf::select('obf.id')->where('obf.product_id', $product['i_name'])->first();
            if(empty($obf_data_product) && $obf_data_product == NULL){
               $message = "No OBF Found With this Car";
               return redirect()->route('inventory')->with('error', $message);   
            }

            $obf_data_product = Obf::select('obf.id')->where('obf.product_id', $product['i_name'])->where(['obf.status' => 'obf_accepted'])/*->orWhere(['obf.status' => 'account_accepted'])*/->orWhere(['obf.status' => 'deal_generated'])->first();
            if(empty($obf_data_product) && $obf_data_product == NULL){
               $message = "Please Create Cash Receipt First";
               return redirect()->route('inventory')->with('error', $message);   
            }
            
            $obf_data_product = Obf::select('obf.id')->where('obf.product_id', $product['i_name'])->where(['obf.status' => 'account_accepted'])->orWhere(['obf.status' => 'deal_generated'])->first();
           
            if(empty($obf_data_product) && $obf_data_product == NULL){
               $message = "Please Generate Receipt First";
               return redirect()->route('inventory')->with('error', $message);   
            }
            $branchIds = explode(',', auth()->user()->branch);
            
            $data = Obf::select(
                 'obf.id',
                 'obf.booking_date',
                 'obf.customer_name', 
                 'obf.product_id as product_id',
                 'branches.id as branch_id',
                 'branches.name as branch_name',
                 'obf.on_road_price',
                //  DB::raw('ROUND(obf.on_road_price - SUM(cash_receipt.amount)) as due_amount'),
                //  DB::raw('ROUND(SUM(cash_receipt.amount)) as received_amount')
            )
            ->leftJoin('branches','branches.id','=','obf.branch_id')
            // ->leftJoin('cash_receipt', 'cash_receipt.obf_id', '=', 'obf.id')
            ->where('obf.product_id', $product['i_name'])
            ->whereIn('obf.branch_id', $branchIds)
            ->where('obf.status','!=','delete')
            ->whereNull('obf.inventory_id')
            ->get();
            
            if ($data->isNotEmpty()) {
                return view('inventory.accept')->with(['data' => $data, 'id' => $id, 'product' => $product]);
            } else {
                return redirect()->route('inventory')->with('error', 'No Data Found In User!');
            }
        } else {
            return redirect()->route('inventory')->with('error', 'No Data Found For This Car!');
        }


    }
    /** accept */

    /** accepted */
    public function accepted(InventoryAcceptRequest $request)
    {
        
        // if ($request->ajax()) {
        //     return true;
        // }
        DB::beginTransaction();
        try {
            //'active','inactive','deleted','pdi_hold','sold','allocated'


            $allocation_count = 0;

            $Inventory_data = Inventory::where(['id' => $request->id])->first();

            if(!empty($Inventory_data)){
                $allocation_count = $Inventory_data->allocation_count;
            }
            $allocation_count++;

            $inventory = Inventory::where(['id' => $request->id])->update(['allocation_count' => $allocation_count,'status' => 'allocated', 'updated_by' => auth()->user()->id,'allocation_date' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]);
            
            if (!$inventory)
                return redirect()->back()->with(['error' => 'something went wrong, please try later1']);
                
            $crud = [
                'module_nm' => 'inventory',
                'module_id' => $request->obf_id,
                'status' => 'allocated',
                'remark' => NULL,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
            ];
            \DB::table('logs')->insert($crud);

            $obf = OBF::where(['id' => $request->obf_id])->update(['inventory_id' => $request->id, 'status' => 'completed', 'updated_by' => auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]);
            if (!$obf)
                return redirect()->back()->with(['error' => 'something went wrong, please try later']);
            
            // $order = Order::where(['obf_id' => $request->obf_id])->update(['inventory_id' => $request->id, 'updated_by' => auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]);
            //'status' => 'delivered'
           $order = Order::where(['obf_id' => $request->obf_id])->exists();
            if (!$order){
                $datetime = date('Y-m-d H:i:s');
                $order_id = "Order_ID" . str_replace(['-', ' ', ':'], '', $datetime);   
                $obf = OBF::where(['id' => $request->obf_id])->first(); 
                $crud = [
                    'inventory_id' => $request->id,
                    'order_id' => $order_id,
                    'obf_id' => $obf->id,
                    'branch_id' => $obf->branch_id,
                    'pdi_reject_reason' => null,
                    'dealer_id' => null,
                    'dealer_gst' => null,
                    'dealer_pan_number' => null,
                    'bill_to' => null,
                    'address' => null,
                    'ship_to' => null,
                    'finance_name' => null,
                    'customer_gst' => null,
                    'customer_id' => null,
                    'invoice_no' => null,
                    'invoice_date' => null,
                    'phone_no' => null,
                    'pan_number' => null,
                    'place_of_supply' => null,
                    'product_name' => null,
                    'on_road_price' => null,
                    'discount_type' => null,
                    'discount' => null,
                    'selling_price' => null,
                    'igst' => null,
                    'cgst' => null,
                    'sgst' => null,
                    'compensation_cess' => null,
                    'total' => null,
                    'tcs_tax' => null,
                    'grand_total' => null,
                    'vin_number' => $Inventory_data->vin_number,
                    'chassis_number' => null,
                    'engine_number' => null,
                    'key_number' => null,
                    'hsn_code' => null,
                    'status' => 'waiting',
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id
                ];
                $order = Order::create($crud);
            } else {
                $order = Order::where(['obf_id' => $request->obf_id])->update(['inventory_id' => $request->id,'vin_number' => $Inventory_data->vin_number, 'updated_by' => auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]);
            }


            if($request->obf_id != ''){
                //notification insert

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

            DB::commit();
            return redirect()->route('inventory')->with(['success' => 'Assign completed']);
        } catch (\Throwable $th) {
            DB::rollback();
            var_dump($th);
            return redirect()->back()->with('error', 'something went wrong, please try again later2')->withInput();
        }
    }
    /** accepted */


      /** accept Dealer */
    public function acceptdealer(Request $request, $id = '')
    {   
        $id_2 = base64_decode($id);
        if (isset($id) && $id != '' && $id != null){
            $id = base64_decode($id);
        }else
            return redirect()->back()->with('error', 'something   went wrong');
        
           $product = Inventory::select('inventory.id as i_id','inventory.name as i_name','car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
                    ->leftJoin('products','products.id','=','inventory.name')
                    ->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('inventory.id', '=', $id)
                    ->first();

        if (!empty($product)) {
            $product = $product->toArray();

            $obf_data_product = Obf::select('obf.id')->where('obf.product_id', $product['i_name'])->first();

            $obf_data_product = Obf::select('obf.id')->where('obf.product_id', $product['i_name'])->where(['obf.status' => 'obf_accepted'])->orWhere(['obf.status' => 'account_accepted'])->first();

            $obf_data_product = Obf::select('obf.id')->where('obf.product_id', $product['i_name'])->where(['obf.status' => 'account_accepted'])->first();
        
            $obf_id = Obf::select('obf.id')
            ->join('inventory', function ($join) use ($product) {
                $join->on('obf.product_id', '=', DB::raw("'" . $product['i_name'] . "'"));
            })
            ->first();
            
            $data = Dealer::get(['id','dealer_name']);
            $branch_nm = Branch::whereNotIn('city', ['Junagadh', 'Mehsana', 'Kadi'])->get(['id', 'city']);

            if ($data->isNotEmpty()) {
                return view('inventory.acceptdealer')->with(['data' => $data, 'id' => $id, 'obf_id' => $obf_id, 'branch_nm' => $branch_nm]);
            } else {
                return redirect()->route('inventory')->with('error', 'No Data Found In User!');
            }
        } else {
            return redirect()->route('inventory')->with('error', 'No Data Found For This Car!');
        }


    }
    /** acceptDealer */

    public function accepteddealer(InventoryDealerAcceptRequest $request)
    {
        if ($request->ajax()) {
            return true;
        }
        DB::beginTransaction();
        try {

            $allocation_count = 0;

            $Inventory_data = Inventory::where(['id' => $request->id])->first();

            if(!empty($Inventory_data)){ 
                $allocation_count = $Inventory_data->allocation_count;
            }
            $allocation_count++;

            $inventory = Inventory::where(['id' => $request->id])->update(['delear_id'=>$request->dealer_id,'to_branch'=> $request->to_branch ? $request->to_branch : null,'allocation_count' => $allocation_count,'status' => 'allocatedDealer', 'updated_by' => auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]); 

            if (!$inventory){
                return redirect()->back()->with(['error' => 'Something Went Wrong, Inventory Data Not Update']);
            }
            
            $crud = [
                'module_nm' => 'inventory',
                'module_id' => $request->id,
                'status' => 'allocatedDealer',
                'remark' => NULL,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
            ];
            \DB::table('logs')->insert($crud);
            
            $orderExists = Order::where('dealer_id', $request->dealer_id)->where('vin_number',$Inventory_data->vin_number)->first();  
            if (!$orderExists) {
                $this->create_order($request->dealer_id, $request->order_obf_id, $request->id, $Inventory_data, $request->discount, $request->discount_type);
            } else {
                $obf = OBF::where(['id' => $request->order_obf_id])->update(['inventory_id' => $request->id, 'status' => 'completed', 'updated_by' => auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]);
                // $order = Order::where(['obf_id' => $request->obf_id])
                $order = Order::where(['id' => $orderExists->id])
                    ->update([
                        'inventory_id' => $request->id,
                        'dealer_id' => $request->dealer_id,
                        'updated_by' => auth()->user()->id,
                        'updated_at' => now(),
                    ]);   
                if(!$order){
                    return redirect()->back()->with(['error' => 'something went wrong, please try later3']);
                }            
            }

 
            if($request->obf_id != ''){
                //notification insert

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

            DB::commit();
            return redirect()->route('inventory')->with(['success' => 'Assign completed']);
        } catch (\Throwable $th) {
            DB::rollback();
            var_dump($th);
            return redirect()->back()->with('error', 'something went wrong, please try again later2')->withInput();
        }
    }
    
    /** acceptedDealer */
    
    // Create Order For Allocated Car To Dealer
    public function create_order($delear_id, $obf_id, $Inventory_id, $Inventory_data, $discount, $discount_type){
        $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();
        
        
        
        $product_name_get = 'Price of One  '.$product_data->car_name.' ** '.$product_data->varient_name.' '.$product_data->exterior_color.' '.$product_data->interior_color;
        
        $dealer_data = Dealer::where('id', $delear_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;
        
        $cess_tax = Texmaster::select('compensation_cess')->where('id', $product_data->tex_master_id)->where('status','active')->first();
        $cess_tax_percentage = $cess_tax->compensation_cess ?? 0; 
        
        $purchase_price = $Inventory_data->purchase_price;
        $gst_tax = Texmaster::select('gst')->where('id', $product_data->tex_master_id)->where('status','active')->first();
        $gst_percentage = $gst_tax->gst;
        
        $total_after_dis = 0;
        if($discount_type === 'discount_plus'){
            $total_after_dis = $purchase_price + $discount;
        } else if($discount_type === 'discount_minus'){
            $total_after_dis = $purchase_price - $discount;
        } else {
            $total_after_dis = $purchase_price; 
        }
        $gst_amount = ($total_after_dis * $gst_percentage) / 100;

        $cgst = 0; 
        $sgst = 0;
        $igst = 0;
        $total = 0;
        if($dealer_data->state == '7' || $dealer_data->state == 'gujarat') {
            $cgst = $gst_amount / 2;
            $sgst = $gst_amount / 2;
        } else {
            $igst = $gst_amount;
        }
        if($cess_tax_percentage > 0){
            $cess = (($purchase_price * $cess_tax_percentage) / 100) ?? 0;
        } else {
           $cess = 0; 
        }
        $discount = $discount ?? 0;
        if($discount_type === 'discount_plus'){
            $total = $purchase_price + $discount;
            $after_dis_total = $total + $cgst + $sgst + $igst + $cess;
        } else if($discount_type === 'discount_minus'){
            $total = $purchase_price - $discount;
            $after_dis_total = $total + $cgst + $sgst + $igst + $cess;
        } else {
            $total = $purchase_price;
            $after_dis_total = $purchase_price + $cgst + $sgst + $igst + $cess; 
        }
        
        $tcs = (($after_dis_total * 1) / 100) ?? 0; 
        $grand_total = $after_dis_total + $tcs;
        
        $datetime = date('Y-m-d H:i:s');
        $order_id = "Order_ID" . str_replace(['-', ' ', ':'], '', $datetime);
        $crud = [
            'inventory_id' => $Inventory_data->id,
            'order_id' => $order_id,
            'obf_id' => null,
            'branch_id' => $Inventory_data->branch_id,
            'pdi_reject_reason' => null,
            'dealer_id' => $delear_id,
            'dealer_gst' => $gst_percentage,
            'dealer_pan_number' => null,
            'bill_to' => $dealer_data->dealer_name,
            'address' => $dealer_data->dealer_address,
            'ship_to' => null,
            'finance_name' => null,
            'customer_gst' => null,
            'customer_id' => null,
            'invoice_no' => null,
            'invoice_date' => null,
            'phone_no' => $dealer_data->dealer_mobile_no,
            'pan_number' => null,
            'place_of_supply' => null,
            'product_name' => $product_name_get,
            'on_road_price' => $Inventory_data->purchase_price,
            'discount_type' => $discount_type ?? null,
            'discount' => $discount ?? null,
            'selling_price' => null,
            'igst' => $igst,
            'cgst' => $cgst,
            'sgst' => $sgst,
            'compensation_cess' => $cess,
            'total' => $total,
            'tcs_tax' => $tcs,
            'grand_total' => $grand_total,
            'vin_number' => $Inventory_data->vin_number,
            'chassis_number' => $Inventory_data->chassis_number,
            'engine_number' => $Inventory_data->engine_number,
            'key_number' => $Inventory_data->key_number,
            'hsn_code' => $product_data->hsn_code,
            'status' => 'all_payment_done',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
            'updated_by' => auth()->user()->id
        ];
        
        $order = Order::create($crud);
        $update_status = Inventory::where('id',$Inventory_data->id)->update(['status'=>'allocatedDealer']);
    }

    /** Import */
        public function import(Request $request){
           //dd(Excel::import(new ImportInventory, $request->file('file')->store('file')));
            if(Excel::import(new ImportInventory, $request->file('file')->store('file'))){
                return redirect()->route('inventory')->with('sucess' ,'File Imported Sucessfully');
            }else{
                return redirect()->route('inventory')->with('error' ,'Faild To Import File!');
            }
        }
    /** Import */
    
    /** Export */
        public function export(Request $request){
            if(isset($request->slug) && $request->slug != null){
                $slug = $request->slug;
            }else{
                $slug = 'all';
            }

            $name = 'Inventorys_'.Date('YmdHis').'.xlsx';
        
            try {
                return Excel::download(new ExportInventory($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
    /** Export */
    
    /* car_varient_asper_fueltype */
        public function car_varient_asper_fueltype(Request $request){
            $carmodel = $request->car_model;
            $fuel_type = $request->fuel_type;
            $data = [];
            $Carvarient_arr = [];
           /*  $query = Carvarient::select('id','name')->where('fule_type',$fuel_type)->where('car_model',$carmodel)->get();
           // dd($query);
            return view('inventory.car_varient_asper_fueltype')->with(['query'=>$query]);*/

            if($request->option_check == 'Carvarient'){
                // $Carvarient = Carvarient::select('car_varient.id','car_varient.name')->where(['car_model' => $carmodel,'fule_type'=>$fuel_type,'status' => 'active'])->get();
                $Carvarient = Carvarient::where([
                    'car_model' => $carmodel,
                    'fule_type'=>$fuel_type,
                    'car_varient.status' => 'active'
                ])
                ->leftJoin('tex_master', 'car_varient.tex_master_id', '=', 'tex_master.id')
                ->where('tex_master.status', 'active')
                ->select('car_varient.id', 'car_varient.name', 'tex_master.gst')
                ->get();
                
                foreach ($Carvarient as $value) {
                    $color_data = [];
                    $color_data['id'] = $value->id;
                    $color_data['name'] = $value->name . ' - ' . $value->gst . ' %';
                    $Carvarient_arr[] = $color_data;                    
                }  
            }
            $data['Carvarient_arr'] = $Carvarient_arr;  

            return json_encode(array('status'=> true ,'data' => $data));
        }
        
        /* car_varient_asper_fueltype */
        
        public function viewlogs(Request $request)
        {
            $id = $request->id;

            $product = Inventory::select(
                    'inventory.id as i_id',
                    'inventory.name as i_name',
                    'inventory.vin_number as vin_number',
                    'inventory.manufacturing_year as manufacturing_year',
                    'car_model.name as car_name',
                    'car_model.id as car_id',
                    'car_varient.name as varient_name',
                    'exteriorcolor.name as exterior_color',
                    'interiorcolor.name as interior_color'
                )
                ->leftJoin('products', 'products.id', '=', 'inventory.name')
                ->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('inventory.id', '=', $id)
                ->first();
        
            if (!$product) {
                abort(404, 'Inventory not found');
            }
        
            $crud = [
                'module_nm'   => 'inventory',
                'module_id'   => $id,
                'status'      => $request->status,
                'created_at'  => now(),
                'created_by'  => auth()->id(),
            ];
        
            \DB::table('logs')->insert($crud);
        
            $logs_data = \DB::table('logs')
                ->leftJoin('users', 'users.id', '=', 'logs.created_by')
                ->select('logs.*', \DB::raw("CONCAT(users.first_name, ' ', users.last_name) as user_name"))
                ->where('logs.module_nm', 'inventory')
                ->where('logs.module_id', $id)
                ->orderBy('logs.created_at', 'desc')
                ->get();
        
            return view('logs.viewlog', compact('product', 'logs_data'));
        }
}
