<?php

namespace App\Http\Controllers\API\UserRole;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Support\Arr;
use App\Helpers\CurrentUser;
use App\Models\User;
use Validator;
use DB;
use Hash;
use Auth;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Check user has permission...
        if (!auth()->user()->hasPermissionTo('user-list', 'web')) {
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }

        //To fet userId..
        $userId = CurrentUser::getUserId();

        if(Auth::user()->role == 'superadmin'){
            $userData = User::orderBy('id','DESC')->whereNotIn('role',['superadmin'])->get();
            $roleData = Role::whereNotIn('name', ['superadmin'])->get();
        }elseif(Auth::user()->role == 'admin'){
            $userData = User::orderBy('id','DESC')->whereNotIn('role', ['superadmin','admin'])->where('admin_id', $userId)->get();
            $roleData = Role::whereNotIn('name', ['superadmin','admin'])->get();
        }else{
            $userRoleName = Auth::user()->role;
            $userData = User::orderBy('id','DESC')->whereNotIn('role', ['superadmin','admin',$userRoleName])->where('admin_id', $userId)->get();
            $roleData = Role::whereNotIn('name', ['superadmin','admin',$userRoleName])->get();
        }
        
        $userCount = $userData->count();

        if(!empty($userData)){
            return response()->json([
                'message'   =>  'Successfully loaded ata.',
                'userCount'   =>  $userCount,
                'userData'   =>  $userData,
                'roleData'   =>  $roleData,
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
				'message'   =>  'Sorry you have no data.',
                'status_code'   => 500
			], 500);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // Check user has permission...
        if (!auth()->user()->hasPermissionTo('user-create', 'web')) {
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }

        if(Auth::user()->role == 'superadmin'){
            $roleData = Role::whereNotIn('name', ['superadmin'])->get();
        }elseif(Auth::user()->role == 'admin'){
            $roleData = Role::whereNotIn('name', ['superadmin','admin'])->get();
        }else{
            $userRoleName = Auth::user()->role;
            $roleData = Role::whereNotIn('name', ['superadmin','admin',$userRoleName])->get();
        }

        if(!empty($roleData)){
            return response()->json([
                'message'   =>  'Successfully loaded ata.',
                'roleData'   =>  $roleData,
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
				'message'   =>  'Sorry you have no data.',
                'status_code'   => 500
			], 500);
        }
    }

    /**
     * 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',
            'email' => 'required|email|unique:users',
            'password' => 'required|same:password_confirmation',
            'roles' => 'required'
        ]);

        if ($validator->fails()) {
        	return response(['errors'=>$validator->errors()->all()], 422);
        }
        
        // Check user has permission...
        if (!auth()->user()->hasPermissionTo('user-create', 'web')) {
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }
    
        $data = $request->all();
        $userRole = Role::where('id', $request->roles)->first();
        $data['role'] = $userRole->name;

        if(Auth::user()->role == 'superadmin'){
            $data['admin_id'] = Auth::user()->id;
        }else{
            $data['admin_id'] = Auth::user()->admin_id;
        }

        $data['password'] = Hash::make($data['password']);

        if($user = User::create($data)){
            $user->roles()->sync($request->input('roles', []));

            return response()->json([
            'message'   =>  'User created successfully.',
            'userData'   =>  $user,
            'status_code'   => 201
        ], 201);
        }else{
            return response()->json([
				'message'   =>  'Something is wrong.!',
                'status_code'   => 500
			], 500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // Check user has permission...
        if (!auth()->user()->hasPermissionTo('user-list', 'web')) {
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }

       $singleUserData = User::where('id', $id)->first();

        // Check user has permission...
        if (auth()->user()->hasPermissionTo('user-list', 'web')) {
            if(isset($singleUserData) && $singleUserData != null){
                return response()->json([
                    'message'   =>  'User loaded successfully.',
                    'singleUserData'   => $singleUserData,
                    'status_code'   => 201
                ], 201);
            }else{
                return response()->json([
                    'message'   =>  'Sorry, User not found.!',
                    'status_code'   => 500
                ], 500);
            }
        }else{
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // Check user has permission...
        if (!auth()->user()->hasPermissionTo('user-edit', 'web')) {
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }
        
        if(Auth::user()->role == 'superadmin'){
            $roleData = Role::whereNotIn('name', ['superadmin'])->get();
        }elseif(Auth::user()->role == 'admin'){
            $roleData = Role::whereNotIn('name', ['superadmin','admin'])->get();
        }else{
            $userRoleName = Auth::user()->role;
            $roleData = Role::whereNotIn('name', ['superadmin','admin',$userRoleName])->get();
        }

        $singleUserData = User::find($id);
        if(!empty($singleUserData)){
            return response()->json([
                'message'   =>  'Successfully loaded ata.',
                'singleUserData'   =>  $singleUserData,
                'roleData'   =>  $roleData,
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
				'message'   =>  'Sorry you have no data.',
                'status_code'   => 500
			], 500);
        }
    }

    /**
     * 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',
            'email' => 'required|email|unique:users,email,'.$id,
            'password' => 'nullable|same:password_confirmation',
            'roles' => 'required'
        ]);

        if ($validator->fails()) {
        	return response(['errors'=>$validator->errors()->all()], 422);
        }
        
        // Check user has permission...
        if (!auth()->user()->hasPermissionTo('user-edit', 'web')) {
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }
    
        $data = $request->all();
        $userRole = Role::where('id', $request->roles)->first();
        $data['role'] = $userRole->name;
        $data['password'] = Hash::make($data['password']);
        if(Auth::user()->role == 'superadmin'){
            $data['admin_id'] = Auth::user()->id;
        }else{
            $data['admin_id'] = Auth::user()->admin_id;
        }

        $singleUserData = User::find($id);
        if($singleUserData->update($data)){
            DB::table('model_has_roles')->where('model_id',$id)->delete();
            $singleUserData->roles()->sync($request->input('roles', []));

            return response()->json([
            'message'   =>  'User updated successfully.',
            'singleUserData'   =>  $singleUserData,
            'status_code'   => 201
        ], 201);
        }else{
            return response()->json([
				'message'   =>  'Something is wrong.!',
                'status_code'   => 500
			], 500);
        }
        
    
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // Check user has permission...
        if (!auth()->user()->hasPermissionTo('user-delete', 'web')) {
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }

        $singleUserData = User::findOrFail($id);
        if($singleUserData->delete()){
            return response()->json([
                'message'   =>  'User deleted successfully.',
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
				'message'   =>  'Something is wrong.!',
                'status_code'   => 500
			], 500);
        }
    }



    //To active user...
    public function userActive($id)
    {
        // Check user has permission...
        if (!auth()->user()->hasPermissionTo('user-edit', 'web')) {
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }

        $singleUserData = User::findOrFail($id);
        $singleUserData->status = 1;
        if($singleUserData->save()){
            return response()->json([
                'message'   =>  'User activated successfully.',
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
				'message'   =>  'Something is wrong.!',
                'status_code'   => 500
			], 500);
        }
    }
    
    //To active user...
    public function userInactive($id)
    {
        // Check user has permission...
        if (!auth()->user()->hasPermissionTo('user-edit', 'web')) {
            return response()->json([
                'message'   =>  'Oops! Access Denied.',
                'status_code'   => 403
            ], 403);
        }

        $singleUserData = User::findOrFail($id);
        $singleUserData->status = 0;
        if($singleUserData->save()){
            return response()->json([
                'message'   =>  'User inactivated successfully.',
                'status_code'   => 201
            ], 201);
        }else{
            return response()->json([
				'message'   =>  'Something is wrong.!',
                'status_code'   => 500
			], 500);
        }
    }


    public function userPassword(Request $request, $id)
    {
        $request->validate([
            'new_password' => 'required',
            'confirm_password' => 'required',
        ]);

            if ($request->new_password == $request->confirm_password) {

                User::find($id)->update([
                    'password' => Hash::make($request->new_password)
                ]);

                return redirect()->route('users.index')->with('message','Successfully Password Updated');

            }else{
                return redirect()->back()->with('error','Something is wrong.!');
            }

        
    }

}
