<?php

namespace App\Http\Controllers\IpdAdmission;

use App\Http\Controllers\Controller;
use App\Models\BedType;
use App\Models\Product;
use Illuminate\Http\Request;

class BedTypeController extends Controller
{
    function __construct()
    {
        // $this->middleware('permission:bed-type-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = BedType::select([
            'bed_types.id',
            'bed_types.code',
            'bed_types.name',
            'bed_types.product_id',
            'bed_types.status',
        ])->with('getProduct')->paginate(10);

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $products = Product::select('id','name')->get();
        return view('bed-type.create',compact('products'));
    }

    /**
     * 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_types',
            'product_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'
        ]);

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

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

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

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Bed Type Created successfully',
                'data'    => $source
            ]);
        }
        return redirect()->route('bed-type.index')
            ->with('success','Bed Type 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)
    {
        $bed_type = BedType::find($id);
        $products = Product::select('id','name')->get();
        return view('bed-type.edit',compact('bed_type','products'));
    }

    /**
     * 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_types,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 = BedType::find($id);

        if (!$source) {
            return redirect()->route('bed-type.index')
                ->with('error','Bed Type not found!');
        }

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

        $source->update($data);

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


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

        $Redirect = 'bed-type';

        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 = BedType::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Bed Type status successfully change'],
                   'data'=>[
                       'redirect'=>'/bed-type/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Bed Type for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
    }
    public function bedTypeSearchProducts(Request $request)
    {
        $searchTerm = $request->search_text;

        $results    = Product::select('products.id','products.name')
            ->where(function ($query) use ($searchTerm) {
                $query->where('products.name', 'LIKE', $searchTerm . "%");
            })
            ->get();

        return response()->json(['result' => $results, 'status' => true]);
    }
}
