<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\MembershipPlan;
use App\Models\Subscription;
use Illuminate\Http\Request;

class PlanApiController extends Controller
{
    public function index(Request $request)
    {
        $plans = MembershipPlan::where('is_active', true)
            ->where('is_public', true)
            ->orderBy('sort_order')
            ->orderBy('price')
            ->get()
            ->map(fn($p) => $this->fmtPlan($p));

        $subscription = null;
        $user = $request->user();
        if ($user) {
            $sub = Subscription::where('user_id', $user->id)
                ->where('status', 'active')
                ->where('expires_at', '>', now())
                ->with('plan')
                ->latest()
                ->first();

            if ($sub) {
                $subscription = [
                    'plan_id'    => $sub->plan_id,
                    'plan_name'  => $sub->plan?->name,
                    'plan_slug'  => $sub->plan?->slug,
                    'status'     => $sub->status,
                    'expires_at' => $sub->expires_at?->toISOString(),
                ];
            }
        }

        return response()->json([
            'plans'        => $plans,
            'subscription' => $subscription,
            'is_premium'   => $user?->isPremium() ?? false,
        ]);
    }

    private function fmtPlan(MembershipPlan $p): array
    {
        return [
            'id'            => $p->id,
            'name'          => $p->name,
            'slug'          => $p->slug,
            'description'   => $p->description,
            'price'         => $p->price,
            'purchase_link' => $p->purchase_link,
            'duration_days' => $p->duration_days,
            'trial_days'    => $p->trial_days,
            'features'      => $p->features ?? [],
            'perks'         => $p->perks ?? [],
            'badge_label'   => $p->badge_label,
            'accent_color'  => $p->accent_color,
        ];
    }
}
