<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nev' => 'required|string',
            'email' => 'required|email|unique:felhasznalok',
            'felh_nev' => 'required|string|unique:felhasznalok',
            'jelszo' => 'required|string|min:6',
            'jelszo_confirmation' => 'required|same:jelszo',
            'is_admin' => 'boolean'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        $user = User::create([
            'nev' => $request->nev,
            'email' => $request->email,
            'felh_nev' => $request->felh_nev,
            'jelszo' => $request->jelszo,
            'is_admin' => $request->is_admin ?? false
        ]);

        return response()->json([
            'message' => 'Sikeresen regisztrált felhasználó',
            'user' => $user
        ], 201);
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'felh_nev' => 'required|string',
            'jelszo' => 'required|string'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        $credentials = [
            'felh_nev' => $request->felh_nev,
            'password' => $request->jelszo
        ];

        if (!$token = auth('api')->attempt($credentials)) {
            return response()->json(['error' => 'Helytelen felhasználónév vagy jelszó'], 401);
        }

        return $this->respondWithToken($token);
    }

    public function me()
    {
        return response()->json(auth('api')->user());
    }

    public function logout()
    {
        auth('api')->logout();

        return response()->json(['message' => 'Sikeres kijelentkezés']);
    }

    public function refresh()
    {
        try {
            $token = JWTAuth::parseToken()->refresh();
            return $this->respondWithToken($token);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Could not refresh token'], 401);
        }
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => config('jwt.ttl') * 60,
            'user' => auth('api')->user()
        ]);
    }
}