<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
// use Illuminate\Support\Facades\Auth; // JWTAuth facade is better if available, or just auth() helper
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    public function token(Request $request)
    {
        $credentials = $request->only('username', 'password');
        
        // Wordpress uses 'username', Laravel uses 'email' usually. 
        // We'll allow 'username' to map to 'email' or 'name' depending on logic.
        // For now assume param is 'username' but we check against 'email'.
        
        $loginData = [
            'email' => $credentials['username'] ?? $request->input('email'),
            'password' => $credentials['password'],
        ];

        if (! $token = auth('api')->attempt($loginData)) {
            return response()->json([
                'code' => 'jwt_auth_invalid_credentials',
                'message' => 'Incorrect username or password',
                'data' => [
                    'status' => 403
                ]
            ], 200); // 200 OK because the legacy API seems to return JSON error with 200 status?
                     // Request says: result['success'] = result['code'] == 'jwt_auth_valid_token';
                     // The login example doesn't show full failure response but usually WP plugins return 200 with error code.
                     // But standard JWT returns 401. I'll stick to 403 or 401 but return JSON structure.
        }

        return response()->json([
            'token' => $token,
            'user_email' => $request->input('username'), // mirroring typical WP JWT response
            'user_nicename' => auth('api')->user()->name,
            'user_display_name' => auth('api')->user()->name,
        ]);
    }

    public function validateToken()
    {
        // Wrapper for checking if token is valid. 
        // Middleware should handle this, but if we reach here, it's valid.
        return response()->json([
            'code' => 'jwt_auth_valid_token',
            'data' => [
                'status' => 200
            ]
        ]);
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string|max:255', // WP Style
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => $validator->errors()->first(),
                'data' => $validator->errors()
            ], 200);
        }

        $user = User::create([
            'name' => $request->username,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => 'user', 
        ]);
        
        // initialize wallet
        $user->wallet()->create(['balance' => 0]);

        return response()->json([
            'code' => 200,
            'message' => 'Registration successful',
            'data' => $user
        ]);
    }
    
    public function user(Request $request)
    {
        return response()->json($request->user());
    }
}
