<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ActivityLogController extends Controller
{
    /**
     * Display a listing of the activity logs.
     */
    public function index(Request $request): Response
    {
        $query = ActivityLog::with('user')->latest();

        // Filter by action
        $action = $request->get('action');
        if ($action && $action !== 'all') {
            $query->where('action', $action);
        }

        // Filter by user
        $userId = $request->get('user_id');
        if ($userId) {
            $query->where('user_id', $userId);
        }

        // Filter by model type
        $modelType = $request->get('model_type');
        if ($modelType && $modelType !== 'all') {
            $query->where('model_type', $modelType);
        }

        // Search by description
        $search = $request->get('search');
        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('description', 'like', "%{$search}%")
                    ->orWhere('action', 'like', "%{$search}%");
            });
        }

        // Date range filter
        $dateFrom = $request->get('date_from');
        $dateTo = $request->get('date_to');
        if ($dateFrom) {
            $query->whereDate('created_at', '>=', $dateFrom);
        }
        if ($dateTo) {
            $query->whereDate('created_at', '<=', $dateTo);
        }

        $perPage = min($request->get('per_page', 50), 100);
        $logsPaginated = $query->paginate($perPage)->withQueryString();

        // Get unique actions and model types for filters
        $actions = ActivityLog::distinct()->pluck('action')->sort()->values();
        $modelTypes = ActivityLog::distinct()->whereNotNull('model_type')->pluck('model_type')->sort()->values();

        return Inertia::render('Admin/ActivityLogs/Index', [
            'logs' => $logsPaginated->items(),
            'pagination' => [
                'data' => $logsPaginated->items(),
                'current_page' => $logsPaginated->currentPage(),
                'last_page' => $logsPaginated->lastPage(),
                'per_page' => $logsPaginated->perPage(),
                'total' => $logsPaginated->total(),
                'links' => $logsPaginated->linkCollection()->toArray(),
            ],
            'actions' => $actions,
            'modelTypes' => $modelTypes,
            'filters' => [
                'action' => $action ?? 'all',
                'user_id' => $userId ?? '',
                'model_type' => $modelType ?? 'all',
                'search' => $search ?? '',
                'date_from' => $dateFrom ?? '',
                'date_to' => $dateTo ?? '',
            ],
        ]);
    }
}

