<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\UserType;

class UserTypesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $user_types = UserType::select(
            'user_types.id as id',
            'user_types.name as name',
            'user_types.code as code',
            'user_types.status',
        );

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

            $user_types = $user_types->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('user_types.name', 'like', '%'.$search_query.'%')
                        ->orWhere('user_types.code', 'like', '%'.$search_query.'%');
            })
            ->orderBy('user_types.name','ASC')
            ->paginate($sort_by);

            return view('user-types.table', compact('user_types'));
        } else {
            $user_types = $user_types->groupBy('id')
                ->orderBy('user_types.name','ASC')
                ->paginate(10);

            return view('user-types.index',compact('user_types'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
       $user_types = UserType::select('id','name' ,'code')->get();

        return view('user-types.create',compact('user_types'));
    }

    /**
     * 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',
            'code' => 'required|unique:user_types,code'
        ]);

        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'
        ]);
        $data = UserType::create($data);


        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'User Type created successfully',
                'data'    => $data
            ]);
        }
        return redirect()->route('user-types.index')
            ->with('success', 'User 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)
    {

        $user_types = UserType::find($id);
  

        return view('user-types.edit', compact('user_types'));
    }

    /**
     * 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',
            'code' => 'required|unique:user_types,code'
        ]);

        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 = UserType::whereId($id)->update($data);
        $data = UserType::find($id);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = UserType::find($id);

        $data->delete();

        return response()->json([
            'success' => true,
            'message' => ['User Type deleted successfully'],
            'data' => [
                'redirect' => 'userr-types.index',
            ]
        ]);
    }

     public function changeStatus(Request $request)
    {
       if ($request->ajax())
       {
           $data = array('status' => $request->status );
           $Update = UserType::where('id', '=', $request->id)->update($data);

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