<?php

namespace App\Http\Controllers;

use App\Models\Staff;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AdminStaffController extends Controller
{
    public function index(Request $request): View
    {
        $query = Staff::orderBy('nama');

        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('nama', 'like', '%' . $search . '%')
                    ->orWhere('jawatan', 'like', '%' . $search . '%');
            });
        }

        $staff = $query->paginate(20)->withQueryString();

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

    public function create(): View
    {
        return view('admin.staff.form', [
            'staff' => new Staff(),
            'mode' => 'create',
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validateData($request);
        Staff::create($data);

        return redirect()->route('admin.staff.index')
            ->with('status', 'Rekod staf berjaya ditambah.');
    }

    public function edit(Staff $staff): View
    {
        return view('admin.staff.form', [
            'staff' => $staff,
            'mode' => 'edit',
        ]);
    }

    public function update(Request $request, Staff $staff): RedirectResponse
    {
        $data = $this->validateData($request);
        $staff->update($data);

        return redirect()->route('admin.staff.index')
            ->with('status', 'Rekod staf berjaya dikemaskini.');
    }

    public function destroy(Staff $staff): RedirectResponse
    {
        $staff->delete();

        return back()->with('status', 'Rekod staf dipadam.');
    }

    protected function validateData(Request $request): array
    {
        return $request->validate([
            'nama' => ['required', 'string', 'max:120'],
            'jantina' => ['required', 'in:Lelaki,Perempuan'],
            'jawatan' => ['required', 'string', 'max:120'],
        ]);
    }
}
