<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\Client;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class PortalAuthController extends Controller
{
    public function loginForm(): View|RedirectResponse
    {
        if (Auth::check()) {
            return redirect()->route('portal.dashboard');
        }

        $page_title = 'Müşteri Portalı Giriş';
        return view('portal.auth.login', compact('page_title'));
    }

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

        $remember = $request->boolean('remember');

        if (! Auth::attempt($credentials, $remember)) {
            return back()->withInput($request->only('email'))->with('error', 'E-posta veya şifre hatalı.');
        }

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

        $user = Auth::user();
        $hasPortalClient = Client::where('portal_enabled', true)
            ->whereHas('users', function ($query) use ($user) {
                $query->where('users.id', $user->id)->where('client_user.is_active', true);
            })
            ->exists();

        if (! $hasPortalClient) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return back()->withInput($request->only('email'))->with('error', 'Bu kullanıcıya atanmış aktif müşteri portalı bulunamadı.');
        }

        DB::table('client_user')
            ->where('user_id', $user->id)
            ->where('is_active', true)
            ->update(['last_portal_login_at' => now()]);

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

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('portal.login')->with('success', 'Güvenli çıkış yapıldı.');
    }
}
