<?php

namespace App\Http\Controllers\Company\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use Illuminate\Http\Request;

class AuditTrailController extends Controller
{
    public function index(Request $request)
    {
        if (!auth()->user()->hasPermission('audit', 'view')) {
            abort(403);
        }

        $companyId = auth()->user()->company_id;

        $query = AuditLog::where('company_id', $companyId)
            ->latest('created_at');

        if ($request->filled('action'))    $query->where('action', $request->action);
        if ($request->filled('module'))    $query->where('module', $request->module);
        if ($request->filled('date_from')) $query->whereDate('created_at', '>=', $request->date_from);
        if ($request->filled('date_to'))   $query->whereDate('created_at', '<=', $request->date_to);

        $logs = $query->paginate(50)->withQueryString();

        $modules = AuditLog::where('company_id', $companyId)
            ->distinct()->pluck('module')->sort()->values();

        $actions = AuditLog::where('company_id', $companyId)
            ->distinct()->pluck('action')->sort()->values();

        return view('admin.audit.index', compact('logs', 'modules', 'actions'));
    }
}
