<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\UserSession;
use Carbon\Carbon;

class AuthController extends Controller
{
    public function showLogin()
    {
        if (auth()->check()) {
            return redirect()->route('dashboard');
        }

        return view('auth.login');
    }

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

        $credentials = $request->only('email', 'password');

        $user = User::where('email', $credentials['email'])->first();

        // Check if account is locked
        if ($user && $user->isLocked()) {
            Log::warning('Login attempt on locked account', [
                'email' => $credentials['email'],
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent()
            ]);
            return back()->withErrors(['login' => 'Account is locked due to too many failed attempts. Please reset your password or try again later.']);
        }

        // Attempt authentication using Laravel's Auth::attempt
        if (!Auth::attempt($credentials, $request->boolean('remember'))) {
            // Increment failed attempts
            if ($user) {
                $user->incrementFailedAttempts();
                Log::warning('Failed login attempt', [
                    'email' => $credentials['email'],
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                    'failed_attempts' => $user->failed_login_attempts
                ]);
            }

            return back()->withErrors(['login' => 'Invalid credentials']);
        }

        $request->session()->regenerate();

        // Reset failed attempts on successful login
        $user = Auth::user();
        $user->resetFailedAttempts();

        // Create custom session record
        $sessionToken = Str::random(64);
        \App\Models\Session::create([
            'user_id' => $user->id,
            'session_token' => $sessionToken,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'login_time' => now(),
            'last_activity' => now(),
            'expires_at' => now()->addMinutes(config('session.lifetime')),
            'status' => 'active',
        ]);

        UserSession::updateOrCreate(
            [
                'user_id' => $user->id,
                'session_id' => session()->getId(),
            ],
            [
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'logged_in_at' => now(),
                'last_seen_at' => now(),
                'status' => 'active',
                'logged_out_at' => null,
            ]
        );

        Log::info('User logged in successfully', [
            'user_id' => $user->id,
            'email' => $credentials['email'],
            'session_id' => session()->getId(),
            'ip' => $request->ip()
        ]);

        $request->session()->regenerateToken();

        return redirect()->intended(route('dashboard'))->cookie('session_token', $sessionToken, config('session.lifetime'));
    }

    public function logout(Request $request)
    {
        // Update custom session
        $sessionToken = $request->cookie('session_token');
        if ($sessionToken) {
            \App\Models\Session::where('session_token', $sessionToken)
                ->where('status', 'active')
                ->update([
                    'status' => 'inactive',
                    'last_activity' => now(),
                ]);
        }

        // Update user_sessions for auditing
        $userSession = UserSession::where('user_id', auth()->id())
            ->where('session_id', session()->getId())
            ->where('status', 'active')
            ->first();

        if ($userSession) {
            $userSession->update([
                'logged_out_at' => now(),
                'status' => 'logged_out',
            ]);
        }

        auth()->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login')->cookie('session_token', '', -1);
    }

    public function logoutAllDevices(Request $request)
    {
        $userId = auth()->id();

        // Revoke custom session tokens for this user
        \App\Models\Session::where('user_id', $userId)
            ->where('status', 'active')
            ->update([
                'status' => 'inactive',
                'last_activity' => now(),
            ]);

        // Update all active sessions for the user in user_sessions for auditing
        UserSession::where('user_id', $userId)
            ->where('status', 'active')
            ->update([
                'logged_out_at' => now(),
                'status' => 'revoked',
            ]);

        auth()->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        Log::info('User logged out from all devices', [
            'user_id' => $userId,
        ]);

        return redirect()->route('login')
            ->cookie('session_token', '', -1)
            ->with('success', 'Logged out from all devices successfully.');
    }
}
