<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Mail;
use App\Mail\NewAccountEmail;
use Illuminate\Support\Facades\Auth;


class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'firstName' => 'required|string|max:255',
            'lastName' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8',
        ]);

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

        Mail::to($request->email)->send(new NewAccountEmail($request->firstName));

        return response()->json([
            'token' => 'user created',
        ], 201);
    }


    public function loginToken(Request $request)
    {
        
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);         
        
        $user = User::where('email', $credentials['email'])->first();
       
        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'errr' => 'The provided credentials are incorrect.'
            ], 201);
        }

        return response()->json([
            'token' => $user->createToken('api-token')->plainTextToken,
        ]);

    }

    public function logoutToken(Request $request)
    {
        // Revoke the current access token
        $request->user()->currentAccessToken()->delete();
        
        return response()->json(['message' => 'Successfully logged out']);
    }




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

        // Ensure any existing session is properly cleared before login
        try {
            if (auth()->check()) {
                \Log::info('Clearing existing session before login', [
                    'existing_user_id' => auth()->id(),
                    'session_id' => $request->session()->getId(),
                ]);
                auth('web')->logout();
            }
            
            // Invalidate and regenerate session to ensure clean state
            $request->session()->invalidate();
            $request->session()->regenerateToken();
        } catch (\Exception $e) {
            \Log::warning('Session cleanup before login failed', [
                'error' => $e->getMessage(),
            ]);
        }

        if (Auth::attempt($credentials, $request->get('remember'))) {
            $request->session()->regenerate();

            return response()->json([
                'message' => 'ok',
                'remember' => $request->get('remember')
            ]);
        }

        \Log::warning('Login failed', [
            'email' => $credentials['email'],
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return response()->json([
            'message' => 'Log in details incorrect. Please try again, or use the password reset form.',
        ], 422);
    }

    public function logoutWeb(Request $request)
    {
        try {
            // Log the logout attempt
            \Log::info('Logout attempt', [
                'user_id' => auth()->id(),
                'session_id' => $request->session()->getId(),
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ]);

            // Clear the authentication
            auth('web')->logout();
            
            // Invalidate the session
            $request->session()->invalidate();
            
            // Regenerate session token
            $request->session()->regenerateToken();
            
            \Log::info('Logout successful', [
                'session_id' => $request->session()->getId(),
            ]);

            return response()->json([
                'message' => 'Successfully logged out!',
            ]);
        } catch (\Exception $e) {
            \Log::error('Logout failed', [
                'error' => $e->getMessage(),
                'session_id' => $request->session()->getId(),
            ]);

            // Even if logout fails, try to clear the session
            try {
                $request->session()->invalidate();
                $request->session()->regenerateToken();
            } catch (\Exception $sessionError) {
                \Log::error('Session cleanup failed', [
                    'error' => $sessionError->getMessage(),
                ]);
            }

            return response()->json([
                'message' => 'Logout completed (with errors)',
            ]);
        }
    }


}