<?php

namespace App\Modules\Core\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Cookie;

class LoginController extends Controller
{
    /**
     * Display the login view.
     */
    public function show()
    {
        $centralDomains = config('tenancy.central_domains', []);

        // [Hack] Demo 環境特殊規則
        $demoPort = config('tenancy.demo_tenant_port');
        if ((!$demoPort || request()->getPort() != $demoPort) && in_array(request()->getHost(), $centralDomains)) {
            return Inertia::render('Landlord/Auth/Login');
        }

        return Inertia::render('Auth/Login');
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(Request $request)
    {
        $request->validate([
            'username' => ['required', 'string'],
            'password' => ['required', 'string'],
        ], [
            'username.required' => '請輸入帳號',
            'password.required' => '請輸入密碼',
        ]);

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

        if (Auth::attempt($credentials, $request->boolean('remember'))) {
            // Check activation status
            if (!Auth::user()->is_active) {
                Auth::guard('web')->logout();
                $request->session()->invalidate();
                $request->session()->regenerateToken();

                throw ValidationException::withMessages([
                    'username' => '此帳號已被停用，請聯繫管理員。',
                ]);
            }

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

            $centralDomains = config('tenancy.central_domains', []);
            // [Hack] Demo 環境特殊規則
            $demoPort = config('tenancy.demo_tenant_port');
            if ((!$demoPort || $request->getPort() != $demoPort) && in_array($request->getHost(), $centralDomains)) {
                return Inertia::location(route('landlord.dashboard'));
            }

            return Inertia::location(route('dashboard'));
        }

        throw ValidationException::withMessages([
            'username' => '帳號或密碼錯誤。',
        ]);
    }

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

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

        $request->session()->regenerateToken();
        
        // 強制清除 Session Cookie (對付 HTTPS/Proxy 環境下的殘留問題)
        $sessionCookieName = config('session.cookie');
        Cookie::queue(Cookie::forget($sessionCookieName));

        return redirect('/');
    }
}
