<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    // Override untuk menggunakan guard admin
    protected function guard()
    {
        return Auth::guard('admin');
    }

    // Override login untuk debugging
    protected function attemptLogin(Request $request)
    {
        $credentials = $this->credentials($request);
        
        // Log attempt
        \Log::info('Login attempt', ['email' => $credentials['email']]);
        
        $attempt = $this->guard()->attempt(
            $credentials, $request->filled('remember')
        );
        
        // Log result
        \Log::info('Login result', ['success' => $attempt]);
        
        return $attempt;
    }

    // Override redirect jika login gagal
    protected function sendFailedLoginResponse(Request $request)
    {
        \Log::error('Login failed', ['email' => $request->email]);
        return redirect()->back()
            ->withInput($request->only('email', 'remember'))
            ->withErrors(['email' => trans('auth.failed')]);
    }
}
