<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\SubscriptionPlan;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SubscriptionPlanController extends Controller
{
    public function index(): JsonResponse
    {
        $plans = SubscriptionPlan::orderBy('sort_order')->get();
        return response()->json($plans);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name'                    => ['required', 'string', 'max:100', 'unique:subscription_plans,name', 'regex:/^[a-z0-9_]+$/'],
            'label'                   => 'required|string|max:100',
            'description'             => 'nullable|string',
            'monthly_price'           => 'required|numeric|min:0',
            'yearly_price'            => 'required|numeric|min:0',
            'features'                => 'nullable|array',
            'features.max_users'      => 'nullable|integer|min:-1',
            'features.max_products'   => 'nullable|integer|min:-1',
            'features.max_branches'   => 'nullable|integer|min:-1',
            'features.reports_access' => 'nullable|boolean',
            'features.api_access'     => 'nullable|boolean',
            'features.multi_branch'   => 'nullable|boolean',
            'features.stock_transfer' => 'nullable|boolean',
            'features.audit_trail'    => 'nullable|boolean',
            'is_active'               => 'nullable|boolean',
            'sort_order'              => 'nullable|integer|min:0',
            'trial_days'              => 'nullable|integer|min:0|max:365',
            'is_featured'             => 'nullable|boolean',
        ]);

        $plan = SubscriptionPlan::create($validated);
        return response()->json(['message' => 'Plan created.', 'data' => $plan], 201);
    }

    public function update(Request $request, SubscriptionPlan $plan): JsonResponse
    {
        $validated = $request->validate([
            'label'                   => 'sometimes|string|max:100',
            'description'             => 'nullable|string',
            'monthly_price'           => 'sometimes|numeric|min:0',
            'yearly_price'            => 'sometimes|numeric|min:0',
            'features'                => 'nullable|array',
            'features.max_users'      => 'nullable|integer|min:-1',
            'features.max_products'   => 'nullable|integer|min:-1',
            'features.max_branches'   => 'nullable|integer|min:-1',
            'features.reports_access' => 'nullable|boolean',
            'features.api_access'     => 'nullable|boolean',
            'features.multi_branch'   => 'nullable|boolean',
            'features.stock_transfer' => 'nullable|boolean',
            'features.audit_trail'    => 'nullable|boolean',
            'is_active'               => 'nullable|boolean',
            'sort_order'              => 'nullable|integer|min:0',
            'trial_days'              => 'nullable|integer|min:0|max:365',
            'is_featured'             => 'nullable|boolean',
        ]);

        // Only one plan can be featured at a time — clear the flag on others
        if (!empty($validated['is_featured'])) {
            SubscriptionPlan::where('id', '!=', $plan->id)->update(['is_featured' => false]);
        }

        $plan->update($validated);
        return response()->json(['message' => 'Plan updated.', 'data' => $plan->fresh()]);
    }

    public function destroy(SubscriptionPlan $plan): JsonResponse
    {
        if (in_array($plan->name, ['free', 'starter', 'professional', 'business', 'enterprise'])) {
            return response()->json(['message' => 'Cannot delete a built-in plan. You may edit or deactivate it instead.'], 422);
        }

        $plan->delete();
        return response()->json(['message' => 'Plan deleted.']);
    }
}
