<?php

namespace App\Http\Controllers;

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

class MexcoSuperAdminAddonController extends Controller
{
    public function index(): View
    {
        $addons = MexcoAddon::query()
            ->withCount('eventAddons')
            ->orderBy('sort_order')
            ->get();

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

    public function edit(MexcoAddon $addon): View
    {
        $addon->load('features');
        $features = MexcoFeature::query()->orderBy('sort_order')->get();
        $plans = MexcoPlan::query()->orderBy('sort_order')->get();
        $linkedFeatures = $addon->features->pluck('id')->all();
        $eligiblePlans = $addon->plans->pluck('id')->all();

        return view('super-admin.addons.edit', compact('addon', 'features', 'plans', 'linkedFeatures', 'eligiblePlans'));
    }

    public function update(Request $request, MexcoAddon $addon): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price_cents' => 'required|integer|min:0',
            'is_active' => 'nullable|boolean',
            'feature_ids' => 'nullable|array',
            'feature_ids.*' => 'integer|exists:mexco_features,id',
            'plan_ids' => 'nullable|array',
            'plan_ids.*' => 'integer|exists:mexco_plans,id',
        ]);

        $addon->update([
            'name' => $data['name'],
            'description' => $data['description'] ?? null,
            'price_cents' => $data['price_cents'],
            'is_active' => $request->boolean('is_active', true),
        ]);

        $featureSync = [];
        foreach ($data['feature_ids'] ?? [] as $fid) {
            $featureSync[$fid] = ['enabled' => true];
        }
        $addon->features()->sync($featureSync);

        $planSync = [];
        foreach ($data['plan_ids'] ?? [] as $pid) {
            $planSync[$pid] = ['is_active' => true];
        }
        $addon->plans()->sync($planSync);

        return redirect()->route('mexco.super.addons.index')
            ->with('success', 'Add-on "'.$addon->name.'" updated.');
    }
}
