<?php

namespace App\Http\Controllers\IpdAdmission;

use App\Http\Controllers\Controller;
use App\Models\BedGroup;
use App\Models\Building;
use App\Models\Floor;
use Illuminate\Http\Request;

class BedGroupController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:bed-group-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = BedGroup::select([
            'bed_groups.id',
            'bed_groups.name',
            'bed_groups.color',
            'bed_groups.description',
            'bed_groups.is_active',
            ])
            ->with('getFloor')
                ->paginate(10);

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

            $data = BedGroup::select([
                'bed_groups.id',
                'bed_groups.name',
                'bed_groups.color',
                'bed_groups.description',
                'bed_groups.is_active',
            ])
            ->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('bed_groups.name', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

            return view('bed-group.table', compact('data'));
        }
        else
        {
          return view('bed-group.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = BedGroup::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('bed-group.create',compact('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(), [
            'name'        => 'required|unique:bed_groups',
        ]);

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

        $data['code'] = strtoupper(str_replace(' ', '_', $request->name));

        $source = BedGroup::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Bed Group Created successfully',
                'data'    => $source
            ]);
        }
        return redirect()->route('bed-group.index')
            ->with('success','Bed Group 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)
    {
        $group = BedGroup::find($id);
        return view('bed-group.edit',compact('group',));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name'        => 'required|unique:bed_groups,name,'.$id,

        ]);

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

        $source = BedGroup::find($id);

        if (!$source) {
            return redirect()->route('bed-group.index')
                ->with('error','Tax Category not found!');
        }

        $data['code'] = strtoupper(str_replace(' ', '_', $request->name));

        $source->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Bed Group updated successfully',
                'data'    => $source
            ]);
        }
        return redirect()->route('bed-group.index')
            ->with('success','Bed Group updated successfully');
    }

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

        $Redirect = 'bed-group';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }
    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_active' => $request->status );
            $Update = BedGroup::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Bed Group status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
    public function getFloor(Request $request)
    {
      $getFloor=Floor::select(['id','name'])->where('building_id',$request->building_id)->get();

      foreach($getFloor as $list)
      {
        if($request->flood_id == $list->id){
          echo '<option value="'.$list->id.'" selected>'.$list->name.'</option>';
        }
        else{
          echo '<option value="'.$list->id.'">'.$list->name.'</option>';
        }
      }
    }
}
