<?php

namespace Modules\ActivityLog\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Spatie\Activitylog\Models\Activity;
use App\Services\ActivityLogger;

class ActivityLogController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        // ActivityLogger::logView(new Activity, 'Viewed activity logs');

        $perPage = $request->get('per_page', 10);
        $perPage = min($perPage, 1000); // Limit max per page to 100
        $search = trim((string) $request->get('search', ''));

        $query = Activity::latest()->with(['causer']);

        if (! empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('description', 'ILIKE', "%{$search}%")
                    ->orWhere('subject_type', 'ILIKE', "%{$search}%")
                    ->orWhere('event', 'ILIKE', "%{$search}%")
                    ->orWhere('causer.name', 'ILIKE', "%{$search}%")
                    ->orWhere('causer.email', 'ILIKE', "%{$search}%");
            });
        }

        $activities = $query->paginate($perPage);

        return response()->json([
            'success' => true,
            'data' => $activities->items(),
            'pagination' => [
                'current_page' => $activities->currentPage(),
                'per_page' => $activities->perPage(),
                'total' => $activities->total(),
                'last_page' => $activities->lastPage(),
                'from' => $activities->firstItem(),
                'to' => $activities->lastItem(),
                'has_more_pages' => $activities->hasMorePages(),
                'links' => [
                    'first' => $activities->appends(request()->query())->url(1),
                    'last' => $activities->appends(request()->query())->url($activities->lastPage()),
                    'prev' => $activities->appends(request()->query())->previousPageUrl(),
                    'next' => $activities->appends(request()->query())->nextPageUrl(),
                ]
            ],
            'message' => 'Activity logs retrieved successfully',
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('activitylog::create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request) {}

    /**
     * Show the specified resource.
     */
    public function show($id)
    {
        return view('activitylog::show');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        return view('activitylog::edit');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id) {}

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id) {}
}
