<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\VipPackage;
use Carbon\Carbon;
use Illuminate\Http\Request;

class VipPackageController extends Controller
{
    /**
     * Return all VIP packages.
     *
     * For authenticated users, `is_locked` is overridden to `false` for any
     * package the user has an active subscription for. Unauthenticated users
     * always receive the static `is_locked` value from the database.
     *
     * GET /api/vip-packages
     */
    public function index(Request $request)
    {
        // Optionally authenticate — Sanctum resolves the Bearer token on this public route
        $user = $request->user('sanctum');

        // Pre-load active subscription package IDs in one query to avoid N+1
        $activePackageIds = collect();
        if ($user) {
            $activePackageIds = $user->activeSubscriptions()->pluck('vip_package_id');
        }

        // Also load subscription expiry dates per package for authenticated users
        $subscriptionEndsAt = collect();
        if ($user) {
            $subscriptionEndsAt = $user->activeSubscriptions()
                ->get(['vip_package_id', 'ends_at'])
                ->pluck('ends_at', 'vip_package_id');
        }

        $packages = VipPackage::all()->map(function (VipPackage $package) use ($activePackageIds, $subscriptionEndsAt) {
            $data = $package->toArray();

            // If the user has an active subscription for this package, unlock it
            if ($activePackageIds->contains($package->id)) {
                $data['is_locked'] = false;
                $data['subscription_ends_at'] = $subscriptionEndsAt->get($package->id);
            } else {
                $data['subscription_ends_at'] = null;
            }

            return $data;
        });

        return response()->json([
            'vip_packages' => $packages,
        ]);
    }
}

