<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Role;
use Illuminate\Http\Request;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            'name'     => ['required','string','max:255'],
            'email'    => ['required','email','max:255','unique:users,email'],
            'password' => ['required', Password::min(8)->mixedCase()->numbers()->symbols()],
        ]);

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

        // Send verification email
        $user->sendEmailVerificationNotification();

        // Auto-login (optional). If you don’t want auto-login before verify, skip this.
        $token = auth('api')->login($user);

        $role = Role::where('name', 'fans')->first();
        $user->PivotRelationWith_roles()->sync([$role->id]);

        return response()->json([
            'message' => 'Registered successfully. Please verify your email.',
            'token'   => $token,
            'user'    => $user,
        ], 201);
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'firstname' => ['required', 'string', 'max:255'],
            'lastname' => ['nullable', 'string', 'max:255'],
            'username' => ['required', 'string', 'max:255', 'unique:users,username'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', Password::min(8)->mixedCase()->numbers()->symbols()],
            'role' => ['required', 'in:admin,fans,creator'], // optional
            'bio' => ['nullable', 'string', 'max:500'],
            'weblink' => ['nullable', 'url'],
        ]);

        try {
            $user = User::create([
                'firstname' => $data['firstname'],
                'lastname' => $data['lastname'] ?? null,
                'username' => $data['username'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
                'role' => $data['role'] ?? 'fans',
                'bio' => $data['bio'] ?? null,
                'weblink' => $data['weblink'] ?? null,
                'profile_pic' => null, // handle upload later
                'banner_pic' => null, // handle upload later
            ]);

            // Send email verification
            $user->sendEmailVerificationNotification();

            // Auto-login (optional)
            $token = auth('api')->login($user);

            return response()->json([
                'message' => 'Registered successfully. Please verify your email.',
                'token' => $token,
                'user' => $user,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Something went wrong during registration.',
            ], 500);
        }
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (!$token = auth('api')->attempt($credentials)) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }

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

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

    public function logout()
    {
        auth('api')->logout();
        return response()->json(['message' => 'Logged out']);
    }

    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60,
            'user' => auth('api')->user(),
        ]);
    }
}
