<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

    public function loginPost(Request $request)
    {
        $credentials = $request->validate([
            'username' => 'required',
            'password' => 'required',
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            // Check role - sesuai dengan proseslogin.php lama
            $user = Auth::user();
            switch ($user->akses) {
                case 'admin':
                    return redirect()->intended('/admin/dashboard');
                case 'petugas_piket':
                    return redirect()->intended('/admin/dashboard'); // Same dashboard for now
                case 'kesiswaan':
                    return redirect()->intended('/admin/dashboard');
                case 'koordinator':
                    return redirect()->intended('/admin/dashboard');
                case 'guru':
                    return redirect()->intended('/guru/dashboard');
                case 'siswa':
                    return redirect()->intended('/siswa/dashboard');
                default:
                    return redirect()->intended('/');
            }
        }

        return back()->withErrors([
            'username' => 'Username atau password salah.',
        ])->onlyInput('username');
    }
    
    public function logout(Request $request) {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }
}
