<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthController extends Controller
{
    /**
     * Show login form
     */
    public function showLogin()
    {
        if (Auth::check()) {
            return $this->redirectBasedOnRole();
        }
        return view('auth.login');
    }

    /**
     * Process login
     */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials, $request->filled('remember'))) {
            $request->session()->regenerate();
            
            return $this->redirectBasedOnRole();
        }

        return back()->withErrors([
            'email' => 'Email atau password salah.',
        ])->onlyInput('email');
    }

    /**
     * Process logout
     */
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        
        return redirect()->route('login');
    }

    /**
     * Redirect based on user role
     */
    private function redirectBasedOnRole()
    {
        $user = Auth::user();
        
        // Pastikan $user adalah instance dari User model
        if ($user instanceof User) {
            if ($user->role === 'superadmin') {
                return redirect()->route('superadmin.dashboard');
            }
            
            if ($user->role === 'admin') {
                return redirect()->route('admin.dashboard');
            }
        }
        
        // Fallback jika role tidak dikenali
        return redirect()->route('login')->withErrors(['error' => 'Role tidak valid']);
    }
}