<?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\Validation\ValidationException;
use Illuminate\Support\Str;
class AuthController extends Controller
{
    /**
     * Register a new user
     */
    public function register(Request $request)
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|email|unique:users',
                'password' => 'required|min:8|confirmed'
            ]);

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

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

            return response()->json([
                'message' => 'User registered successfully',
                'user' => $user,
                'token' => $token
            ], 201);
        } catch (ValidationException $e) {
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        }
    }

    /**
     * Login user
     */
    public function login(Request $request)
    {
        try {
            $validated = $request->validate([
                'email' => 'required|email',
                'password' => 'required|string'
            ]);

            $user = User::where('email', $validated['email'])->first();

            if (!$user || !Hash::check($validated['password'], $user->password)) {
                throw ValidationException::withMessages([
                    'email' => ['The provided credentials are incorrect.'],
                ]);
            }

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

            return response()->json([
                'message' => 'Login successful',
                'user' => $user,
                'token' => $token
            ], 200);
        } catch (ValidationException $e) {
            return response()->json([
                'message' => 'Invalid credentials',
                'errors' => $e->errors()
            ], 401);
        }
    }

    /**
     * Logout user
     */
    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();

        return response()->json([
            'message' => 'Logged out successfully'
        ], 200);
    }

    /**
     * Get current authenticated user
     */

public function profile(Request $request)
{
    if (!$request->user()) {
        return response()->json([
            'message' => 'Unauthorized'
        ], 401);
    }

    $user = $request->user();

    // 🔥 حساب التقدم
    $currentLevelXP = pow(($user->level - 1), 2) * 50;
    $nextLevelXP = pow($user->level, 2) * 50;
    $remainingXP = $nextLevelXP - $user->xp;

    return response()->json([
        'user' => array_merge($user->toArray(), [

            // 🔥 الإضافات فقط
            'current_level_xp' => $currentLevelXP,
            'next_level_xp' => $nextLevelXP,
            'remaining_xp' => $remainingXP,

        ])
    ]);
}




public function googleLogin(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'name' => 'required',
        'photo' => 'nullable|string',
    ]);

    $user = User::where('email', $request->email)->first();

    if (!$user) {
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'photo' => $request->photo,
            'password' => bcrypt(Str::random(16)),
        ]);
    } else {
        if ($request->photo) {
            $user->update([
                'photo' => $request->photo,
            ]);
        }
    }

    $user->tokens()->delete();

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

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