<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use App\Models\User;
use Illuminate\Support\Str;
use Spatie\Permission\Models\Role;

class RegisterController extends Controller
{//validate register user send response

    public function register(RegisterRequest $request){
        $user=User::create([
            'name'=>$request->name,
            'email'=>$request->email,
            'password'=>bcrypt($request->password),
            'code'=> Str::random(4),
            'phone'=> $request->phone,
            'parent_phone'=> $request->parent_phone,
            'class'=> $request->class,
            'subject_id'=> $request->subject_id,
            'grade'=> $request->grade ?? null,
        ]);
        $user_role=Role::where('name' , $request->role)->first();
        if($user_role){
            $user->assignRole($user_role);
        }

        $token = $user->createToken('Token')->plainTextToken;

        $user->token = $token;

        return response()->json([
            'status'=>200,
            'message'=> 'User Created Successfully',
            'data'=>$user,
            'groups' => $user->groups,
            "token"=>$token
        ],200);

    }
}

