<?php

namespace App\Http\Controllers;

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

class StaffController extends Controller
{
    public function index(Request $request)
    {
        $query = Staff::query();

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

        if ($jawatan = $request->get('jawatan')) {
            $query->where('jawatan', $jawatan);
        }

        if ($jantina = $request->get('jantina')) {
            $query->where('jantina', $jantina);
        }

        $totalStaf = (clone $query)->count();
        $totalLelaki = (clone $query)->where('jantina', 'Lelaki')->count();
        $totalPerempuan = (clone $query)->where('jantina', 'Perempuan')->count();

        $staff = $query->orderBy('nama')->paginate(5)->withQueryString();

        $jawatanOptions = Staff::query()
            ->select('jawatan')
            ->whereNotNull('jawatan')
            ->where('jawatan', '!=', '')
            ->distinct()
            ->orderBy('jawatan')
            ->pluck('jawatan');

        return view('staff-info', compact(
            'staff',
            'totalStaf',
            'totalLelaki',
            'totalPerempuan',
            'jawatanOptions'
        ));
    }
}
