<?php

namespace App\Http\Controllers;

use App\Exports\ExportInventory;
use App\Http\Requests\InventoryAcceptRequest;
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\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;

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', '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'),'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','obf.product_id','=','i.name')
                ->leftjoin('fule_type','fule_type.id','=','i.fuel_type')
                ->groupBy('i.id')//->groupBy('i.name')
                ->orderBy('i.id', 'desc')
                
                ->where('i.status','!=',"allocatedDealer")
                ->where('i.status','!=','deleted')->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') {
                            //$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'])
                ->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')
                ->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('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'])
                ->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'/*, 'pricelist_master.ex_showroom_price'*/, 'pricelist_master.basic as ex_showroom_price')
                    ->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')
                    ->where('products.status', '=', 'active')
                    ->where('products.id', '=', $id)
                    ->orderBy('pricelist_master.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',
        ]);
        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,
            '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);

        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(); 
        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
        // ];
        $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,
            '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);

        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]);
                // 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')]);

                        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')]);
                        
                        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);
       // dd($id_2); 
        if (isset($id) && $id != '' && $id != null){
            $id = base64_decode($id);
           // dd($id);
        }else
            return redirect()->back()->with('error', 'something went wrong');
        /*$product =    ::select('products.car_model', 'products.veriant', 'products.exterior_color', 'products.interior_color','car_model.id','car_varient.name','interior_color.interior_color','exterior_color.exterior_color')
        ->leftjoin('inventory',  function($join)
        {
            $join->on('car_model.id', '=', 'products.car_model');
            $join->on('car_varient.name', '=', 'products.veriant');
            $join->on('interior_color.interior_color', '=', 'products.interior_color');
            $join->on('exterior_color.exterior_color', '=', 'products.exterior_color');
        })
        ->where(['inventory.id' => $id])->first();*/
        
           $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();
            //dd($product->i_name);

        if (!empty($product)) {
            $product = $product->toArray();

            //new code
            //For OBF -selection
            $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  '.$product['car_name'].' | '.$product['varient_name'].'   ('.$product['exterior_color'].' , '.$product['interior_color'].' )';
               $message = "No OBF Found With this Car";
               return redirect()->route('inventory')->with('error', $message);   
            }
            
            //For OBF- cash receipt creation
            $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();
            //dd($obf_data_product);
            if(empty($obf_data_product) && $obf_data_product == NULL){
               //$message = 'No OBF Found With  '.$product['car_name'].' | '.$product['varient_name'].'   ('.$product['exterior_color'].' , '.$product['interior_color'].' )';
               $message = "Please Create Cash Receipt First";
               return redirect()->route('inventory')->with('error', $message);   
            }
            //For OBF selection
            $obf_data_product = Obf::select('obf.id')->where('obf.product_id', $product['i_name'])->where(['obf.status' => 'account_accepted'])->first();
            //dd($obf_data_product);
           
           if(empty($obf_data_product) && $obf_data_product == NULL){
               //$message = 'No OBF Found With  '.$product['car_name'].' | '.$product['varient_name'].'   ('.$product['exterior_color'].' , '.$product['interior_color'].' )';
               $message = "Please Generate Receipt First";
               return redirect()->route('inventory')->with('error', $message);   
           }
            /*$order = Order::select('id')->where('obf_id', $obf_data_product->id)->first();
           if(empty($order) && $order == NULL){
                $message = "Please Generate Receipt First";
                return redirect()->route('inventory')->with('error', $message);   
           }*/
           
           //end
                  
         /*   $obf_data = Obf::select('obf.id')->where(['obf.status' => 'account_accepted'])->where('obf.product_id', $product['i_name'])->first();
                        
            $order = '';
             if (!empty($obf_data)) {
                $order = Order::select('id')->where('obf_id', $obf_data->id)->first();
            }

           / * var_dump($order);
            die('stop');* /
            
            if($order == ''){
                return redirect()->route('inventory')->with('error', 'Please Generate Receipt First ');
            }*/
        
          
             $data = Obf::select('obf.id','obf.customer_name', 'obf.product_id as product_id')->where(['obf.status' => 'account_accepted'])->where('obf.product_id', $product['i_name'])->get();

            if ($data->isNotEmpty()) {
                return view('inventory.accept')->with(['data' => $data, 'id' => $id]);
            } 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, 'updated_at' => date('Y-m-d H:i:s')]);

            if (!$inventory)
                return redirect()->back()->with(['error' => 'something went wrong, please try later1']);

            $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'
           
            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();
        }
    }
    /** accepted */


      /** accept Dealer */
    public function acceptdealer(Request $request, $id = '')
    {   
      
        $id_2 = base64_decode($id);
       // dd($id_2); 
        if (isset($id) && $id != '' && $id != null){
            $id = base64_decode($id);
           // dd($id);
        }else
            return redirect()->back()->with('error', 'something   went wrong');
        /*$product =    ::select('products.car_model', 'products.veriant', 'products.exterior_color', 'products.interior_color','car_model.id','car_varient.name','interior_color.interior_color','exterior_color.exterior_color')
        ->leftjoin('inventory',  function($join)
        {
            $join->on('car_model.id', '=', 'products.car_model');
            $join->on('car_varient.name', '=', 'products.veriant');
            $join->on('interior_color.interior_color', '=', 'products.interior_color');
            $join->on('exterior_color.exterior_color', '=', 'products.exterior_color');
        })
        ->where(['inventory.id' => $id])->first();*/
        
           $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();
            //dd($product->i_name);

        if (!empty($product)) {
            $product = $product->toArray();

            //new code
            //For OBF -selection
            $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  '.$product['car_name'].' | '.$product['varient_name'].'   ('.$product['exterior_color'].' , '.$product['interior_color'].' )';
               $message = "No OBF Found With this Car";
               return redirect()->route('inventory')->with('error', $message);   
            }
            */
            //For OBF- cash receipt creation
            $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();
            //dd($obf_data_product);
          /*  if(empty($obf_data_product) && $obf_data_product == NULL){
               //$message = 'No OBF Found With  '.$product['car_name'].' | '.$product['varient_name'].'   ('.$product['exterior_color'].' , '.$product['interior_color'].' )';
               $message = "Please Create Cash Receipt First";
               return redirect()->route('inventory')->with('error', $message);   
            }
            *///For OBF selection
            $obf_data_product = Obf::select('obf.id')->where('obf.product_id', $product['i_name'])->where(['obf.status' => 'account_accepted'])->first();
           /*
           if(empty($obf_data_product) && $obf_data_product == NULL){
               //$message = 'No OBF Found With  '.$product['car_name'].' | '.$product['varient_name'].'   ('.$product['exterior_color'].' , '.$product['interior_color'].' )';
               $message = "Please Generate Receipt First";
               return redirect()->route('inventory')->with('error', $message);   
           }*/
            /*$order = Order::select('id')->where('obf_id', $obf_data_product->id)->first();
           if(empty($order) && $order == NULL){
                $message = "Please Generate Receipt First";
                return redirect()->route('inventory')->with('error', $message);   
           }*/
           
           //end
                  
         /*   $obf_data = Obf::select('obf.id')->where(['obf.status' => 'account_accepted'])->where('obf.product_id', $product['i_name'])->first();
                        
            $order = '';
             if (!empty($obf_data)) {
                $order = Order::select('id')->where('obf_id', $obf_data->id)->first();
            }

           / * var_dump($order);
            die('stop');* /
            
            if($order == ''){
                return redirect()->route('inventory')->with('error', 'Please Generate Receipt First ');
            }*/
        
          
             $data = Dealer::get(['id','dealer_name']);

            if ($data->isNotEmpty()) {
                return view('inventory.acceptdealer')->with(['data' => $data, 'id' => $id]);
            } 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 */

    /** acceptedDealer */
    public function accepteddealer(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(['delear_id'=>$request->obf_id,'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, please try later1']);

            $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'
           
            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 */

    /** 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();
                
                foreach ($Carvarient as $value) {
                    $color_data = [];
                    $color_data['id'] = $value->id;
                    $color_data['name'] = $value->name;
                    $Carvarient_arr[] = $color_data;                    
                }  
            }
            $data['Carvarient_arr'] = $Carvarient_arr;  

            return json_encode(array('status'=> true ,'data' => $data));
        }
        
        /* car_varient_asper_fueltype */
}
