<?php

namespace App\Http\Controllers;

use App\Http\Requests\ActivateAccountRequest;
use App\Http\Requests\ChangePasswordRequest;
use App\Http\Requests\LoginRequest;
use App\Mail\ActivationMail;
use App\Http\Requests\RegisterRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller
{
    public function createUser(RegisterRequest $request)
{
    $tempPassword = Str::random(10);

    $user = User::create([
        'name' => $request->name,
        'surname' => $request->surname,
        'email' => $request->email,
        'role' => $request->role,
        'password' => Hash::make($tempPassword),
        'activation_token' => Str::random(64),
    ]);

   // ✅ Build frontend activation URL dynamically from .env
    $activationUrl = config('app.frontend_url') . '/dashboard/accountActivation?token=' . $user->activation_token;

    // ✅ Send activation email
    Mail::to($user->email)->send(new ActivationMail($user, $tempPassword, $activationUrl));

    Log::info("Account activated", ['email' => $user->email, 'ip' => request()->ip()]);


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

    /**
     * ✅ User Activates Account & Sets a New Password
     */
    public function activateAccount(ActivateAccountRequest $request)
{
    // Find the user by activation token
    $user = User::where('activation_token', $request->token)->first();

    if (!$user) {
        return response()->json(['error' => 'Invalid activation token.'], 400);
    }

    // ✅ Update user details
    $user->password = Hash::make($request->new_password);
    $user->activation_token = null; // Remove token after activation
    $user->email_verified_at = now();
    $user->save();

    return response()->json(['message' => 'Account activated successfully. You can now log in.'], 200);
}

    /**
     * ✅ User Login
            */
          public function login(LoginRequest $request)
            {
                $credentials = $request->only('email', 'password');

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

                if (!$user) {
                    // Log real reason, hide from user
                    Log::info('Login failed: email not found', ['email' => $request->email]);

                    return response()->json([
                        'message' => 'Invalid credentials.'
                    ], 401);
                }

                if (!Hash::check($request->password, $user->password)) {
                    Log::info('Login failed: incorrect password', [
                        'email' => $request->email
                    ]);

                    return response()->json([
                        'message' => 'Invalid credentials.'
                    ], 401);
                }

                // Authentication successful
                $token = $user->createToken($user->email)->plainTextToken;

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


    /**
     * ✅ Change Password (User Must Be Logged In)
     */
    public function changePassword(ChangePasswordRequest $request)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();

        // Check if the current password is correct
        if (!Hash::check($request->current_password, $user->password)) {
            return response()->json(['error' => 'Current password is incorrect.'], 400);
        }

        // Check if the temporary password is correct
        if (!Hash::check($request->temporary_password, $user->password)) {
            return response()->json(['error' => 'Temporary password is incorrect.'], 401);
        }

        // Update the password
        $user->update(['password' => Hash::make($request->new_password)]);

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

    /**
     * ✅ Get Logged-in User Details
     */
    public function userDetails(Request $request)
    {
        return response()->json($request->user());
    }

    /**
     * ✅ Logout (Revokes User Token)
     */
    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();
        return response()->json(['message' => 'Logged out successfully'], 200);
    }

    /**
     * ✅ Admin & Super Admin - List All Users
     */
    public function listUsers()
    {
        return response()->json(User::all(), 200);
    }

    /**
     * ✅ Admin & Super Admin - Retrieve a Specific User
     */
    public function getUser($id)
    {
        $user = User::find($id);
        if (!$user) {
            return response()->json(['error' => 'User not found.'], 404);
        }

        return response()->json($user, 200);
    }

    /**
     * ✅ Admin & Super Admin - Update User Details
     */
    public function updateUser(Request $request, $id)
{
    $user = User::find($id);

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

    // Update user details
    $user->update($request->all());

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

    /**
     * ✅ Admin & Super Admin - Delete User
     */
    public function deleteUser($id)
    {
        $user = User::find($id);
        if (!$user) {
            return response()->json(['error' => 'User not found.'], 404);
        }

        $user->delete();

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

