<?php
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

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



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

        $login = $request->input('login');
        $password = $request->input('password');
        $remember = (bool)$request->boolean('remember');

        $candidates = [];

        // Try email
        if (filter_var($login, FILTER_VALIDATE_EMAIL)) {
            $candidates[] = ['email' => $login, 'password' => $password];
        } else {
            // Try student_id, then username
            $candidates[] = ['student_id' => $login, 'password' => $password];
            $candidates[] = ['username'   => $login, 'password' => $password];
        }

        foreach ($candidates as $creds) {
            if (Auth::attempt($creds, $remember)) {
                $request->session()->regenerate();
                return redirect()->intended(
                    auth()->user()->role === 'admin'
                        ? route('admin.dashboard')
                        : route('dashboard')
                );
            }
        }

        return back()
            ->withErrors(['login' => __('app.login.error')])
            ->onlyInput('login');
    }


    public function logout(Request $request)
    {
        Auth::logout();                       // log out the user
        $request->session()->invalidate();    // invalidate session
        $request->session()->regenerateToken(); // prevent CSRF token fixation

        // Redirect to your login page route; adjust if your login route name differs
        return redirect()->route('login');    // e.g. Route::get('/login', ...)->name('login')
        // If you don't have a named 'login' route, use:
        // return redirect('/login');
    }
}
