<?php

namespace App\Http\Controllers\Api;

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

class AuthController extends Controller
{
    // Register user
    public function register(Request $request)
{
    // Validate the input
    $validator = Validator::make($request->all(), [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|confirmed|min:8',
    ]);

    // If validation fails, return errors
    if ($validator->fails()) {
        return response()->json(['error' => $validator->errors()], 422);
    }

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

    // Create token using Passport
    $token = $user->createToken('YourAppName')->accessToken;

    // Respond with success, user data, and the token
    return response()->json([
        'status' => 200,
        'message' => 'Registration successful!',
        'token' => $token,
        'data' => $user,
    ], 200);
}


    // Login user
    public function login(Request $request)
    {
        // Validate input
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            // Create token using Passport
            $token = $user->createToken('YourAppName')->accessToken;

            return response()->json([
                'status' => 200,
                'message' => 'Login successful!',
                'token' => $token,
                'data' => $user,
            ], 200);
        } else {
            return response()->json([
                'status' => 401,
                'message' => 'Unauthorized',
            ], 401);
        }
    }
}
