<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class EmployeeController extends Controller
{
    public function store(Request $request)
    {
        Employee::create($this->validated($request));
        return back()->with('success', 'Pegawai berhasil ditambahkan.');
    }

    public function update(Request $request, Employee $employee)
    {
        $employee->update($this->validated($request, $employee));
        return back()->with('success', 'Data pegawai berhasil diperbarui.');
    }

    public function destroy(Employee $employee)
    {
        $employee->delete();
        return back()->with('success', 'Pegawai berhasil dihapus.');
    }

    private function validated(Request $request, ?Employee $employee = null): array
    {
        return $request->validate([
            'nip' => ['required', 'string', 'max:32', Rule::unique('employees')->ignore($employee)],
            'name' => ['required', 'string', 'max:120'],
            'role' => ['required', 'in:Pimpinan,PJ,Perawat'],
            'unit' => ['required', 'string', 'max:120'],
            'status' => ['required', 'in:Aktif,Cuti,Nonaktif'],
        ]);
    }
}
