<?php

namespace App\Http\Controllers;

use App\Models\Staff;
use App\Models\Guru;
use Illuminate\Http\Request;

class StaffController extends Controller
{
    public function index()
    {
        $staff = Staff::latest()->get();

        return view('staff.index', compact('staff'));
    }

    public function create()
    {
        $guru = Guru::orderBy('nama')->get();

        return view(
            'staff.create',
            compact('guru')
        );
    }

    public function store(Request $request)
    {
        $request->validate([
            'nip' => 'required|unique:staff,nip',
            'nama' => 'required',
            'jabatan' => 'required',
            'gaji_pokok' => 'required|numeric'
        ]);

        Staff::create([
            'guru_id' => $request->guru_id ?: null,
            'nip' => $request->nip,
            'nama' => $request->nama,
            'jabatan' => $request->jabatan,
            'gaji_pokok' => $request->gaji_pokok
        ]);

        return redirect()
            ->route('staff.index')
            ->with('success','Data staff berhasil ditambahkan');
    }

    public function edit($id)
    {
        $staff = Staff::findOrFail($id);

        $guru = Guru::orderBy('nama')->get();

        return view(
            'staff.edit',
            compact(
                'staff',
                'guru'
            )
        );
    }

    public function update(Request $request,$id)
    {
        $staff = Staff::findOrFail($id);

        $request->validate([
            'nip' => 'required|unique:staff,nip,'.$staff->id,
            'nama' => 'required',
            'jabatan' => 'required',
            'gaji_pokok' => 'required|numeric'
        ]);

        $staff->update([
            'guru_id' => $request->guru_id ?: null,
            'nip' => $request->nip,
            'nama' => $request->nama,
            'jabatan' => $request->jabatan,
            'gaji_pokok' => $request->gaji_pokok
        ]);

        return redirect()
            ->route('staff.index')
            ->with('success','Data staff berhasil diupdate');
    }

    public function destroy($id)
    {
        Staff::findOrFail($id)->delete();

        return redirect()
            ->route('staff.index')
            ->with('success','Data staff berhasil dihapus');
    }

    public function guru()
    {
        return $this->belongsTo(Guru::class);
    }
}