<?php

namespace App\Http\Controllers;

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

class RoomController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:room-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $building_id = $request->get('building_id') ?? '';
        $query       = Room::select([
            'id',
            'room_number',
            'room_name',
            'building_id',
            'floor_id',
            'status',
            'default',
            'priority'
            ])
        ->with(['getFloor', 'getBuilding'])
        ->when(!empty($building_id), function($query) use ($building_id) {
            return $query->where('rooms.building_id', $building_id);
        }); 

        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('rooms.table', compact('data'));
        } else {
            $data        = $query->paginate(10);
            $buildings   = Building::select('id' ,'name')->get();

            return view('rooms.index', compact('data' ,'buildings','building_id'));
        }
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = Room::max('priority');
        $priority = $priority != '' ? $priority : 0;
        $building = Building::select('id', 'name')->where('status','1')->get();
        $floor    = Floor::select('id', 'name')->where('status','1')->get();

        return view('rooms.create', compact('building','floor','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(), [
            'room_number' => 'required',
            'floor_id'    => 'required',
            'building_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 = Room::where(['default' => 1,'status' => 1])->first();

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

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

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Tax Master created successfully',
                'data'    => $taxMaster
            ]);
        }
        return redirect()->route('rooms.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)
    {
        $room     = Room::find($id);
        $building = Building::select('id', 'name')->where('status','1')->get();
        $floor    = Floor::select('id', 'name')->where('status','1')->get();

        return view('rooms.edit', compact('building', 'floor','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(), [
            'room_number' => 'required',
            'floor_id'    => 'required',
            'building_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 = Room::findOrFail($id);
        $data['room_code'] = strtoupper(str_replace(' ', '_', $request->room_number));
        $room->update($data);

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

        $room->update($data);

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

        return redirect()->route('rooms.index')
            ->with('success','Room updated successfully');
    }

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

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

        $about->delete();

        $Redirect = 'rooms';

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

    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('default' => $request->status );
            $count  = Room::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 = Room::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Room 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 = Room::where('id', '=', $request->id)->update($data);

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