<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

/**
 * Add purchases_access feature flag to all subscription plans.
 *
 * Starter plan      → false  (Purchases, Suppliers, AR, AP hidden)
 * Professional+     → true   (full access)
 * Free / trial plan → false  (but during an active trial all features are unlocked
 *                             in code via Organization::getPlanFeatures())
 */
return new class extends Migration
{
    public function up(): void
    {
        $plans = DB::table('subscription_plans')->get();

        foreach ($plans as $plan) {
            $features = json_decode($plan->features ?? '{}', true) ?: [];

            $features['purchases_access'] = match ($plan->name) {
                'starter', 'free' => false,
                default           => true,   // professional, business, enterprise
            };

            DB::table('subscription_plans')
                ->where('id', $plan->id)
                ->update([
                    'features'   => json_encode($features),
                    'updated_at' => now(),
                ]);
        }
    }

    public function down(): void
    {
        $plans = DB::table('subscription_plans')->get();

        foreach ($plans as $plan) {
            $features = json_decode($plan->features ?? '{}', true) ?: [];
            unset($features['purchases_access']);

            DB::table('subscription_plans')
                ->where('id', $plan->id)
                ->update([
                    'features'   => json_encode($features),
                    'updated_at' => now(),
                ]);
        }
    }
};
