<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class PortalAuthController extends Controller
{
    /**
     * Resolve the guard used for the portal.
     */
    protected function guard()
    {
        // Falls back to 'web' if 'portal' isn't configured.
        $name = config('auth.portal_guard', 'portal') ?: 'web';
        return Auth::guard($name);
    }

    /**
     * GET /portal/login  (route name: portal.login)
     * Show the login form.
     */
    public function showLoginForm()
    {
        return view('portal.login');
    }

    /** Legacy alias some views might call. */
    public function show()
    {
        return $this->showLoginForm();
    }

    /**
     * Optional placeholder for magic-link/OTP flow.
     * GET /portal/login/magic (route name up to you)
     */
    public function magic()
    {
        return view('portal.magic-placeholder');
    }

    /**
     * POST /portal/login  (route name: portal.login.attempt)
     * Handle email/password OR email-only (stub) login.
     */
    public function attempt(Request $request)
    {
        $data = $request->validate([
            'email'     => ['required', 'email'],
            'password'  => ['nullable', 'string'],
            'remember'  => ['nullable', 'boolean'],
            'reference' => ['nullable', 'string', 'max:64'],
        ]);

        $guard = $this->guard();

        // Classic password login path
        if (!empty($data['password'])) {
            $remember = (bool) ($data['remember'] ?? false);

            if ($guard->attempt(
                ['email' => $data['email'], 'password' => $data['password']],
                $remember
            )) {
                $request->session()->regenerate();

                // Prefer named route if present, else fallback path.
                $target = route_exists('customer.dashboard')
                    ? route('customer.dashboard')
                    : '/customer/dashboard';

                return redirect()->intended($target);
            }

            throw ValidationException::withMessages([
                'email' => __('These credentials do not match our records.'),
            ]);
        }

        // Email-only placeholder (future magic link / OTP)
        return back()->with('status', __("If that email exists, we've sent a one-time code."));
    }

    /**
     * POST /portal/logout  (route name: portal.logout)
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

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

        return redirect()->route('portal.login');
    }
}

/**
 * Tiny helper: check if a named route exists.
 */
if (! function_exists('route_exists')) {
    function route_exists(string $name): bool
    {
        return app('router')->has($name);
    }
}
