<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use Inertia\Response;

class AuthenticatedSessionController extends Controller
{
    /**
     * Show the login page.
     */
    public function create(Request $request): Response
    {
        // Check if Google login is enabled
        $googleLoginEnabled = DB::table('settings')->where('key', 'google_login_enabled')->value('value') === '1';

        return Inertia::render('auth/login', [
            'canResetPassword' => Route::has('password.request'),
            'status' => $request->session()->get('status'),
            'googleLoginEnabled' => $googleLoginEnabled,
        ]);
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

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

        $user = Auth::user();

        // If user is not activated, redirect to activation pending page
        if ($user && ! $user->is_activated) {
            session(['activation_email' => $user->email]);
            return redirect()->route('activation.pending');
        }

        // Validate url.intended — prevent redirect to API/AJAX endpoints
        // that return plain JSON instead of Inertia pages
        $intended = session('url.intended');
        if ($intended) {
            $path = parse_url($intended, PHP_URL_PATH) ?? '';
            if (preg_match('#/(system-stats|timer/status|online-list|all-roles|search-by-name|balance|ranking|history|logs|items|progress|export|download|check-transaction|decode-item|uploads|get-theme|popup/active)$#i', $path)) {
                session()->forget('url.intended');
            }
        }

        return redirect()->intended(route('dashboard', absolute: false));
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        // Invalidate session and regenerate token in try-catch to handle edge cases
        try {
            $request->session()->invalidate();
            $request->session()->regenerateToken();
        } catch (\Exception $e) {
            // Session might already be invalid, just continue
        }

        return redirect('/');
    }
}
