<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Branch;
use App\Models\Transfer;
use App\Models\Product;
use App\Models\Inventory;
use App\Models\Carmodel;
use App\Models\Carvarient;
use App\Http\Requests\TransferRequest;
use App\Http\Requests\TransferAcceptRequest;
use Auth, DB, Mail, Validator, File, DataTables;

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

    /** index */
        public function index(Request $request){
            if($request->ajax()){
                $collection = DB::table('transfer as t')
                                ->select('t.id', 't.to_branch as to_branch_id', 't.from_branch as from_branch_id', 'tb.name as to_branch', 'fb.name as from_branch', 'p.name as product', 't.status','cm.name as cm_name','cv.name as cv_name','i.vin_number as vin_number','t.driver_name as d_name','t.driver_lic as d_lic','t.driver_pan as d_pan','t.car_image_1 as carImage1','t.car_image_2 as carImage2','t.car_image_3 as carImage3','t.car_image_4 as carImage4','t.car_image_5 as carImage5','t.remark as remark','t.toolkit as tolkit','t.medikit as medkit','t.spare_bulb as sparbulb','t.hazard_trinagle as hzdtringle','t.good_condtiton as gudcondition','t.created_at as transfer_date')
                                ->leftjoin('branches as tb', 'tb.id', 't.to_branch')
                                ->leftjoin('branches as fb', 'fb.id', 't.from_branch')
                                ->leftjoin('inventory as i', 'i.id', 't.inventory_id')
                                ->leftjoin('products as p', 'i.name', '=', 'p.id')
                                ->leftjoin('car_model as cm', 'cm.id', 'p.car_model')
                                ->leftjoin('car_varient as cv', 'cv.id', 'p.veriant');
                    
                // if(auth()->user()->roles->pluck('name')[0] != 'admin')
                //     $collection->where(['t.to_branch' => auth()->user()->branch]);
                
                // $data = $collection->get();
                $data = $collection->orderBy('t.created_at', 'desc');
                 
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('action', function($data){
                            $return = '';
                                
                            $userBranchArray = explode(',',auth()->user()->branch);
                            $fromBranchArray = explode(',', $data->from_branch_id);
                            $toBranchArray   = explode(',', $data->to_branch_id);
                            
                            if (auth()->user()->can('transfer-delete') && $data->status == 'pending') {
                                if(count(array_intersect($toBranchArray, $userBranchArray)) > 0){
                                    $return = '<div class="btn-group">';
                                    $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                                    <i class="fa fa-bars"></i>
                                                </a> &nbsp;
                                                <ul class="dropdown-menu">
                                                    <li><a class="dropdown-item" href="'.route('transfer.accept.check', ['id' => base64_encode($data->id)]).'">Accept</a></li>
                                                    <li><button type="button" class="dropdown-item" data-toggle="modal" data-target="#model_reject_'.$data->id.'">Reject</button></li>
                                                </ul>';
                                    $return .= '</div>';
                                }else{
                                    $return =   '<a class="btn btn-default btn-xs" href="javascript:;" onclick="change_status(this);" data-status="delete" data-id="'.base64_encode($data->id).'"><i class="fa fa-trash"></i></a>';
                                }
                            }
                            if (auth()->user()->can('transfer-delete') && $data->status == "accepted") {
                                
                                if(count(array_intersect($toBranchArray, $userBranchArray)) > 0){
                                    $return = '<div class="btn-group">';
                                    $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                                    <i class="fa fa-bars"></i>
                                                </a> &nbsp;
                                                <ul class="dropdown-menu">

                                                    <li><button type="button" class="dropdown-item" data-toggle="modal" data-target="#model_received_'.$data->id.'">Received</button></li>
                                                </ul>';
                                    $return .= '</div>';
                                }

                                if(count(array_intersect($fromBranchArray, $userBranchArray)) > 0){
                                    $return .=  '<a href="'.route('transfer.gate.pass', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                    <i class="fa fa-ticket"></i>
                                                </a>';
                                                $return .=  '<a href="'.route('transfer.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                    <i class="fa fa-pencil"></i>
                                                </a>';
                                }
                            }
                            
                            if($data->status == 'received'){
                                if(count(array_intersect($fromBranchArray, $userBranchArray)) > 0){
                                    $return .=  '<a href="'.route('transfer.gate.pass', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                    <i class="fa fa-ticket"></i>
                                                </a>';
                                                // $return .=  '<a href="'.route('transfer.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                //     <i class="fa fa-pencil"></i>
                                                // </a>';
                                }else{
                                    $return .=  '<a href="'.route('transfer.transfer.details', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                    <i class="fa fa-eye"></i>
                                                </a>';
                                }
                            }

                            $return .= '<div class="modal fade" id="model_reject_'.$data->id.'" tabindex="-1" role="dialog" aria-labelledby="model_reject_'.$data->id.'" aria-hidden="true">
                                            <div class="modal-dialog" role="document">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="model_reject_'.$data->id.'">Reject</h5>
                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                            <span aria-hidden="true">&times;</span>
                                                        </button>
                                                    </div>
                                                    <form class="transfer_reject" method="post" action="'.route('transfer.reject').'">
                                                        <div class="modal-body">
                                                            <input type="hidden" name="id" value="'.$data->id.'" />

                                                            <div class="row">
                                                                <div class="form-group col-sm-6">
                                                                    <label for="from_branch">From Branch</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->from_branch.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-6">
                                                                    <label for="to_branch">To Branch</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->to_branch.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-12">
                                                                    <label for="reason'.$data->id.'">To Branch</label>
                                                                    <textarea id="reason_'.$data->id.'" name="reason" class="form-control" rows="3" cols="30" required></textarea>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="submit" class="btn btn-primary">Save</button>
                                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>';
                                        
                                        
                                        $return .= '<div class="modal fade" id="model_received_'.$data->id.'" tabindex="-1" role="dialog" aria-labelledby="model_received_'.$data->id.'" aria-hidden="true">
                                            <div class="modal-dialog modal-xl" role="document">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 style="color:black!important;" class="modal-title" id="model_received_'.$data->id.'">Received</h5>
                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color:black;">
                                                            <span aria-hidden="true">&times;</span>
                                                        </button>
                                                    </div>
                                                    <form class="transfer_received" method="post" action="'.route('transfer.received').'" enctype="multipart/form-data">
                                                        <div class="modal-body">
                                                            <input type="hidden" name="id" value="'.$data->id.'" />

                                                            <div class="row">
                                                                <div class="form-group col-sm-3">
                                                                    <label for="from_branch" style="color:black;">From Branch</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->from_branch.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">To Branch</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->to_branch.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Car Model</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->cm_name.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Car Veriant</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->cv_name.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Vin Number</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->vin_number.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Driver Name</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->d_name.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Driver Licence Number</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->d_lic.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Driver PanCard</label>
                                                                    <input type="text" class="form-control" placeholder="Plese enter from branch" value="'.$data->d_pan.'" readonly>
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Car Image1</label>
                                                                    <img src="' . asset('storage/' . $data->carImage1) . '" width="100" height="100" style="display:inline-block;margin-top:15px;" class="m-b-15" data-toggle="modal" data-target="#imageModal">
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Car Image2</label>
                                                                    <img src="' . asset('storage/' . $data->carImage2) . '" width="100" height="100" style="display:inline-block;margin-top:15px;" class="m-b-15" data-toggle="modal" data-target="#imageModal">
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Car Image3</label>
                                                                    <img src="' . asset('storage/' . $data->carImage3) . '" width="100" height="100" style="display:inline-block;margin-top:15px;" class="m-b-15" data-toggle="modal" data-target="#imageModal">
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Car Image4</label>
                                                                    <img src="' . asset('storage/' . $data->carImage4) . '" width="100" height="100" style="display:inline-block;margin-top:15px;" class="m-b-15" data-toggle="modal" data-target="#imageModal">
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Car Image5</label>
                                                                    <img src="' . asset('storage/' . $data->carImage4) . '" width="100" height="100" style="display:inline-block;margin-top:15px;" class="m-b-15" data-toggle="modal" data-target="#imageModal">
                                                                </div>
                                                                <div class="form-group col-sm-3">
                                                                    <label for="to_branch" style="color:black;">Remark</label>
                                                                    <textarea class="form-control" readonly>'.$data->remark.'</textarea>
                                                                </div>
                                                                <div class="form-group col-sm-12">
                                                                    <label for="carrecivedImage1'.$data->id.'" style="color:black;">Gatepass Image</label>
                                                                    <input type="file" id="carrecivedImage1_'.$data->id.'" name="carrecivedImage1" class="form-control" rows="3" cols="30" required>
                                                                </div>
                                                                <div class="form-group col-sm-12">
                                                                    <label for="carrecivedImage1'.$data->id.'" style="color:black;">Received Car Image 1</label>
                                                                    <input type="file" id="carrecivedImage2_'.$data->id.'" name="carrecivedImage2" class="form-control" rows="3" cols="30">
                                                                </div>
                                                                <div class="form-group col-sm-12">
                                                                    <label for="carrecivedImage3'.$data->id.'" style="color:black;">Received Car Image 2</label>
                                                                    <input type="file" id="carrecivedImage3_'.$data->id.'" name="carrecivedImage3" class="form-control" rows="3" cols="30">
                                                                </div>
                                                                <div class="form-group col-sm-12">
                                                                    <label for="carrecivedImage4'.$data->id.'" style="color:black;">Received Car Image 3</label>
                                                                    <input type="file" id="carrecivedImage4_'.$data->id.'" name="carrecivedImage4" class="form-control" rows="3" cols="30">
                                                                </div>
                                                                <div class="form-group col-sm-12">
                                                                    <label for="carrecivedImage5'.$data->id.'" style="color:black;">Received Car Image 4</label>
                                                                    <input type="file" id="carrecivedImage5_'.$data->id.'" name="carrecivedImage5" class="form-control" rows="3" cols="30">
                                                                </div>
                                                                <div class="form-group col-sm-12">
                                                                    <label for="reason'.$data->id.'" style="color:black;">Remark</label>
                                                                    <textarea id="reason_'.$data->id.'" name="reason" class="form-control" rows="3" cols="30" required></textarea>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="submit" class="btn btn-primary">Save</button>
                                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>';

                            return $return;
                        })

                        ->editColumn('status', function ($data) {
                            if ($data->status == 'rejected') {
                                return '<span class="badge badge-pill badge-danger">Rejected</span>';
                            } else if ($data->status == 'accepted') {
                                return '<span class="badge badge-pill badge-success">Accepted</span>';
                            }  else if ($data->status == 'received') {
                                return '<span class="badge badge-pill badge-success">Received</span>';
                            }else {
                                return '<span class="badge badge-pill badge-info">Pending</span>';
                            }
                        })

                        ->editColumn('transfer_date',function($data){
                            $transferDate = \Carbon\Carbon::parse($data->transfer_date)->format('d-m-Y');
                            return $transferDate;
                        })

                        ->rawColumns(['action', 'status','transferDate'])
                        ->filter(function ($query) {
                                if ($dateRange = request()->get('transfer_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 H:i:s');
                                            $end = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[1]))->endOfDay()->format('Y-m-d H:i:s');
                                            $query->whereBetween('t.created_at', [$start, $end]);
                                        } catch (\Exception $e) {
                                            \Log::error('Invalid date range format for transfer_date filter', [
                                                'input' => $dateRange,
                                                'error' => $e->getMessage()
                                            ]);
                                        }
                                    }
                                }
                                if (request()->get('cm_name', false)) {
                                    $query->where('p.name', 'like', "%" . request()->get("cm_name") . "%");
                                }
                                if (request()->get('cv_name', false)) {
                                    $query->where('cv.name', 'like', "%" . request()->get("cv_name") . "%");
                                }
                                if (request()->get('vin_number', false)) {
                                    $query->where('i.vin_number', 'like', "%" . request()->get("vin_number") . "%");
                                }
                                if (request()->get('from_branch', false)) {
                                    $query->where('fb.name', 'like', "%" . request()->get("from_branch") . "%");
                                }
                                if (request()->get('to_branch', false)) {
                                    $query->where('tb.name', 'like', "%" . request()->get("to_branch") . "%");
                                }
                                if (request()->get('status', false)) {
                                    $query->where('t.status', 'like', "%" . request()->get("status") . "%");
                                }
                            })
                        ->make(true);
            }
            
            return view('transfer.index');
        }
    /** index */

    /** create */
        public function create(Request $request)
        {
            ini_set('memory_limit', '512M');
            $products = Product::select('id', 'name', 'veriant')->get();

            // Branch selection
            $branch = Branch::select('*');
            if (!empty(auth()->user()->branch)) {
                $branch_arr = explode(',', auth()->user()->branch);
                if (!empty($branch_arr)) {
                    $branch = $branch;
                }
            }
            $branch = $branch->where(['status' => 'active', 'flag' => '1'])->get();
        
            // Car model and variant
            $carmodel = Carmodel::where(['status' => 'active'])->get();
            $carvarient = Carvarient::where(['status' => 'active'])->get();
        
            return view('transfer.create')->with([
                'branches'     => $branch,
                'products'     => $products,
                'carmodel'     => $carmodel,
                'carvarient'   => $carvarient
            ]);
        }

    /** create */
    
        public function getTransferVinDetails(Request $request)
        {
            $vin = trim($request->vin_number);
        
            $data = DB::table('inventory as i')
                ->leftjoin('branches as b', 'i.branch_id', '=', 'b.id')
                ->leftjoin('products as p', 'i.name', '=', 'p.id')
                ->leftjoin('car_model as cm', 'p.car_model', '=', 'cm.id')
                ->leftjoin('car_varient as cv', 'p.veriant', '=', 'cv.id')
                ->where('i.status', '!=', 'sold')
                ->where('i.vin_number', $vin)
                ->select(
                    'i.id as inventory_id',
                    'i.vin_number',
                    'i.status',
                    'b.name as branch_name',
                    'cm.name as model_name',
                    'cv.name as varient_name',
                    'p.car_model as car_model_id',
                    'p.veriant as car_varient_id',
                    'i.branch_id'
                )
                ->first();
        
            return response()->json($data);
        }


    /** insert */
        public function insert(TransferRequest $request){
            if($request->ajax()){ return true; }
            
            $from_branch = auth()->user()->branch;
            if(auth()->user()->roles->pluck('name')[0] == 'admin')
                $from_branch = $request->from_branch;


            $carImage1Path = '';
            $carImage2Path = '';
            $carImage3Path = '';
            $carImage4Path = '';
            $carImage5Path = '';
            
            if(!empty($request->file('car_image_1'))){
                $carImage1 = $request->file('car_image_1');
                $carImage1Name = time().'.'.$carImage1->extension();
                $carImage1Path = $carImage1->storeAs('carImage1', $carImage1Name, 'public');   
            }
            
            if(!empty($request->file('car_image_2'))){
                $carImage2 = $request->file('car_image_2');
                $carImage2Name = time().'.'.$carImage2->extension();
                $carImage2Path = $carImage2->storeAs('carImage2', $carImage2Name, 'public');
            }
            
            if(!empty($request->file('car_image_3'))){
                $carImage3 = $request->file('car_image_3');
                $carImage3Name = time().'.'.$carImage3->extension();
                $carImage3Path = $carImage3->storeAs('carImage3', $carImage3Name, 'public');
            }
            
            if(!empty($request->file('car_image_4'))){
                $carImage4 = $request->file('car_image_4');
                $carImage4Name = time().'.'.$carImage4->extension();
                $carImage4Path = $carImage4->storeAs('carImage4', $carImage4Name, 'public');
            }
            
            if(!empty($request->file('car_image_5'))){
                $carImage5 = $request->file('car_image_5');
                $carImage5Name = time().'.'.$carImage5->extension();
                $carImage5Path = $carImage5->storeAs('carImage5', $carImage5Name, 'public');
            }
            $data = [
                'to_branch' => $request->to_branch,
                // 'product_id' => $request->product_id,
                'from_branch' => $from_branch,
                'inventory_id'=>$request->inventory_id,
                'status' => 'pending',
                'driver_name' => $request->driver_name,
                'driver_pan' => $request->driver_pan,
                'driver_lic' => $request->driver_lic,
                'remark' => $request->remark,
                'car_image_1' => $carImage1Path,
                'car_image_2' => $carImage2Path,
                'car_image_3' => $carImage3Path,
                'car_image_4' => $carImage4Path,
                'car_image_5' => $carImage5Path,
                'toolkit' => $request->tool_kit,
                'medikit' => $request->health_kit,
                'spare_bulb' => $request->spare_bulb,
                'hazard_trinagle' => $request->harzard_triangle,
                'good_condtiton' => $request->good_condition,
                '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
            ];

            $transfer = Transfer::create($data);

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

    /** Edit */
    public function edit($id)
    {
        if (isset($id) && $id != '' && $id != null)
                $id = base64_decode($id);
            else
                return redirect()->route('transfer')->with('error', 'Something went wrong');


        $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;    
                }
            }                        
        $branch = $branch->where(['status' => 'active'])->get(); 
            //branch selection
        $carmodel = Carmodel::where(['status' => 'active'])->get();
        $carvarient = Carvarient::where(['status' => 'active'])->get();   

        $transferEdit = Transfer::where('id',$id)->first();
        $transferVinNumber = Inventory::where('id',$transferEdit->inventory_id)->first();
        $transfercarModel = Product::where('id',$transferVinNumber->name)->first();
        return view('transfer.edit',compact('branch','carmodel','carvarient','transferEdit','transferVinNumber','transfercarModel'));

    }

    public function update(Request $request,$id)
    {
        
        $transferUpdate = Transfer::where('id',$id)->first();
        $carImage1Path = $transferUpdate->car_image_1;
        $carImage2Path = $transferUpdate->car_image_2;
        $carImage3Path = $transferUpdate->car_image_3;



        if($request->ajax()){ return true; }
            
            $from_branch = auth()->user()->branch;
            if(auth()->user()->roles->pluck('name')[0] == 'admin')
                $from_branch = $request->from_branch;

            $carImage1 = $request->file('car_image_1');
            if(!empty($carImage1)){
                $carImage1Name = time().'.'.$carImage1->extension();
                $carImage1Path = $carImage1->storeAs('carImage1', $carImage1Name, 'public');
            }
            $carImage2 = $request->file('car_image_2');
            if(!empty($carImage2)){   
                $carImage2Name = time().'.'.$carImage2->extension();
                $carImage2Path = $carImage2->storeAs('carImage2', $carImage2Name, 'public');
            }
            $carImage3 = $request->file('car_image_3');
            if(!empty($carImage3)){
                $carImage3Name = time().'.'.$carImage3->extension();
                $carImage3Path = $carImage3->storeAs('carImage3', $carImage3Name, 'public');
            }

            $transfer = Transfer::findOrFail($id);
            $transfer->update([
                'to_branch' => $request->to_branch,
                // 'product_id' => $request->product_id,
                'from_branch' => $from_branch,
                'inventory_id'=>$request->vin_number,
                'status' => 'pending',
                'driver_name' => $request->driver_name,
                'driver_pan' => $request->driver_pan,
                'driver_lic' => $request->driver_lic,
                'remark' => $request->remark,
                'car_image_1' => $carImage1Path,
                'car_image_2' => $carImage2Path,
                'car_image_3' => $carImage3Path,
                'toolkit' => $request->tool_kit,
                'medikit' => $request->health_kit,
                'spare_bulb' => $request->spare_bulb,
                'hazard_trinagle' => $request->harzard_triangle,
                'good_condtiton' => $request->good_condition,
                '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
            ]);

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



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

            if (!empty($request->all())) {
                $data = Transfer::where(['id' => $request->id])->first();

                if(!empty($data)){
                    $process = Transfer::where(['id' => $request->id])->update(['status' => 'rejected', 'reason' => $request->reason, 'updated_by' => auth()->user()->id]);

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

    /** accept-check */
        public function accept_check(Request $request, $id = ''){
           
            if (isset($id) && $id != '' && $id != null)
                $id = base64_decode($id);
            else
                return redirect()->route('transfer')->with('error', 'Something went wrong');
            
            $transfer = Transfer::select('from_branch', 'to_branch', 'product_id','inventory_id')->where(['id' => $id])->first();
            if(!$transfer){
                return redirect()->back()->with(['error' => 'Record not found']);
            }

            // $product = Product::select('id', 'name', 'veriant')->where(['id' => $transfer->product_id])->first();
            // if(!$product){
            //     return redirect()->back()->with(['error' => 'Product not found']);
            // }
            
            $inventories = Inventory::where('id','=',$transfer->inventory_id)->get();
         
            return view('transfer.accept')->with(['id' => $id, 'inventories' => $inventories]);
        }
    /** accept-check */

    /** inventory-details */
        public function inventory_details(Request $request, $id = ''){
            $data = DB::table('inventory as i')
            ->select('cm.name as cm_name', 'cv.name as cv_name', 'i.key_number', 'i.engine_number', 'i.vin_number', 'i.ex_showroom_price', 
                                        'int.name as int_name', 'ext.name as ext_name', 'i.status','t.driver_name as d_name','t.driver_lic as d_lic','t.driver_pan as d_pan','t.car_image_1 as cri_1','t.car_image_2 as cri_2','t.car_image_3 as cri_3','t.car_image_4 as cri_4','t.car_image_5 as cri_5','t.remark as remarks')
                                        ->leftjoin('products as p','p.id','=','i.name')
                                        ->leftJoin('car_model as cm','cm.id','=','p.car_model')
                                        ->leftJoin('car_varient as cv','cv.id','=','p.veriant')
                                        ->leftJoin('exteriorcolor as ext','ext.id','=','p.exterior_color')
                                        ->leftJoin('interiorcolor as int','int.id','=','p.interior_color')
                                        ->leftJoin('transfer as t', 't.inventory_id', '=', 'i.id')
                                        ->where(['i.id' => $request->id])
                                        ->first();                            

            if($data)
                return response()->json(['code' => 200, 'data' => $data]);
            else
                return response()->json(['code' => 201]);

        }
    /** inventory-details */

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

            DB::beginTransaction();
            try {
               $transfer = Transfer::where(['id' => $request->id])->update(['status' => 'accepted', 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
                  
                if(!$transfer){
                    DB::rollback();
                    return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();    
                }

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

                if(!$inventory){
                    DB::rollback();
                    return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();    
                }

                DB::commit();
                return redirect()->route('transfer')->with(['success' => 'Transfer accepted']);
            }catch (\Throwable $th){
                DB::rollback();
                return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
            }
        }
    /** accept */

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

           $data = DB::table('transfer as t')
                        // ->select('t.id', 't.transfer_fee', 'fb.name as from_branch', 'tb.name as to_branch', 'cm.name as cm_name', 'cv.name as cv_name','i.key_number', 'i.engine_number', 'i.chassis_number', 'i.vin_number', 'i.ex_showroom_price','int.name as int_name', 'ext.name as ext_name','t.driver_name as driver_name','t.driver_lic as lic', 't.driver_pan as pan','t.toolkit as toolkit','t.medikit as medikit','t.good_condtiton as good_condtiton','t.spare_bulb as spare_bulb','t.hazard_trinagle as hazard_trinagle')
                        ->select('t.id', 't.transfer_fee','fb.id as from_branch_id','fb.name as from_branch','fb.address as from_branch_address', 'tb.name as to_branch', 'cm.name as cm_name', 'cv.name as cv_name', 
                                'i.key_number', 'i.engine_number', 'i.chassis_number', 'i.vin_number', 'i.ex_showroom_price',
                                'int.name as int_name', 'ext.name as ext_name','t.driver_name as driver_name','t.driver_lic as lic', 't.driver_pan as pan','t.toolkit as toolkit','t.medikit as medikit','t.good_condtiton as good_condtiton','t.spare_bulb as spare_bulb','t.hazard_trinagle as hazard_trinagle')
                        ->leftjoin('branches as fb', 'fb.id', 't.from_branch')
                        ->leftjoin('branches as tb', 'tb.id', 't.to_branch')
                        ->leftjoin('inventory as i', 'i.id', 't.inventory_id')
                          ->leftjoin('products as p','p.id','=','i.name')
                                        ->leftJoin('car_model as cm','cm.id','=','p.car_model')
                                        ->leftJoin('car_varient as cv','cv.id','=','p.veriant')
                                        ->leftJoin('exteriorcolor as ext','ext.id','=','p.exterior_color')
                                        ->leftJoin('interiorcolor as int','int.id','=','p.interior_color')
                        ->where(['t.id' => $id])
                        ->first();

            $images = DB::table('global_configuration')->select('gatepass_logo1','gatepass_logo2')->where('branch_id',$data->from_branch_id)->first();
            return view('transfer.gate_pass')->with(['data' => $data,'images'=>$images]);
            // return view('transfer.gate_pass')->with(['data' => $data]);
        }
    /** gate-pass */

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

            $data = DB::table('transfer as t')
                        ->select('t.id', 't.transfer_fee', 'fb.name as from_branch', 'tb.name as to_branch', 'cm.name as cm_name', 'cv.name as cv_name', 
                                'i.key_number', 'i.engine_number', 'i.chassis_number', 'i.vin_number', 'i.ex_showroom_price',
                                'int.name as int_name', 'ext.name as ext_name','t.driver_name as driver_name','t.driver_lic as lic', 't.driver_pan as pan','t.toolkit as toolkit','t.medikit as medikit','t.good_condtiton as good_condtiton','t.spare_bulb as spare_bulb','t.hazard_trinagle as hazard_trinagle')
                        ->leftjoin('branches as fb', 'fb.id', 't.from_branch')
                        ->leftjoin('branches as tb', 'tb.id', 't.to_branch')
                        ->leftjoin('inventory as i', 'i.id', 't.inventory_id')
                          ->leftjoin('products as p','p.id','=','i.name')
                                        ->leftJoin('car_model as cm','cm.id','=','p.car_model')
                                        ->leftJoin('car_varient as cv','cv.id','=','p.veriant')
                                        ->leftJoin('exteriorcolor as ext','ext.id','=','p.exterior_color')
                                        ->leftJoin('interiorcolor as int','int.id','=','p.interior_color')
                        ->where(['t.id' => $id])
                        ->first();

            return view('transfer.transfer_details')->with(['data' => $data]);
        }
    /** transfer-details */

    /** change-status */
        public function change_status(Request $request){
            if (!$request->ajax()) { exit('No direct script access allowed'); }
            $id = base64_decode($request->id);
            
            $data = Transfer::where(['id' => $id])->first();

            if (!empty($data)) {
                $update = Transfer::where(['id' => $id])->delete();
                if ($update) {
                    return response()->json(['code' => 200]);
                } else {
                    return response()->json(['code' => 201]);
                }
            } else {
                return response()->json(['code' => 201]);
            }
        
        }
    /** change-status */

    /** car varient as per car model*/
    public function varientaspercarmodel(Request $request)
    {
        $model = $request->car_model;

        $query = Carmodel::select('car_varient.id','car_varient.name')->leftjoin('car_varient','car_varient.car_model','=','car_model.id')->where('car_varient.car_model',$model)->get();

        return view('transfer.car_varient_list')->with(['query'=>$query]);
    }
    /** car varient as per car model*/ 

    /** VIN Number as per car varient */
    public function vinaspercarvarient(Request $request)
    {
        $car_varient = $request->car_varient;
        //dd($car_varient);
        $query = Inventory::select('inventory.id','inventory.vin_number')->leftjoin('products', 'products.id', 'inventory.name')->where('products.veriant',$car_varient)->get();
        //dd($query);
        return view('transfer.vin_car_varient_list')->with(['query'=>$query]);
    }
    /** VIN Number as per car varient */
    
    public function received(Request $request)
    {
         if (!$request->ajax()) { exit('No direct script access allowed'); }
            
          DB::beginTransaction();
            try {
                
                if ($request->hasFile('carrecivedImage1')) {
                    $carImage1 = $request->file('carrecivedImage1');
                    $carImage1Name = time().'.'.$carImage1->extension();
                    $carImage1Path = $carImage1->storeAs('carReceivedImage1', $carImage1Name, 'public');
                } else {
                    return redirect()->back()->with('error', 'Gatepass Image Compulsory...')->withInput(); 
                } 
                
                $carImage2 = '';
                $carImage2Name = '';
                $carImage2Path = '';
                if ($request->hasFile('carrecivedImage2')) {
                    $carImage2 = $request->file('carrecivedImage2');
                    $carImage2Name = time().'.'.$carImage2->extension();
                    $carImage2Path = $carImage2->storeAs('carReceivedImage2', $carImage2Name, 'public');
                }
                
                $carImage3 = '';
                $carImage3Name = '';
                $carImage3Path = '';
                if ($request->hasFile('carrecivedImage3')) {
                    $carImage3 = $request->file('carrecivedImage3');
                    $carImage3Name = time() . '_3.' . $carImage3->extension();
                    $carImage3Path = $carImage3->storeAs('carReceivedImage3', $carImage3Name, 'public');
                }
                
                $carImage4 = '';
                $carImage4Name = '';
                $carImage4Path = '';
                if ($request->hasFile('carrecivedImage4')) {
                    $carImage4 = $request->file('carrecivedImage4');
                    $carImage4Name = time() . '_4.' . $carImage4->extension();
                    $carImage4Path = $carImage4->storeAs('carReceivedImage4', $carImage4Name, 'public');
                }
                
                $carImage5 = '';
                $carImage5Name = '';
                $carImage5Path = '';
                if ($request->hasFile('carrecivedImage5')) {
                    $carImage5 = $request->file('carrecivedImage5');
                    $carImage5Name = time() . '_5.' . $carImage5->extension();
                    $carImage5Path = $carImage5->storeAs('carReceivedImage5', $carImage5Name, 'public');
                }

                $transfer = Transfer::where(['id' => $request->id])->update(['status' => 'received','carrecivedimage1' => $carImage1Path,'carrecivedimage2' => $carImage2Path,'carrecivedimage3' => $carImage3Path,'carrecivedimage4' => $carImage4Path,'carrecivedimage5' => $carImage5Path,'remarks'=>$request->reason, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
                
                if(!$transfer){
                    DB::rollback();
                    return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();    
                }

                $transfer = Transfer::where(['id' => $request->id])->first();
           
                $inventory = Inventory::where(['id' => $transfer->inventory_id])->update(['branch_id'=>auth()->user()->branch,'status' => 'active', 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
                           
                if(!$inventory){
                    DB::rollback();
                    return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();    
                }
                
                DB::commit();
                 return response()->json(['code' => 200,'message' => 'Entry updated successfully.']);
            }catch (\Throwable $th){
                dd($th);
                DB::rollback();
                return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
            }
    }
    
}
