<?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 AdminAuthController extends Controller
{
    public function showLogin()
    {
        // Redirect if already logged in as admin
        if (Auth::guard('admin')->check()) {
            return redirect()->route('admin.dashboard');
        }

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

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

        $credentials = $request->only('email', 'password');
        $remember = $request->has('remember');

        // Debug: Log login attempt
        Log::info('Admin Login Attempt', [
            'email' => $credentials['email'],
            'ip' => $request->ip(),
            'session_id' => session()->getId(),
        ]);

        // Attempt login with admin guard and check role
        if (Auth::guard('admin')->attempt($credentials, $remember)) {
            $user = Auth::guard('admin')->user();

            // Debug: Log successful authentication
            Log::info('Admin Auth Successful', [
                'user_id' => $user->id,
                'email' => $user->email,
                'role' => $user->role,
                'guard_check' => Auth::guard('admin')->check(),
            ]);

            // Check if user is admin
            if ($user->role !== 'admin') {
                Auth::guard('admin')->logout();
                Log::warning('Admin Login Denied - Not Admin Role', ['user_id' => $user->id]);
                return back()->with('error', 'Access denied. Admin only.');
            }

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

            // Debug: Log after session regenerate
            Log::info('Admin Session Regenerated', [
                'new_session_id' => session()->getId(),
                'guard_check_after' => Auth::guard('admin')->check(),
            ]);

            return redirect()
                ->intended(route('admin.dashboard'))
                ->with('success', 'Welcome back, ' . $user->name);
        }

        Log::warning('Admin Login Failed - Invalid Credentials', [
            'email' => $credentials['email'],
        ]);

        return back()->with('error', 'Invalid credentials')->withInput($request->only('email'));
    }

    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();

        // Only regenerate token, don't invalidate entire session
        // This preserves other guard sessions (like web)
        $request->session()->regenerateToken();

        return redirect()->route('admin.login')->with('success', 'Logged out successfully');
    }
}
