<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\ActivityLogResource;
use App\Models\ActivityLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ActivityLogController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        try {
            $query = ActivityLog::with('user');

            if ($request->filled('project_id')) {
                $query->where('project_id', $request->project_id);
            }
            if ($request->filled('task_id')) {
                $query->where('task_id', $request->task_id);
            }
            if ($request->filled('user_id')) {
                $query->where('user_id', $request->user_id);
            }
            if ($request->filled('action')) {
                $query->where('action', $request->action);
            }
            if ($request->filled('subject_type')) {
                $query->where('subject_type', $request->subject_type);
            }
            if ($request->filled('subject_id')) {
                $query->where('subject_id', $request->subject_id);
            }

            $perPage = $request->input('per_page', 15);
            $sortBy = $request->input('sort_by', 'created_at');
            $sortDir = $request->input('sort_dir', 'desc');
            $logs = $query->orderBy($sortBy, $sortDir)->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => ActivityLogResource::collection($logs),
                'meta' => [
                    'current_page' => $logs->currentPage(),
                    'last_page' => $logs->lastPage(),
                    'per_page' => $logs->perPage(),
                    'total' => $logs->total(),
                ],
                'message' => 'لاگ فعالیت‌ها',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت لاگ فعالیت‌ها',
            ], 500);
        }
    }

    public function show(ActivityLog $activityLog): JsonResponse
    {
        try {
            $activityLog->load('user');

            return response()->json([
                'success' => true,
                'data' => new ActivityLogResource($activityLog),
                'message' => 'جزئیات لاگ',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت جزئیات لاگ',
            ], 500);
        }
    }
}
