<?php

namespace App\Http\Controllers\IpdAdmission;

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

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

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

            $data = Building::select([
                'buildings.id',
                'buildings.name',
                'buildings.code',
                'buildings.no_of_floor',
                'buildings.priority',
                'buildings.status',
                'buildings.default',
            ])
                ->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('buildings.name', 'like', '%' . $search_query . '%');
                })
                ->paginate($sort_by);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = Building::max('priority');
        $priority = $priority != '' ? $priority : 0;
        return view('buildings.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:buildings',
            'no_of_floor' => '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 = Building::where(['default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['default'] = 1;
        }
        $data['company_id'] = \Auth::user()->company_id;

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

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

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

    /**
     * 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:buildings,name,' . $id,
            'no_of_floor'     => '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 = Building::find($id);

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

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

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

        $source->update($data);

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

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


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

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

        $about->delete();

        $Redirect = 'buildings';

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

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


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

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

                if($Update){
                    return response()->json([
                        'success'=>true,
                        'message'=>['Building default status successfully changed.'],
                        'data'=>[
                        ]
                    ]);
                } else {
                    return response()->json([
                       'success'=>false,
                       'message'=>['Error for change default'],
                       'data'=>[
                           'redirect'=>'',
                       ]
                    ]);
                }
            }
        }
    }
}
