<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ActivityLogController extends Controller
{
    public function index(Request $request): View
    {
        $query = ActivityLog::query()->with('user')->orderByDesc('created_at');

        if ($request->filled('user_id')) {
            $query->where('user_id', (int) $request->input('user_id'));
        }

        if ($request->filled('action')) {
            $term = '%'.addcslashes($request->input('action'), '%_\\').'%';
            $query->where('action', 'like', $term);
        }

        if ($request->filled('from')) {
            $query->whereDate('created_at', '>=', $request->date('from')->format('Y-m-d'));
        }

        if ($request->filled('to')) {
            $query->whereDate('created_at', '<=', $request->date('to')->format('Y-m-d'));
        }

        $logs = $query->paginate(40)->withQueryString();
        $users = User::query()->orderBy('name')->get(['id', 'name', 'email']);

        return view('admin.activity-log.index', compact('logs', 'users'));
    }
}
