<?php

namespace App\Http\Controllers;

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

class OfficerAuthController extends Controller
{
    public function showLogin(): View
    {
        return view('officer.login');
    }

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

        $user = User::where('email', $credentials['email'])->first();

        if (! $user || ! Hash::check($credentials['password'], $user->password)) {
            return back()
                ->withInput($request->only('email'))
                ->withErrors(['email' => 'Emel atau kata laluan tidak sah.']);
        }

        $request->session()->regenerate();
        $request->session()->put('officer_id', $user->id);
        $request->session()->put('officer_name', $user->name);

        return redirect()->intended(route('officer.letters.index'));
    }

    public function logout(Request $request): RedirectResponse
    {
        $request->session()->forget(['officer_id', 'officer_name']);
        $request->session()->invalidate();
        $request->session()->regenerateToken();

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

