<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    public function register(Request $req)
    {
        try {
            $champs = $req->validate([
                'name' => 'required|max:255',
                'pname' => 'required|max:255',
                'nname' => 'required|max:255',
                'type_user' => 'required|max:255',
                'email' => 'required|email|unique:users',
                'password' => 'required|confirmed'
            ]);

            $userData = User::create($champs);
            $token = $userData->createToken($req->name);
            return [
                'data' => $userData,
                'token' => $token->plainTextToken
            ];
        } catch (\Throwable $th) {
            return $th;
        }
    }
    public function login(Request $req)
    {
        try {
            $req->validate([
                'email' => 'required|email|exists:users',
                'password' => 'required '
            ]);
            $user = User::where('email', $req->email)->first();

            if (!$user || !Hash::check($req->password, $user->password)) {
                return ['message' => 'votre mail ou votre mot de passe incorrect'];
            } else {
                $token = $user->createToken($user->name);
                return [
                    'data' => $user,
                    'token' => $token->plainTextToken
                ];
            }
        } catch (\Throwable $th) {
            return $th;
        }
    }
    public function logout(Request $req)
    {
        try {
            $req->user()->tokens()->delete();
            return ['message' => 'vous etes deconnecte '];
        } catch (\Throwable $th) {
            return $th;
        }
    }
}
