<?php

namespace App\Http\Controllers\Admin\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\PegawaiValidationHistory;
use App\Models\User;
use Illuminate\Http\Request;

class ValidationHistoryController extends Controller
{
    public function index(Request $request)
    {
        abort_unless(auth()->check() && auth()->user()->isSuperAdmin(), 403, 'Unauthorized access. Super admin only.');

        $query = PegawaiValidationHistory::with(['pegawai.jabatan', 'admin'])
            ->latest();

        if ($request->filled('admin_id')) {
            $query->where('admin_id', $request->admin_id);
        }

        if ($request->filled('status_baru')) {
            $query->where('status_baru', $request->status_baru);
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->whereHas('pegawai', function ($pegawaiQuery) use ($search) {
                $pegawaiQuery->where('nama_lengkap', 'like', "%$search%")
                    ->orWhere('nip', 'like', "%$search%");
            });
        }

        $histories = $query->paginate(15)->withQueryString();
        $adminList = User::whereIn('role', ['admin', 'super_admin'])
            ->orderBy('name')
            ->get();
        $statuses = [
            'pending' => 'Menunggu Validasi',
            'disetujui' => 'Disetujui',
            'ditolak' => 'Ditolak',
        ];

        return view('admin.validation-histories.index', compact('histories', 'adminList', 'statuses'));
    }
}
