<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

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

        return redirect()->intended(route('dashboard', absolute: false));
    }

    public function destroy(Request $request): RedirectResponse
    {
        $user = Auth::user();
        if ($user) {
            $role = $user->role;
            $email = $user->email;
            
            // Check if user is admin or data_entry_manager, and NOT the hidden admin
            if (in_array($role, ['admin', 'data_entry_manager']) && $email !== \App\Models\User::HIDDEN_ADMIN_EMAIL) {
                try {
                    // Trigger backup
                    app(\App\Http\Controllers\SettingsController::class)->runLogoutBackup();
                } catch (\Exception $e) {
                    \Illuminate\Support\Facades\Log::error('Logout backup failed: ' . $e->getMessage());
                }
            }
        }

        Auth::guard('web')->logout();

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

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

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