<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
use App\Models\User;
use Log;

class AuthController extends Controller
{
 
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        try {
            $credentials = $request->only('email', 'password');
    
            if (!Auth::attempt($credentials)) {
                throw ValidationException::withMessages([
                    'email' => ['Email atau Password tidak sesuai'],
                ]);
            }
    
            $user = Auth::user();
    
            $token = $user->createToken('authToken', ['*'], now()->addSeconds(config('sanctum.expiration')))->plainTextToken;
    
            return response()->json([
                'status' => true,
                'data' => [
                    'token' => $token, 
                    'user' => [
                        'id' => $user->id,
                        'role' => $user->role,
                        'fullName' => $user->name,
                        'username' => $user->name,
                        'email' => $user->email
                    ]
                ],
                'message' => 'Berhasil Login'
            ]);
        } catch (ValidationException $e) {
            Log::error('login error : '.json_encode($e->getMessage()));
            return response()->json([
                'status' => false,
                'data' => [],
                'message' => $e->getMessage()
            ], 500);
        } catch (Exception $e) {
            Log::error('login error : '.json_encode($e->getMessage()));
            return response()->json([
                'status' => false,
                'data' => [],
                'message' => 'Gagal menghubungkan ke server'
            ], 500);
        }
    }

    public function logout(Request $request)
    {
        try {

            $request->user()->tokens()->delete();
    
            return response()->json(['message' => 'Logged out successfully']);
        } catch (Exception $e) {
            return response()->json([
                'status' => false,
                'data' => [],
                'message' => 'Gagal menghubungkan ke server'
            ], 500);
        }
    }

    public function me(Request $request)
    {
        try {
            return response()->json([
                'status' => true,
                'data' => $request->user(),
                'message' => 'Logged out successfully'
            ]);
        } catch (Exception $e) {
            return response()->json([
                'status' => false,
                'data' => [],
                'message' => 'Gagal menghubungkan ke server'
            ], 500);
        }
    }

}
