<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Illuminate\Support\Facades\Storage;


class UserController extends Controller
{
    public function createUserRole(Request $request){
        $request->validate([
            'role' =>'required',
        ]);

        $user = User::where('id',$request->id)->first();
        $user = $user->syncRoles($request->role);
 
        $response = [
            'success'=>true,
            'user'  =>$user,
        ];
        return response($response,200);

    }

    public function deleteUserRole(Request $request){
        $request->validate([
            'role' =>'required',
        ]);

        $user = User::find($request->id);
        $user = $user->removeRole($request->role);

        $response = [
            'success'=>true,
            'user'  =>$user,
        ];
        return response($response,200);
    }

    public function getUser(){

        $user = User::with('roles')->get();

        $response = [
            'success'=>true,
            'user'  =>$user ,
        ];

        return response($response,200);

    }

    public function CheckUser(Request $request)
    {
        $user = User::find(12);
        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found',
            ], 404);
        }

        $isPassword = Hash::check('password123', $user->password);

        $response = [
            'success' => true,
            'isPassword' => $isPassword,
            'user' => $user,
        ];

        return response()->json($response, 200);
    }

    public function editUser(Request $request){
        $request->validate([
            'name'  =>'required',
            'email' =>'required|email',
        ]);

        $user = User::find($request->id);
        $user->name = $request->name;
        $user->email = $request->email;
        $user->user_title = $request->user_title;
        $user->user_phone = $request->user_phone;
        $user->save();

        $response = [
            'success'=>true,
            'user'  =>$user ,
        ];

        return response($response,200);

    }

    public function deleteUser(Request $request){

        $user = User::find($request->id);
        $user->delete();

        $response = [
            'success'=>true,
            'user'  =>$user,
        ];
        return response($response,200);
    }
}
