<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User; // Mengimpor model User
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
  use AuthenticatesUsers;

  protected $redirectTo = RouteServiceProvider::HOME;

  protected function redirectTo() {
    if (auth()->user()->level == 1 || auth()->user()->level == 2) {
      return '/';
    }
    return '/';
  }

  public function __construct() {
    $this->middleware('guest')->except('logout');
  }

  public function logout(Request $request) {
    $this->guard()->logout();

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

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

    session()->flash('success', 'Anda berhasil Logout!');

    return redirect('/');
  }

  public function username() {
    return 'name';
  }


  protected function sendFailedLoginResponse(Request $request) {
    $user = User::where('name', $request->name)->first();

    if (!$user) {
      return response()->json([
        's' => 'f',
        'm' => 'Nama Pengguna atau Kata Sandi salah!'
      ]);
    }

    // Check if the user is locked or banned
    if ($user->status === 'locked') {
      return response()->json([
        's' => 'f',
        'm' => 'Akun Anda telah dikunci. Silakan hubungi administrator.'
      ]);
    }

    

    if (!Hash::check($request->password, $user->password)) {
      return response()->json([
        's' => 'f',
        'm' => 'Kata Sandi tidak cocok dengan Nama Pengguna!'
      ]);
    }
    
    if ($user->status === 'banned') {
      return response()->json([
        's' => 'f',
        'm' => 'Akun Anda telah dibanned. Silakan hubungi administrator.'
      ]);
    }

    $errors = [$this->username() => trans('auth.failed')];

    if ($request->expectsJson()) {
      return response()->json([
        'success' => false,
        'message' => trans('auth.failed'),
      ], 422);
    }

    return redirect()->back()
    ->withInput($request->only($this->username(), 'remember'))
    ->withErrors($errors);
  }

  protected function sendLoginResponse(Request $request) {
    if ($request->expectsJson()) {
      return response()->json([
        's' => 's',
        'redirectUrl' => $this->redirectTo(),
      ]);
    }

    return redirect()->intended($this->redirectPath());
  }
}