<?php

namespace App\Http\Controllers;

use App\Models\Floor;
use App\Models\RackLocation;
use App\Models\Room;
use Illuminate\Http\Request;

class RackLocationController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:rack-location-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = RackLocation::select([
            'id',
            'room_id',
            'row_number',
            'column_number',
            'priority',
            'status',
            'default'
        ])->with('getRoom');

        if ($request->ajax()) {
            $sort_by = $request->get('sortby') ?? 10;
            $sort_type = $request->get('sorttype');
            $search_query = $request->get('query');

            $query->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('name', 'like', '%' . $search_query . '%');
            });

            $data = $query->paginate($sort_by);

            return view('rack-locations.table', compact('data'));
        } else {
            $data = $query->paginate(10);
            return view('rack-locations.index', compact('data'));
        }
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = RackLocation::max('priority');
        $priority = $priority != '' ? $priority : 0;
        $room    = Room::select('id', 'room_number')->get();

        return view('rack-locations.create', compact('room','priority'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'row_number'    => 'required',
            'column_number' => 'required',
            'room_id'      => 'required',

        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $default_check = RackLocation::where(['default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['default'] = 1;
        }

        // $data['room_code'] = strtoupper(str_replace(' ', '_', $request->room_number));
        $data = RackLocation::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Rack Location created successfully',
                'data'    => $data
            ]);
        }
        return redirect()->route('rack-locations.index')
            ->with('success', 'Tax Master created successfully');
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $rack     = RackLocation::find($id);
        $room    = Room::select('id', 'room_number')->get();

        return view('rack-locations.edit', compact('rack','room'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd($request->all());
        $validator = \Validator::make($request->all(), [
            'row_number'    => 'required',
            'column_number' => 'required',
            'room_id'      => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $room = RackLocation::findOrFail($id);
        $room->update($data);

        if (!$room) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => "Rack Location not found!",
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', "Rack Location  not found!");
        }

        $room->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Rack Location has been created successfully',
            ]);
        }

        return redirect()->route('rack-locations.index')
            ->with('success','Rack Location updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $about = RackLocation::find($request->id);

        if ($about->default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $about->delete();

        $Redirect = 'rack-locations';

        return response()->json([
            'success' => true,
            'message' => ['Rack Location Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('default' => $request->status );
            $count  = RackLocation::where(['default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Task!'],
                    'data'    => []
                ]);
            }

            $Update = RackLocation::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Rack Locations default status successfully changed.'],
                    'data'=>[
                       'redirect'=>'/task/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
    public function changeStatus(Request $request)
    {
       if ($request->ajax())
       {
           $data = array('status' => $request->status );
           $Update = RackLocation::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Rack Locations status successfully change'],
                   'data'=>[
                       'redirect'=>'/buckets/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Rack Locations for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
    }
}
