<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller
{
    /**
     * Show the user login form
     */
    public function showLoginForm()
    {
        if (Auth::check()) {
            $user = Auth::user();
            
            // Si es admin, redirigir al login de admin
            if ($user->isAdmin()) {
                return redirect()->route('admin.login');
            }
            
            // Si es usuario regular, verificar que tenga todo configurado antes de redirigir
            if ($user->isActive() && $user->ghl_contact_id) {
                $ghlFormUrl = \App\Models\SystemSetting::getValue('ghl_form_url');
                if ($ghlFormUrl) {
                    return redirect()->route('redirect.ghl');
                }
            }
        }
        
        return view('auth.login');
    }

    /**
     * Handle user 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('Admin attempted regular user login', [
                    'user_id' => $user->id,
                    'email' => $request->email,
                    'ip' => $request->ip(),
                ]);
                return back()->withErrors(['email' => 'Por favor, usa el panel de administración para iniciar sesión.']);
            }

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

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

            return redirect()->route('redirect.ghl');
        }

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

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

    /**
     * Handle user logout
     */
    public function logout(Request $request)
    {
        $user = Auth::user();
        
        Log::info('User 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('login')->with('success', 'Sesión cerrada correctamente.');
    }
}
