<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\User;
use App\Models\PendingUser;
use App\Models\HoldUser;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Events\LawyerStatusUpdated;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;


class AuthController extends Controller
{
        public function register3(Request $request)
{
    $fields = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'phone_number' => [
            'required',
            'string',
            'max:20',
            'unique:users,phone_number',
            'regex:/^(\+?[1-9]\d{9,14}|0\d{9})$/'
        ],
        'role' => ['required', Rule::in([0, 1, 2])], // 0=user, 1=lawyer, 2=admin
        'password' => 'required|confirmed|min:6'
    ]);

    // Hash password
    $fields['password'] = Hash::make($fields['password']);

    // Create user
    $user = User::create($fields);

    // Send verification email for both user and lawyer
    $user->sendEmailVerificationNotification();

    return response()->json([
        'message' => 'Registration successful. Please verify your email before logging in.',
        'user' => $user
    ], 201);
}

public function register(Request $request)
{
    $fields = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'phone_number' => [
            'required',
            'string',
            'max:20',
            'unique:users,phone_number',
            'regex:/^(\+?[1-9]\d{9,14}|0\d{9})$/'
        ],
        'role' => ['required', Rule::in([0, 1, 2])], // 0=user, 1=lawyer, 2=admin
        'password' => 'required|confirmed|min:6'
    ]);

    // Hash password
    $fields['password'] = Hash::make($fields['password']);

    // Create user
    $user = User::create($fields);

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

    return response()->json([
        'message' => 'Your account is successfully created, please log in to your email and verify your email to complete the Registration',
        'user' => $user,
        'email_verified' => $user->hasVerifiedEmail() // This will be false initially
    ], 201);
}



    public function register2(Request $request)
{
    $fields = $request->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users|unique:pending_users',
        'phone_number' => [
            'required',
            'string',
            'max:20',
            'unique:users,phone_number',
            'unique:pending_users,phone_number',
            'regex:/^(\+?[1-9]\d{9,14}|0\d{9})$/'
        ],
        'role' => ['required', Rule::in([0, 1, 2])],
        'password' => 'required|confirmed'
    ]);

    // If role == 1, send to PendingUser for approval
    if ($fields['role'] == 1) {
        $fields['password'] = Hash::make($fields['password']);

        PendingUser::create($fields);

        return response()->json([
            'message' => 'Your registration request has been submitted for approval. Please wait for admin approval.'
        ], 202);
    }

    // Otherwise, register immediately
    $fields['password'] = Hash::make($fields['password']);
    $user = User::create($fields);

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

    // Create Sanctum token
    $token = $user->createToken($request->name)->plainTextToken;

    return response()->json([
        'message' => 'User registered successfully. A verification email has been sent to your email address.',
        'user' => $user,
        'token' => $token
    ], 201);
}

    public function approveUser($pendingUserId)
{
    $pendingUser = PendingUser::findOrFail($pendingUserId);

    // Create user in the users table
    $user = User::create([
        'name' => $pendingUser->name,
        'email' => $pendingUser->email,
        'phone_number' => $pendingUser->phone_number,
        'role' => $pendingUser->role,
        'password' => $pendingUser->password,
    ]);

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

    // Remove from pending list
    $pendingUser->delete();

    return response()->json([
        'message' => 'User approved successfully. Verification email sent.',
        'user' => $user
    ]);
}


    public function rejectUser($pendingUserId)
    {
        $pendingUser = PendingUser::find($pendingUserId);

        if (!$pendingUser) {
            return response()->json([
                'message' => 'Pending user not found.'
            ], 404);
        }

        // Delete the pending user
        $pendingUser->delete();

        return response()->json([
            'message' => 'Pending user has been rejected and removed.'
        ]);
    }





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

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

    if (!$user || !Hash::check($request->password, $user->password)) {
        return response()->json([
            'message' => 'The provided credentials are incorrect.'
        ], 401);
    }

    // Check if email is verified
    if (!$user->hasVerifiedEmail()) {
        // Send another verification link automatically
        $user->sendEmailVerificationNotification();

        return response()->json([
            'message' => 'Your email address is not verified. A new verification link has been sent to your email.'
        ], 403);
    }

    // Create Sanctum token
    $token = $user->createToken($user->name)->plainTextToken;

    return response()->json([
        'message' => 'Login successful.',
        'user' => $user,
        'token' => $token
    ], 200);
}


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

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

    if (!$user || !Hash::check($request->password, $user->password)) {
        return response()->json([
            'message' => 'The provided credentials are incorrect.'
        ], 401);
    }

    // Check if email is verified
    if (!$user->hasVerifiedEmail()) {
        $user->sendEmailVerificationNotification();

        return response()->json([
            'message' => 'Your email address is not verified. A new verification link has been sent to your email.'
        ], 403);
    }

    // Update last activity and mark as active if the user is a lawyer
    if ($user->role == 1) {
        $user->last_activity = now();
        $user->is_active = true;
        $user->save();

        // Optional: broadcast event for real-time frontend updates
        event(new \App\Events\LawyerStatusUpdated($user->id, 'active'));
    }

    // Create Sanctum token
    $token = $user->createToken($user->name)->plainTextToken;

    return response()->json([
        'message' => 'Login successful.',
        'user' => $user,
        'token' => $token
    ], 200);
}



    public function logoutExist(Request $request)
    {
        $request->user()->tokens()->delete();

        return [
            'message' => 'You are logged out'
        ];
    }


    public function logout(Request $request)
{
    $user = $request->user();

    if ($user && $user->role == 1) {
        $user->last_activity = null;
        $user->save();

        event(new LawyerStatusUpdated($user->id, 'inactive'));
    }

    // using sanctum tokens:
    if ($request->user()) {
        $request->user()->currentAccessToken()?->delete(); // or tokens()->delete() depending on implementation
    }

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


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

    $status = Password::sendResetLink($request->only('email'));

    if ($status === Password::RESET_LINK_SENT) {
        return response()->json([
            'message' => 'Password reset link sent to your email.'
        ], 200);
        }

    if ($status === Password::INVALID_USER) {
        return response()->json([
            'message' => 'No account found with this email.'
        ], 404);
        }
}


