<?php

namespace App\Http\Controllers\Api\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Event;
use App\Services\Analytics\EventAnalyticsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class EventAnalyticsController extends Controller
{
    public function __construct(
        private readonly EventAnalyticsService $analyticsService
    ) {}

    public function show(Request $request, Event $event): JsonResponse
    {
        // Check if package has advanced_analytics feature
        $packageFeatures = $event->eventPackage?->package?->features ?? [];
        // Handle array or JSON string features
        if (is_string($packageFeatures)) {
            $packageFeatures = json_decode($packageFeatures, true) ?? [];
        }
        
        $hasAccess = in_array('advanced_analytics', $packageFeatures, true);

        if (!$hasAccess) {
             return response()->json([
                'message' => 'This feature is only available in the Premium package.',
                'code' => 'feature_locked'
            ], 403);
        }

        $timeline = $this->analyticsService->getTimeline($event);
        $contributors = $this->analyticsService->getTopContributors($event);
        $tasks = $this->analyticsService->getTaskStats($event);

        return response()->json([
            'timeline' => $timeline,
            'contributors' => $contributors,
            'tasks' => $tasks,
        ]);
    }
}
