<?php

namespace App\Http\Controllers\IpdAdmission;

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

class FloorController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:floor-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = Floor::select([
            'floors.id',
            'floors.name',
            'floors.no_of_rooms',
            'floors.description',
            'floors.code',
            'floors.status',
            'floors.priority',
        ])
            ->paginate(10);

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

            $data = Floor::select([
                'floors.id',
                'floors.name',
                'floors.no_of_rooms',
                'floors.building_id',
                'floors.description',
                'floors.code',
                'floors.status',
                'floors.priority',
            ])
                ->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('floors.name', 'like', '%' . $search_query . '%');
                    // ->orWhere('enquiry_sources.enquiry_source_code', 'like', '%'.$search_query.'%');
                })
                ->paginate($sort_by);

            return view('floor.table', compact('data'));
        } else {
            return view('floor.index', compact('data'));
        }
    }

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

        return view('floor.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:floors',
            'no_of_rooms' => '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'
        ]);

        // $data['company_id'] = \Auth::user()->company_id;

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

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Floor Created successfully',
                'data' => $source
            ]);
        }
        return redirect()->route('floors.index')
            ->with('success', 'Floor 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)
    {
        $floor = Floor::find($id);

        return view('floor.edit', compact('floor'));
    }

    /**
     * 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:floors,name,' . $id,
            'no_of_rooms'   => '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'
        ]);

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

        if (!$source) {
            return redirect()->route('floor.index')
                ->with('error','Floor not found!');
        }

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

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Floor updated successfully',
                'data'    => $source
            ]);
        }

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


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

        $Redirect = 'floors';

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

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

}
