<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\GuruProfile;
use App\Models\SiswaProfile;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

class AuthController extends Controller
{
    public function showLogin(): View
    {
        return view('auth.login');
    }

    public function login(Request $request): RedirectResponse
    {
        if (empty($request->login) && empty($request->password)) {
            return back()
                ->withErrors([
                    'login' => 'Harap isi username dan password.',
                ])
                ->onlyInput('login');
        }

        if (empty($request->login)) {
            return back()
                ->withErrors([
                    'login' => 'Harap isi username.',
                ])
                ->onlyInput('login');
        }

        if (empty($request->password)) {
            return back()
                ->withErrors([
                    'password' => 'Harap isi password.',
                ])
                ->onlyInput('login');
        }

        $login = $request->login;

        $user = User::where('email', $login)->first();

        if (!$user) {
            $guru = GuruProfile::where('nip', $login)->first();
            $user = $guru?->user;
        }

        if (!$user) {
            $siswa = SiswaProfile::where('nis', $login)->first();
            $user = $siswa?->user;
        }

        if (!$user) {
            return back()
                ->withErrors([
                    'login' => 'Login Gagal. Username salah.',
                ])
                ->onlyInput('login');
        }

        if (!Hash::check($request->password, $user->password)) {
            return back()
                ->withErrors([
                    'password' => 'Login Gagal. Password salah.',
                ])
                ->onlyInput('login');
        }

        Auth::login($user, $request->boolean('remember'));
        $request->session()->regenerate();
        return redirect()->intended($this->redirectPathByRole());
    }

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();

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

        return redirect()->route('login');
    }

    private function redirectPathByRole(): string
    {
        $user = Auth::user();

        if ($user->isAdmin()) {
            return route('admin.dashboard');
        }

        if ($user->isGuru()) {
            return route('guru.dashboard');
        }

        return route('siswa.dashboard');
    }
}
