<?php

namespace App\Http\Controllers;

use App\Models\MexcoAddon;
use App\Models\MexcoFeature;
use App\Models\MexcoPlan;
use App\Models\MexcoPlanFeature;
use App\Services\EntitlementService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MexcoSuperAdminPlanController extends Controller
{
    public function index(): View
    {
        $plans = MexcoPlan::query()
            ->withCount(['eventLicenses', 'planFeatures'])
            ->orderBy('sort_order')
            ->get();

        return view('super-admin.plans.index', compact('plans'));
    }

    public function edit(MexcoPlan $plan): View
    {
        $plan->load(['planFeatures.feature']);
        $features = MexcoFeature::query()->orderBy('sort_order')->get();
        $enabled = $plan->planFeatures->keyBy(fn ($pf) => $pf->feature_id);

        return view('super-admin.plans.edit', compact('plan', 'features', 'enabled'));
    }

    public function update(Request $request, MexcoPlan $plan): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price_cents' => 'nullable|integer|min:0',
            'is_custom_pricing' => 'nullable|boolean',
            'is_active' => 'nullable|boolean',
            'participant_limit' => 'nullable|integer|min:0',
            'session_limit' => 'nullable|integer|min:0',
            'booth_limit' => 'nullable|integer|min:0',
            'storage_limit_mb' => 'nullable|integer|min:0',
            'retention_days' => 'nullable|integer|min:0',
            'features' => 'nullable|array',
            'features.*' => 'nullable|boolean',
        ]);

        $plan->update([
            'name' => $data['name'],
            'description' => $data['description'] ?? null,
            'price_cents' => $data['price_cents'] ?? $plan->price_cents,
            'is_custom_pricing' => $request->boolean('is_custom_pricing'),
            'is_active' => $request->boolean('is_active', true),
            'participant_limit' => $data['participant_limit'] ?? null,
            'session_limit' => $data['session_limit'] ?? null,
            'booth_limit' => $data['booth_limit'] ?? null,
            'storage_limit_mb' => $data['storage_limit_mb'] ?? null,
            'retention_days' => $data['retention_days'] ?? null,
        ]);

        $selected = $request->input('features', []);
        foreach (MexcoFeature::all() as $feature) {
            MexcoPlanFeature::query()->updateOrCreate(
                ['plan_id' => $plan->id, 'feature_id' => $feature->id],
                ['enabled' => ! empty($selected[$feature->id])]
            );
        }

        $entitlements = app(EntitlementService::class);
        foreach ($plan->eventLicenses()->pluck('event_id') as $eventId) {
            $entitlements->rebuildEntitlements($eventId);
        }

        return redirect()->route('mexco.super.plans.index')
            ->with('success', 'Plan "'.$plan->name.'" updated.');
    }
}
