<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePlanRequest;
use App\Http\Requests\UpdatePlanRequest;
use App\Http\Resources\PlanResource;
use App\Models\Plan;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class PlanController extends Controller
{
    /**
     * GET /api/plans
     * List all plans (supports ?active=1 filter and ?with_products=1)
     */
    public function index(Request $request): AnonymousResourceCollection
    {
        $query = Plan::withCount('products');

        if ($request->boolean('active')) {
            $query->active();
        }

        if ($request->boolean('with_products')) {
            $query->with(['products.contributions', 'products.eligibilities']);
        }

        $plans = $query->orderBy('plan_id')->paginate($request->integer('per_page', 15));

        return PlanResource::collection($plans);
    }

    /**
     * POST /api/plans
     */
    public function store(StorePlanRequest $request): JsonResponse
    {
        $plan = Plan::create($request->validated());

        return response()->json([
            'message' => 'Plan created successfully.',
            'data'    => new PlanResource($plan),
        ], 201);
    }

    /**
     * GET /api/plans/{plan}
     */
    public function show(Request $request, Plan $plan): PlanResource
    {
        if ($request->boolean('with_products')) {
            $plan->load(['products.contributions', 'products.eligibilities']);
        }

        $plan->loadCount('products');

        return new PlanResource($plan);
    }

    /**
     * PUT/PATCH /api/plans/{plan}
     */
    public function update(UpdatePlanRequest $request, Plan $plan): JsonResponse
    {
        $plan->update($request->validated());

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

    /**
     * DELETE /api/plans/{plan}
     */
    public function destroy(Plan $plan): JsonResponse
    {
        $plan->delete();

        return response()->json(['message' => 'Plan deleted successfully.'], 200);
    }

    /**
     * PATCH /api/plans/{plan}/toggle-status
     */
    public function toggleStatus(Plan $plan): JsonResponse
    {
        $plan->update(['is_active' => !$plan->is_active]);

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

    /**
     * GET /api/v1/plans/{plan}/summary
     *
     * Returns two clean blocks for the mobile UI:
     *   1. highlight_card  — the marketing / "starting from" card for the plan
     *   2. product_cards   — one efu_card entry per active variant (Platinum → Bronze)
     */
    public function summary(Plan $plan): JsonResponse
    {
        $products = $plan->activeProducts()
            ->with('contributions')
            ->orderByRaw("FIELD(variant, 'platinum', 'gold', 'silver', 'bronze')")
            ->get();

        // Build the per-variant product cards
        $productCards = $products->map(fn($p) => [
            'product_id'                => $p->product_id,
            'variant'                   => $p->variant,
            'variant_label'             => ucfirst($p->variant),
            'efu_product_name'          => $p->efu_product_name,
            'primary_sum_assured_label' => 'Primary Sum Assured (Health Cover)',
            'primary_sum_assured_pkr'   => (float) $p->coverage_per_person,
            'primary_sum_assured_fmt'   => 'Rs. ' . number_format($p->coverage_per_person, 0) . '/-',
            'cashless_hospitalization'  => $p->cashless_hospitalization,
            'contributions'             => $p->contributions->map(fn($c) => [
                'age_group'        => $c->age_group_label,
                'contribution_pkr' => (float) $c->contribution_pkr,
                'contribution_fmt' => 'Rs. ' . number_format($c->contribution_pkr, 0) . '/- Yearly',
            ])->values(),
        ]);

        return response()->json([
            'data' => [
                'plan_id'   => $plan->plan_id,
                'plan_name' => $plan->plan_name,

                // Block 1 — Marketing / highlight card
                'highlight_card' => [
                    'brand_name'         => $plan->highlight_brand_name,
                    'starting_price_pkr' => $plan->highlight_starting_price
                                              ? (float) $plan->highlight_starting_price
                                              : null,
                    'starting_price_fmt' => $plan->highlight_starting_price
                                              ? 'Starting from Rs. ' . number_format($plan->highlight_starting_price, 0) . '/- Yearly'
                                              : null,
                    'features'           => $plan->highlight_features ?? [],
                ],

                // Block 2 — One card per variant
                'product_cards' => $productCards,
            ],
        ]);
    }
}