<?php

namespace App\Http\Controllers\Api;

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


class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

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

        return response()->json(['token' => $token], 201);
    }

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            $token = $user->createToken('Token Name')->plainTextToken;
            return response()->json(['token' => $token], 200);
        }

        return response()->json(['error' => 'Unauthorized'], 401);
    }

    public function getUserInfoFromEmail(Request $request) {
        $email = $request->email;

        if (!$email) {
            return response()->json(['error' => 'Missing require info in request'], 401);
        }

        try {
            $user = User::where('email', $email)->first();
        } catch (\Exception $e) {
            return response()->json(['error' => 'Invalid Request '], 401);
        }

        if (!$user) {
            return response()->json(['error' => 'Invalid request'], 401);
        }

        // Formatez les informations de l'utilisateur pour la réponse API
        $formattedUserDataInfo = [
            'user_type' => $user->user_type,
            'name' => $user->name,
            'email' => $user->email
            // ... Autres informations de l'utilisateur
        ];

        return response()->json($formattedUserDataInfo);
    }
}
