<?php
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function register(Request $request) {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed',
            'role' => 'required|in:Admin,Buyer,Content Creator',
            // 'role' => 'required|in:Admin,Content Creator,Buyer',

        ]);

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

        $user->assignRole($request->role);

        event(new Registered($user));
        // $user->sendEmailVerificationNotification();

        return response()->json(['message' => 'Registered! Please verify email.']);
    }

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

    //     if (!Auth::attempt($request->only('email', 'password'), $request->has('remember'))) {
    //         return response()->json(['message' => 'Invalid credentials'], 401);
    //     }

    //     $user = Auth::user();

    //     if (!$user->hasVerifiedEmail()) {
    //         return response()->json(['message' => 'Please verify your email.'], 403);
    //     }

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

    //     return response()->json([
    //         'message' => 'Logged in successfully',
    //         'token'   => $token,
    //         'role'    => $user->getRoleNames()
    //     ]);
    // }


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

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

    //     // If user doesn't exist
    //     if (!$user) {
    //         return response()->json(['message' => 'Invalid credentials'], 401);
    //     }

    //     // Check if the user's profile has been deleted
    //     if ($user->status === 'deleted') {
    //         return response()->json(['message' => 'Your profile has been deleted. Please register again.'], 403);
    //     }

    //     // Attempt to authenticate the user
    //     if (!Auth::attempt($request->only('email', 'password'), $request->has('remember'))) {
    //         return response()->json(['message' => 'Invalid credentials'], 401);
    //     }

    //     // If the user's email is not verified
    //     if (!$user->hasVerifiedEmail()) {
    //         return response()->json(['message' => 'Please verify your email.'], 403);
    //     }

    //     // Generate an authentication token
    //     $token = $user->createToken('auth_token')->plainTextToken;

    //     // Return the successful login response with token and role
    //     return response()->json([
    //         'message' => 'Logged in successfully',
    //         'token'   => $token,
    //         'role'    => $user->getRoleNames()
    //     ]);
    // }
    
        {
   
        $request->validate
        ([
        'email'    => 'required|email',
        'password' => 'required',
        ]);

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

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

            // Check if user is deleted
            if ($user->status === 'deleted') {
                return response()->json(['message' => 'Your profile has been deleted. Please register again.'], 403);
            }

            // Check if user is inactive
            if ($user->status === 'inactive') {
                return response()->json(['message' => 'Your account is inactive. Please contact support.'], 403);
            }

            // Attempt login
            if (!Auth::attempt($request->only('email', 'password'), $request->has('remember'))) {
                return response()->json(['message' => 'Invalid credentials'], 401);
            }

            // Check if email verified
            if (!$user->hasVerifiedEmail()) {
                return response()->json(['message' => 'Please verify your email.'], 403);
            }

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

            return response()->json([
                'message' => 'Logged in successfully',
                'token'   => $token,
                'id'      => $user->id,
                'role'    => $user->getRoleNames()
            ]);
    }


    public function logout(Request $request) {
        $request->user()->tokens()->delete();
        return response()->json(['message' => 'Logged out']);
    }

    public function verifyEmail(Request $request, $id, $hash) {
        $user = User::findOrFail($id);
        if (! hash_equals((string) $hash, sha1($user->getEmailForVerification()))) {
            return response()->json(['message' => 'Invalid verification link.'], 403);
        }

        if ($user->hasVerifiedEmail()) {
            return response()->json(['message' => 'Email already verified.']);
        }

        $user->markEmailAsVerified();
        return response()->json(['message' => 'Email verified successfully.']);
    }

    public function creatorHome(Request $request, $id)
    {
        $authUser = $request->user();

        // Allow access only to Admin or the creator themselves
        if (!$authUser->hasAnyRole(['Content Creator', 'Admin']) && $authUser->id != $id) {
            return response()->json(['message' => 'Access denied.'], 403);
        }

        $user = User::find($id);

        if (!$user || !$user->hasAnyRole(['Content Creator', 'Admin'])) {
            return response()->json(['message' => 'User not found or not a valid creator/admin.'], 404);
        }

        return response()->json([
            'message' => 'Welcome, ' . $user->name,
            'name'    => $user->name,
            'email'   => $user->email,
            'role'    => $user->getRoleNames()->first(),
            'actions' => [
                'add_gig' => '/api/add-gig'
            ]
        ]);
    }



}
