<?php

namespace App\Http\Controllers\Web\Payroll\V2;

use App\Http\Controllers\Controller;
use App\Models\PayrollRunLog;
use Illuminate\Http\Request;

class PayrollAuditController extends Controller
{
    public function index(Request $request)
    {
        $companyId = auth()->user()->company_id;
        if (! $companyId) {
            return redirect()->route('payroll.v2.index')->with('error', 'Company not found.');
        }
        $query = PayrollRunLog::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->with(['payrollCycle', 'actor'])
            ->orderByDesc('created_at');
        if ($request->filled('search')) {
            $term = $request->search;
            $query->where(function ($q) use ($term) {
                $q->where('action', 'like', '%' . $term . '%')
                    ->orWhereHas('actor', fn ($a) => $a->where('name', 'like', '%' . $term . '%'));
            });
        }
        $logs = $query->paginate(20)->withQueryString();
        return view('payroll.v2.audit', compact('logs'));
    }
}
