<?php

namespace App\Http\Controllers;

use App\Exports\ExportTransitInventory;
use App\Http\Requests\InventoryRequest;
use App\Imports\ImportTransitInventory;
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\TransitInventory;
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 TransitInventoryController extends Controller
{
    /** construct */
    public function __construct()
    {
        $this->middleware('permission:transit_inventory-create', ['only' => ['create']]);
        $this->middleware('permission:transit_inventory-edit', ['only' => ['edit']]);
        $this->middleware('permission:transit_inventory-view', ['only' => ['view']]);
        $this->middleware('permission:transit_inventory-delete', ['only' => ['delete']]);
    }
    /** construct */

    /** index */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = DB::table('transit_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',
                'i.remark',
                DB::raw("DATE_FORMAT(i.created_at, '%d-%m-%Y') as booking_date"),
                DB::raw('count(obb.id) as obf_count'),
                'obb.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('fule_type','fule_type.id','=','i.fuel_type')
            ->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('transit_inventory-view')) {
                        $return .=  '<a href="' . route('transit-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('transit_inventory-edit')) {
                        if ($data->status == 'allocated') {
                            $return .= '';
                        }else{
                            $return .= '<a href="' . route('transit-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('transit_inventory-create')) {
                        $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('transit-inventory.convert_stock', base64_encode($data->id)) . '">Convert To Stock</a></li>
                                    <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('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('transit_inventory.index');
    }
    
    /** create */
    public function create(Request $request)
    {
        $categories = Category::select('id', 'name')->where(['status' => 'active'])->get();
        
        $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(); 
        $fuel_type = Fuletype::where(['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('transit_inventory.create')->with(['categories' => $categories, 'branches' => $branch, 'data'=>$data,'Carmodel_arr'=>$Carmodel_arr,'fuel_type'=>$fuel_type]);
    }
    
    /**carvarient */
    public function carvarient(Request $request){ 
        $id = ($request->id);

         $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));
    }
    
    /** insert */
    public function insert(InventoryRequest $request)
    {
        if ($request->ajax()) {
            return true;
        }

        $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); 
        
        $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,  
        ];

        $last_id = TransitInventory::insertGetId($data);
        
        $crud = [
            'module_nm' => 'transit_inventory',
            'module_id' => $last_id,
            'status' => 'Transit 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('transit-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 = TransitInventory::select('transit_inventory.*','fule_type.title')->leftjoin('fule_type','fule_type.id','=','transit_inventory.fuel_type')->where(['transit_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('transit_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 = TransitInventory::select('transit_inventory.*','fule_type.title','fule_type.id as fuel_id')->leftjoin('fule_type','fule_type.id','=','transit_inventory.fuel_type')->where(['transit_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();

        $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('transit_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 */
    
    
    

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

        $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 = TransitInventory::where(['id' => $request->id])->update($data);
        
        $crud = [
            'module_nm' => 'transit_inventory',
            'module_id' => $request->id,
            'status' => 'Transit 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('transit-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 = TransitInventory::where(['id' => $id])->first();

        if (!empty($data)) {
            // DB::enableQueryLog();
           
            $update = TransitInventory::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
            $crud = [
                'module_nm' => 'transit_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(['transit_inventory_id' => $data->id])->update(['transit_inventory_id' => null]); 
                // dd(DB::getQueryLog());


            if($request->status == 'active'){
                $obf_data = OBF::select('id')->where(['transit_inventory_id' => $id])->first();

                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' => 'transit_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' => 'transit_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']);    
                    }
                }
                
            }

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


    /** Import */
        public function import(Request $request){
            if(Excel::import(new ImportTransitInventory, $request->file('file')->store('file'))){
                return redirect()->route('transit-inventory')->with('sucess' ,'File Imported Sucessfully');
            }else{
                return redirect()->route('transit-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 = 'TransitInventorys_'.Date('YmdHis').'.xlsx';
        
            try {
                return Excel::download(new ExportTransitInventory($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
    /** Export */
    
    /* Convert To Stock */
    public function convert_stock($id){
        
        $decodedId = base64_decode($id);
        $transit_inventory = TransitInventory::findOrFail($decodedId);
        
        DB::beginTransaction();
        try {
            $crud = [
                'delear_id' => $transit_inventory->delear_id,
                'name' => $transit_inventory->name,
                'branch_id' => $transit_inventory->branch_id,
                'key_number' => $transit_inventory->key_number,
                'engine_number' => $transit_inventory->engine_number,
                'chassis_number' => $transit_inventory->chassis_number,
                'vin_number' => $transit_inventory->vin_number,
                'basic_price' => $transit_inventory->basic_price,
                'ex_showroom_price' => $transit_inventory->ex_showroom_price,
                'allocation_count' => 0,
                'aging_days' => $transit_inventory->aging_days,
                'purchase_price' => $transit_inventory->purchase_price,
                'kin_margin' => $transit_inventory->kin_margin,
                'fuel_type' => $transit_inventory->fuel_type,
                'veriant' => $transit_inventory->veriant,
                'interior_color' => $transit_inventory->interior_color,
                'exterior_color' => $transit_inventory->exterior_color,
                'kin_invoice_no' => $transit_inventory->kin_invoice_no,
                'kin_invoice_date' => $transit_inventory->kin_invoice_date,
                'manufacturing_year' => $transit_inventory->manufacturing_year,
                'inventory_type' => $transit_inventory->inventory_type,
                'remark' => $transit_inventory->remark,
                'offer_applicable' => $transit_inventory->offer_applicable,
                'status' => $transit_inventory->status,
                'allocation_date' => $transit_inventory->allocation_date,
                'created_at' => $transit_inventory->created_at,
                'updated_at' => date('Y-m-d H:i:s'),
                'created_by' => $transit_inventory->created_by,
                'updated_by' => auth()->user()->id,
                'fsc_code' => $transit_inventory->fsc_code,
            ];
            DB::table('inventory')->insert($crud);

            // Delete from transit_inventory
            $transit_inventory->delete();
    
            DB::commit();
    
            // Redirect back to transit-inventory listing route
            return redirect()->route('transit-inventory')->with('success', 'Converted to stock successfully!');
        }catch (\Throwable $th) {
            dd($th);
            DB::rollback();
            return redirect()->route('transit-inventory')->with('error' ,'Faild To Convert Stock');
        }    
        
        
    }
}
