<?php

namespace App\Http\Controllers;

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

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

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

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();
            
            // Redirect berdasarkan role setelah login
            $role = Auth::user()->role;
            if ($role == 'admin') return redirect()->intended('/dashboard');
            if ($role == 'gudang') return redirect()->intended('/pesanan');
            return redirect()->intended('/');
        }

        return back()->withErrors(['email' => 'Email atau kata sandi salah!']);
    }

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