<?php

namespace App\Http\Controllers\Admin;

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

class AuthController extends Controller
{
    /**
     * Show the admin login form
     */
    public function showLoginForm()
    {
        if (Auth::check() && Auth::user()->isAdmin()) {
            return redirect()->route('admin.dashboard');
        }
        
        return view('admin.login');
    }

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

        if (Auth::attempt($credentials, $request->boolean('remember'))) {
            $user = Auth::user();
            
            if (!$user->isAdmin()) {
                Auth::logout();
                Log::warning('Non-admin user attempted admin login', [
                    'email' => $request->email,
                    'ip' => $request->ip(),
                ]);
                return back()->withErrors(['email' => 'Acceso denegado. Se requieren permisos de administrador.']);
            }

            if (!$user->isActive()) {
                Auth::logout();
                Log::warning('Inactive admin attempted login', [
                    'user_id' => $user->id,
                    'email' => $request->email,
                    'ip' => $request->ip(),
                ]);
                return back()->withErrors(['email' => 'Tu cuenta está desactivada.']);
            }

            $request->session()->regenerate();
            
            Log::info('Admin logged in successfully', [
                'user_id' => $user->id,
                'email' => $user->email,
                'ip' => $request->ip(),
            ]);

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

        Log::warning('Failed admin login attempt', [
            'email' => $request->email,
            'ip' => $request->ip(),
        ]);

        return back()->withErrors([
            'email' => 'Las credenciales proporcionadas no coinciden con nuestros registros.',
        ])->onlyInput('email');
    }

    /**
     * Handle admin logout
     */
    public function logout(Request $request)
    {
        $user = Auth::user();
        
        Log::info('Admin logged out', [
            'user_id' => $user->id ?? null,
            'email' => $user->email ?? null,
            'ip' => $request->ip(),
        ]);

        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('admin.login')->with('success', 'Sesión cerrada correctamente.');
    }
}
