<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AdminAuthController extends Controller
{
    public function showLogin(Request $request): View|RedirectResponse
    {
        if ($request->session()->get('admin_authenticated')) {
            return redirect()->route('admin.dashboard');
        }

        return view('admin.auth.login');
    }

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

        $expectedEmail = env('ADMIN_EMAIL', 'admin@example.com');
        $expectedPassword = env('ADMIN_PASSWORD', 'admin123');

        if (
            $validated['email'] !== $expectedEmail ||
            $validated['password'] !== $expectedPassword
        ) {
            return back()
                ->withInput($request->only('email'))
                ->withErrors([
                    'email' => 'The provided admin credentials are invalid.',
                ]);
        }

        $request->session()->regenerate();
        $request->session()->put('admin_authenticated', true);

        return redirect()
            ->route('admin.dashboard')
            ->with('status', 'Welcome back to the admin dashboard.');
    }

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

        return redirect()
            ->route('admin.login')
            ->with('status', 'You have signed out of the admin dashboard.');
    }
}
