<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\Petugas;
use App\Models\Admin;

class PetugasAuthController extends Controller
{
    /**
     * Show the petugas login form.
     */
    public function showLoginForm()
    {
        return view('auth.petugas');
    }

    /**
     * Handle petugas login attempt.
     */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        if (Auth::guard('petugas')->attempt($credentials, $request->boolean('remember'))) {
            $request->session()->regenerate();
            return redirect()->intended('/petugas/dashboard')
                ->with('success', 'Selamat datang kembali, Petugas!');
        }

        return back()->withErrors([
            'username' => 'Username atau password Petugas salah.',
        ])->onlyInput('username');
    }

    /**
     * Handle petugas registration attempt.
     */
    public function register(Request $request)
    {
        $data = $request->validate([
            'nama_petugas' => 'required|string|max:100',
            'username' => 'required|string|max:100|unique:petugas,username',
            'password' => 'required|string|min:6',
            'jabatan' => 'required|string|max:100',
        ]);

        // Fetch the first available admin to bind id_admin
        $admin = Admin::first();
        $adminId = $admin ? $admin->id_admin : 1;

        $petugas = Petugas::create([
            'nama_petugas' => $data['nama_petugas'],
            'username' => $data['username'],
            'password' => Hash::make($data['password']),
            'jabatan' => $data['jabatan'],
            'foto' => 'default_petugas.jpg',
            'id_admin' => $adminId,
        ]);

        Auth::guard('petugas')->login($petugas);
        $request->session()->regenerate();

        return redirect('/petugas/dashboard')
            ->with('success', 'Pendaftaran berhasil! Anda telah masuk sebagai Petugas.');
    }

    /**
     * Log the petugas out.
     */
    public function logout(Request $request)
    {
        Auth::guard('petugas')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/')
            ->with('success', 'Anda telah berhasil logout dari portal Petugas.');
    }
}
