<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AuthController extends Controller
{
    public function showLogin(): View
    {
        return view('admin.login');
    }

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

        $admin = \App\Models\AdminUser::where('email', $request->email)
            ->where('is_active', true)
            ->first();

        if ($admin && \Illuminate\Support\Facades\Hash::check($request->password, $admin->password)) {
            $request->session()->put('admin.auth', true);
            $request->session()->put('admin.user_id', $admin->id);
            $request->session()->put('admin.email', $admin->email);
            $request->session()->put('admin.role', $admin->role);
            $request->session()->put('admin.just_logged_in', true);

            if ($admin->role === 'service_admin') {
                return redirect()->route('admin.support');
            }
            return redirect()->route('admin.dashboard');
        }

        return back()->withErrors([
            'email' => 'Invalid admin credentials.',
        ])->onlyInput('email');
    }

    public function logout(Request $request): RedirectResponse
    {
        $request->session()->forget(['admin.auth', 'admin.user_id', 'admin.email', 'admin.role']);
        $request->session()->invalidate();
        $request->session()->regenerateToken();

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

