<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Setting;

class AdminLoginController extends Controller
{
    public function showLoginForm()
    {
        $settings = Setting::all()->pluck('value', 'key')->toArray();

        $siteName = $settings['site_name'] ?? config('app.name', 'SmartGrocery Admin');
        $logo = $settings['logo'] ?? null;

        if ($logo && !filter_var($logo, FILTER_VALIDATE_URL)) {
            $logo = route('public.media', ['path' => $logo]);
        }

        return view('admin.auth.login', [
            'siteName' => $siteName,
            'siteLogo' => $logo,
        ]);
    }

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

        if (Auth::guard('admin')->attempt($credentials)) {
            $request->session()->regenerate();

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

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }

    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();

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

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