//Reset password
public function resetPassword(Request $request)
{
    $request->validate([
        'token' => 'required',
        'email' => 'required|email',
        'password' => 'required|min:6|confirmed',
    ]);

    $status = Password::reset(
        $request->only('email', 'password', 'password_confirmation', 'token'),
        function ($user) use ($request) {
            $user->forceFill([
                'password' => Hash::make($request->password)
            ])->save();
        }
    );

    if ($status === Password::PASSWORD_RESET) {
        return response()->json([
            'message' => 'Password has been reset successfully.'
        ], 200);
    }

    return response()->json([
        'message' => 'Invalid token or email.'
    ], 400);
}






 public function putUserOnHold($userId, Request $request)
    {
        $user = User::findOrFail($userId);

        // Create record in hold_users table
        $holdUser = HoldUser::create([
            'name' => $user->name,
            'email' => $user->email,
            'phone_number' => $user->phone_number,
            'role' => $user->role,
            'password' => $user->password,
            'email_verified_at' => $user->email_verified_at,
            'hold_reason' => $request->input('reason', null)
        ]);

        // Delete user's tokens
        $user->tokens()->delete();

        // Remove from users table
        $user->delete();

        return response()->json([
            'message' => 'User has been put on hold successfully.',
            'hold_user' => $holdUser
        ], 200);
    }

    /**
     * Restore user from hold_users table to users table
     */
    public function restoreUserFromHold($holdUserId)
    {
        $holdUser = HoldUser::findOrFail($holdUserId);

        // Move back to users table
        $user = User::create([
            'name' => $holdUser->name,
            'email' => $holdUser->email,
            'phone_number' => $holdUser->phone_number,
            'role' => $holdUser->role,
            'password' => $holdUser->password,
            'email_verified_at' => $holdUser->email_verified_at,
        ]);

        // Remove from hold_users table
        $holdUser->delete();

        return response()->json([
            'message' => 'User has been restored successfully.',
            'user' => $user
        ], 200);
    }
    
    public function getHoldUsers()
    {
        return response()->json([
            'hold_users' => HoldUser::all()
        ]);
    }




    // Get list of pending lawyers
    public function getPendingUsers(){

        return PendingUser::all();

    }

    public function getAllUsers(){
        return User::where('role' , 0)->get();
    }

    public function deleteUser(User $user)
{
    $user->delete();

    return response()->json([
        'message' => 'User deleted successfully'
    ]);
}

 /**
     * Update user's name and phone number
     */
    public function updateUser(Request $request, $userId)
    {
        $user = User::findOrFail($userId);

        $fields = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'phone_number' => [
                'sometimes',
                'required',
                'string',
                'max:20',
                'regex:/^(\+?[1-9]\d{9,14}|0\d{9})$/',
                Rule::unique('users', 'phone_number')->ignore($user->id)
            ]
        ]);

        $user->update($fields);

        return response()->json([
            'message' => 'User updated successfully.',
            'user' => $user
        ], 200);
    }


}
