<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    // ── Show login form ───────────────────────────────────────

    public function showLogin()
    {
        if (Auth::check()) {
            return redirect($this->homeForRole(Auth::user()->role));
        }

        return view('auth.login');
    }

    // ── Process login ─────────────────────────────────────────

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

        $remember = $request->boolean('remember');

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

            return redirect()->intended(
                $this->homeForRole(Auth::user()->role)
            );
        }

        return back()
            ->withInput($request->only('email'))
            ->withErrors(['email' => 'Email atau password salah.']);
    }

    // ── Logout ────────────────────────────────────────────────

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

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

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

    // ── Helper: redirect target per role ─────────────────────

    private function homeForRole(string $role): string
    {
        return match ($role) {
            'admin'      => route('admin.tickets.index'),
            'cashier'    => route('admin.invoices.index'),
            'technician' => route('technician.home'),
            'courier'    => route('courier.pickup'),
            default      => route('admin.tickets.index'),
        };
    }
}
