<?php

namespace Database\Seeders;

use App;
use App\Models\Plan;
use App\Models\Product;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use MediaUploader;

class ProductTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $categoryIds = DB::table('product_categories')->pluck('id')->toArray();
        if (empty($categoryIds)) {
            $categoryIds = [1];
        }

        $this->createSimpleProduct($categoryIds);
        $this->createVariableSoftwareProduct($categoryIds);
        $this->createSubscriptionSaaSProduct($categoryIds);
        $this->createHybridProduct($categoryIds);
        $this->createManagedHostingProduct($categoryIds);
        $this->createSeoAuditProduct($categoryIds);
        $this->createBundleProduct($categoryIds);

        // Attach demo images from storage/demo/ to each product gallery
        $this->attachDemoImages();
    }

    /**
     * Attach gallery images to products from storage/demo/.
     *
     * Mirrors AdminMediaController::store() exactly:
     *   - Uploads to uploads/YYYYMM (same path as admin UI)
     *   - Creates resized thumbnail + medium variants via Intervention Image
     *   - Saves each variant path to media->meta() so frontend thumbnails work
     *
     * Images sorted alphabetically, assigned one-per-product in seeder order:
     *   1st → Simple Ebook Download,  2nd → Variable Server Software,
     *   3rd → SaaS Project Manager,   4th → Hybrid Cloud Storage,
     *   5th → Managed Web Hosting,    6th → SEO Audit Service
     *
     * Drop any image names into storage/demo/ — no naming convention needed.
     */
    private function attachDemoImages(): void
    {
        $demoDir = storage_path('demo');

        if (!File::isDirectory($demoDir)) {
            return;
        }

        // Sorted alphabetically — position maps to product order
        $validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $imageFiles = collect(File::files($demoDir))
            ->filter(fn($f) => in_array(strtolower($f->getExtension()), $validExtensions))
            ->sortBy(fn($f) => $f->getFilename())
            ->values();

        if ($imageFiles->isEmpty()) {
            return;
        }

        $products   = Product::orderBy('id')->get();
        $disk       = 'public';
        $uploadPath = 'uploads/' . date('Ym'); // e.g. uploads/202603 — same as controller

        foreach ($products as $index => $product) {
            if (!isset($imageFiles[$index])) {
                break;
            }

            // Idempotent — skip if already has gallery
            if ($product->getMedia('gallery')->isNotEmpty()) {
                continue;
            }

            $sourceFile = $imageFiles[$index]->getPathname();

            try {
                // ── Step 1: Upload via MediaUploader (same as controller) ──────────
                $media = MediaUploader::fromSource($sourceFile)
                    ->toDestination($disk, $uploadPath)
                    ->upload();

                // ── Step 2: Create resized variants (same as controller) ──────────
                if ($media->aggregate_type === 'image') {
                    foreach (config('media.sizes') as $name => $size) {
                        $width  = ($name !== 'medium') ? $size[0] : null;
                        $height = $size[1];

                        $resizedFilename = $media->filename . '.' . $media->extension;
                        $absPath         = $media->directory . '/' . $name . '/';
                        $fullAbsPath     = storage_path('app/' . $disk . '/' . $absPath);

                        if (!File::exists($fullAbsPath)) {
                            File::makeDirectory($fullAbsPath, 0755, true);
                        }

                        Image::make(storage_path('app/' . $disk . '/' . $media->getDiskPath()))
                            ->resize($width, $height, function ($constraint) {
                                $constraint->aspectRatio();
                                $constraint->upsize();
                            })
                            ->save($fullAbsPath . $resizedFilename);

                        // ── Step 3: Save meta path (same as controller) ───────────
                        $media->meta()->updateOrCreate(
                            ['size_name' => $name],
                            ['path'      => $absPath . $resizedFilename]
                        );
                    }
                }

                // ── Step 4: Attach to product gallery ────────────────────────────
                $product->attachMedia($media, ['gallery']);

            } catch (\Exception $e) {
                \Log::warning('Demo image attach failed for ' . $product->name . ': ' . $e->getMessage());
            }
        }
    }

    /**
     * Seed plan_entitlements rows from the plan's features array.
     *
     * Mirrors the logic in 2026_04_08_000005_migrate_plan_features_to_entitlements.php
     * so that fresh installs seeded via this seeder end up with the same entitlement
     * rows that the data migration would have produced on an existing installation.
     */
    private function seedPlanEntitlements(Plan $plan): void
    {
        $features = $plan->features;

        if (empty($features) || ! is_array($features)) {
            return;
        }

        // Idempotent — skip if this plan already has entitlements
        if ($plan->entitlements()->exists()) {
            return;
        }

        $existingKeys = [];
        $rows         = [];

        foreach ($features as $feature) {
            if (! is_string($feature) || trim($feature) === '') {
                continue;
            }

            $label   = trim($feature);
            $baseKey = Str::snake(Str::ascii($label));
            $baseKey = preg_replace('/[^a-z0-9_]/', '_', $baseKey);
            $baseKey = preg_replace('/_+/', '_', trim($baseKey, '_'));
            $baseKey = substr($baseKey ?: 'feature', 0, 95);

            $key    = $baseKey;
            $suffix = 2;
            while (in_array($key, $existingKeys, true)) {
                $key = $baseKey . '_' . $suffix++;
            }

            $existingKeys[] = $key;
            $rows[]         = [
                'key'        => $key,
                'value'      => null,
                'label'      => $label,
                'is_visible' => true,
            ];
        }

        if (! empty($rows)) {
            $plan->entitlements()->createMany($rows);
        }
    }

    private function createSimpleProduct($categoryIds)
    {
        if (Product::where('name', 'Simple Ebook Download')->exists()) return;

        $product = Product::create([
            'name' => 'Simple Ebook Download',
            'description' => 'A basic frictionless digital download example without explicit versions, licenses, or support policies.',
            'category_id' => \Illuminate\Support\Arr::random($categoryIds),
            'product_type' => 'simple',
            'user_id' => 1,
            'status' => 1,
            'features' => json_encode([
                'support' => false,
                'versioning' => false,
            ]),
        ]);

        $plan = $product->plans()->create([
            'billing_type' => getConstant('BILLING_ONETIME'),
            'is_default' => 1,
            'is_licensable' => 0,
            'features' => ['High-resolution PDF', 'DRM-free EPUB', 'Lifetime Access'],
        ]);
        $this->seedPlanEntitlements($plan);

        $plan->pricingTiers()->create([
            'tier_name' => 'One-time',
            'price' => 19.99,
            'setup_fee' => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'is_default' => 1,
        ]);

        // Simple Global File
        $file = $product->files()->create([
            'version' => 'v1.0',
            'changelog' => 'Initial release',
            'is_global' => 1,
            'released_at' => now(),
        ]);
        $file->plans()->attach([$plan->id]);

        $product->meta()->create(['key' => 'seo_title', 'value' => 'Buy Simple Ebook Download']);
        $product->meta()->create(['key' => 'seo_description', 'value' => 'The best ebook for beginners. Get your copy today.']);
    }

    private function createVariableSoftwareProduct($categoryIds)
    {
        $checkoutFields = [
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'company_name',
                'label'       => 'Company / Organisation Name',
                'type'        => 'text',
                'placeholder' => 'Acme Corp',
                'help_text'   => 'This will be embedded in your generated licence file.',
                'required'    => true,
                'validation'  => ['min_length' => 2, 'max_length' => 100, 'regex' => '', 'regex_message' => ''],
                'options'     => [],
            ],
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'deployment_environment',
                'label'       => 'Deployment Environment',
                'type'        => 'select',
                'placeholder' => '',
                'help_text'   => 'Helps our team tailor the setup documentation we send you.',
                'required'    => false,
                'validation'  => ['min_length' => '', 'max_length' => '', 'regex' => '', 'regex_message' => ''],
                'options'     => [
                    ['value' => 'production',  'label' => 'Production'],
                    ['value' => 'staging',     'label' => 'Staging / Testing'],
                    ['value' => 'development', 'label' => 'Development / Local'],
                ],
            ],
        ];

        if (Product::where('name', 'Variable Server Software')->exists()) {
            Product::where('name', 'Variable Server Software')->first()
                ?->meta()->updateOrCreate(['key' => 'checkout_fields'], ['value' => json_encode($checkoutFields)]);
            return;
        }

        $product = Product::create([
            'name' => 'Variable Server Software',
            'description' => 'A complex downloadable software offering tiered license options, release versioning, a support policy, and global addons.',
            'category_id' => \Illuminate\Support\Arr::random($categoryIds),
            'product_type' => 'simple', // OneTimeMode + variable pricingMode sends 'simple' to backend
            'user_id' => 1,
            'status' => 1,
            'features' => json_encode([
                'support' => true,
                'versioning' => true,
            ]),
        ]);

        // Support Policy correctly linked
        $product->supportPolicy()->create([
            'enabled' => 1,
            'support_duration' => 6,
            'support_duration_unit' => 1, // Months
            'support_description' => 'Priority support for 6 months. Renewal discount applies.',
            'discount_type' => 1, // Percentage
            'discount_value' => 20,
        ]);

        // Plans
        $personalPlan = $product->plans()->create([
            'name'                      => 'Personal License',
            'description'               => 'For individual developers and hobbyists.',
            'billing_type'              => getConstant('BILLING_ONETIME'),
            'is_default'                => 1,
            'is_licensable'             => 1,
            'license_validity'          => getConstant('LICENSE_VALIDITY_CUSTOM'),
            'license_validity_duration' => 1,
            'license_validity_unit'     => 'years',
            'features'                  => ['1 Domain', 'Community Support', '5 downloads per day'],
            'daily_download_limit'      => 5, // Demo: limited to 5 downloads/day
        ]);
        $this->seedPlanEntitlements($personalPlan);

        $proPlan = $product->plans()->create([
            'name'                 => 'Professional License',
            'description'          => 'For freelancers and small agencies.',
            'billing_type'         => getConstant('BILLING_ONETIME'),
            'is_default'           => 0,
            'is_licensable'        => 1,
            'license_validity'     => getConstant('LICENSE_VALIDITY_LIFETIME'),
            'features'             => ['5 Domains', 'Priority Email Support', 'White-labeling', 'Unlimited downloads'],
            'daily_download_limit' => null, // Unlimited downloads for Pro
        ]);
        $this->seedPlanEntitlements($proPlan);

        // Pricing Tiers
        $personalTier = $personalPlan->pricingTiers()->create([
            'tier_name' => 'One-time',
            'price' => 49.00,
            'setup_fee' => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'is_default' => 1,
        ]);

        $proTier = $proPlan->pricingTiers()->create([
            'tier_name' => 'One-time',
            'price' => 149.00,
            'setup_fee' => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'is_default' => 1,
        ]);

        // Global Addon
        $addon = $product->addons()->create([
            'name' => 'Professional Installation',
            'description' => 'Our team will install and configure the software on your server within 24 hours.',
            'billing_type' => getConstant('BILLING_ONETIME'),
        ]);

        $addon->plans()->attach([$personalPlan->id, $proPlan->id]);

        // Exact schema per ProductManagerService: global addon price is null pricing_tier_id
        DB::table('addon_pricing_tier')->insert([
            'addon_id' => $addon->id,
            'pricing_tier_id' => null,
            'price' => 40.00,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Also attach specifically to tiers to mimic what Service does in full variable mode
        $addon->pricingTiers()->attach([
            $personalTier->id => ['price' => 40.00],
            $proTier->id => ['price' => 40.00],
        ]);

        // Versioning Files
        $release1 = $product->files()->create([
            'version' => 'v1.0.0',
            'changelog' => 'Initial legacy release.',
            'is_global' => 0,
            'released_at' => now()->subDays(30),
        ]);
        $release1->plans()->attach([$personalPlan->id]); // Only personal plan got this

        $release2 = $product->files()->create([
            'version' => 'v2.0.0',
            'changelog' => 'Major overhaul and Pro features added.',
            'is_global' => 0,
            'released_at' => now(),
        ]);
        $release2->plans()->attach([$personalPlan->id, $proPlan->id]); // Both get this

        $product->meta()->create(['key' => 'checkout_fields', 'value' => json_encode($checkoutFields)]);
    }

    private function createSubscriptionSaaSProduct($categoryIds)
    {
        $checkoutFields = [
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'team_name',
                'label'       => 'Team or Company Name',
                'type'        => 'text',
                'placeholder' => 'e.g. Acme Design Team',
                'help_text'   => 'Used to personalise your workspace and onboarding emails.',
                'required'    => true,
                'validation'  => ['min_length' => 2, 'max_length' => 80, 'regex' => '', 'regex_message' => ''],
                'options'     => [],
            ],
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'team_size',
                'label'       => 'How many people will use this?',
                'type'        => 'number',
                'placeholder' => '5',
                'help_text'   => 'An approximate headcount helps us set up your account correctly.',
                'required'    => false,
                'validation'  => ['min_length' => 1, 'max_length' => 10000, 'regex' => '', 'regex_message' => ''],
                'options'     => [],
            ],
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'industry',
                'label'       => 'Industry',
                'type'        => 'select',
                'placeholder' => '',
                'help_text'   => 'Optional — helps us recommend relevant integrations during onboarding.',
                'required'    => false,
                'validation'  => ['min_length' => '', 'max_length' => '', 'regex' => '', 'regex_message' => ''],
                'options'     => [
                    ['value' => 'agency',    'label' => 'Agency / Freelance'],
                    ['value' => 'saas',      'label' => 'Software / SaaS'],
                    ['value' => 'ecommerce', 'label' => 'E-commerce'],
                    ['value' => 'marketing', 'label' => 'Marketing'],
                    ['value' => 'education', 'label' => 'Education'],
                    ['value' => 'other',     'label' => 'Other'],
                ],
            ],
        ];

        if (Product::where('name', 'SaaS Project Manager')->exists()) {
            Product::where('name', 'SaaS Project Manager')->first()
                ?->meta()->updateOrCreate(['key' => 'checkout_fields'], ['value' => json_encode($checkoutFields)]);
            return;
        }

        $product = Product::create([
            'name' => 'SaaS Project Manager',
            'description' => 'A recurring multi-tier subscription service testing Monthly/Yearly options, trials, and plan-specific addons.',
            'category_id' => \Illuminate\Support\Arr::random($categoryIds),
            'product_type' => 'subscription', // SubscriptionMode sends 'subscription' to backend
            'user_id' => 1,
            'status' => 1,
            'features' => json_encode([
                'support' => false,
                'versioning' => false,
            ]),
        ]);

        $starterPlan = $product->plans()->create([
            'name' => 'Starter Plan',
            'description' => 'Perfect for small teams getting started.',
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'is_default' => 1,
            'is_licensable' => 0,
            'features' => ['Up to 5 Users', '10GB Storage', 'Basic Reporting'],
        ]);
        $this->seedPlanEntitlements($starterPlan);

        $agencyPlan = $product->plans()->create([
            'name' => 'Agency Plan',
            'description' => 'For growing teams with demanding workflows.',
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'is_default' => 0,
            'is_licensable' => 0,
            'features' => ['Unlimited Users', '500GB Storage', 'Advanced Analytics'],
        ]);
        $this->seedPlanEntitlements($agencyPlan);

        // Starter Pricing
        $starterMonthly = $starterPlan->pricingTiers()->create([
            'tier_name' => 'Monthly',
            'price' => 15.00,
            'setup_fee' => 0.00,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle' => getConstant('BILLING_CYCLE_MONTHLY'),
            'trial_available' => 0,
            'is_default' => 1,
        ]);

        $starterYearly = $starterPlan->pricingTiers()->create([
            'tier_name' => 'Yearly',
            'price' => 150.00,
            'setup_fee' => 0.00,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle' => getConstant('BILLING_CYCLE_YEARLY'),
            'trial_available' => 0,
            'is_default' => 0,
        ]);

        // Agency Pricing (With Trial)
        $agencyMonthly = $agencyPlan->pricingTiers()->create([
            'tier_name' => 'Monthly',
            'price' => 49.00,
            'setup_fee' => 0.00,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle' => getConstant('BILLING_CYCLE_MONTHLY'),
            'trial_available' => 1,
            'trial_duration' => 14,
            'trial_duration_unit' => 1, // Days
            'is_default' => 1,
        ]);

        $agencyYearly = $agencyPlan->pricingTiers()->create([
            'tier_name' => 'Yearly',
            'price' => 490.00,
            'setup_fee' => 0.00,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle' => getConstant('BILLING_CYCLE_YEARLY'),
            'trial_available' => 1,
            'trial_duration' => 14,
            'trial_duration_unit' => 1, // Days
            'is_default' => 0,
        ]);

        // SaaS Addon 1 (Variable Pricing)
        $dedicatedIp = $product->addons()->create([
            'name' => 'Dedicated IP Address',
            'description' => 'Improve deliverability with a dedicated tracking IP.',
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
        ]);
        $dedicatedIp->plans()->attach([$starterPlan->id, $agencyPlan->id]);
        $dedicatedIp->pricingTiers()->attach([
            $starterMonthly->id => ['price' => 5.00],
            $starterYearly->id => ['price' => 50.00],
            $agencyMonthly->id => ['price' => 10.00], // More expensive for agency
            $agencyYearly->id => ['price' => 100.00],
        ]);

        $product->meta()->create(['key' => 'checkout_fields', 'value' => json_encode($checkoutFields)]);

        // SEO Meta
        $product->meta()->create(['key' => 'seo_title', 'value' => 'SaaS Project Manager Subscription']);
    }

    // -------------------------------------------------------------------------
    // 4. Cloud Design Assets — Simple product, variable pricing (3 plans, 1 one-time tier each)
    //    Rules: simple type + variable pricingMode = multiple plans, ONE tier per plan, one-time only
    // -------------------------------------------------------------------------
    private function createHybridProduct($categoryIds)
    {
        if (Product::where('name', 'Cloud Design Assets')->exists()) return;

        $product = Product::create([
            'name'         => 'Cloud Design Assets',
            'description'  => 'A premium collection of UI kits, icons, and Figma templates for designers and developers. Choose the license tier that fits your project scope.',
            'category_id'  => \Illuminate\Support\Arr::random($categoryIds),
            'product_type' => 'simple', // OneTimeMode + variable pricingMode
            'user_id'      => 1,
            'status'       => 1,
            'features'     => json_encode([
                'support'    => false,
                'versioning' => false,
            ]),
        ]);

        // Variable pricing: multiple plans, exactly ONE one-time tier per plan
        $personalPlan = $product->plans()->create([
            'name'          => 'Personal License',
            'description'   => 'For personal projects and freelancers. Use on 1 project.',
            'billing_type'  => getConstant('BILLING_ONETIME'),
            'is_default'    => 1,
            'is_licensable' => 0,
            'features'      => ['100+ UI Components', 'Figma + Sketch Files', '1 Project Use', 'Free Updates 6 Months'],
        ]);
        $this->seedPlanEntitlements($personalPlan);
        $personalPlan->pricingTiers()->create([
            'tier_name'    => 'One-time',
            'price'        => 39.00,
            'setup_fee'    => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'billing_cycle'=> null,
            'is_default'   => 1,
        ]);

        $teamPlan = $product->plans()->create([
            'name'          => 'Team License',
            'description'   => 'For small teams and studios. Use across up to 5 projects.',
            'billing_type'  => getConstant('BILLING_ONETIME'),
            'is_default'    => 0,
            'is_licensable' => 0,
            'features'      => ['Everything in Personal', '5 Project Use', 'Priority Support', 'Updates 1 Year'],
        ]);
        $this->seedPlanEntitlements($teamPlan);
        $teamPlan->pricingTiers()->create([
            'tier_name'    => 'One-time',
            'price'        => 99.00,
            'setup_fee'    => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'billing_cycle'=> null,
            'is_default'   => 1,
        ]);

        $extendedPlan = $product->plans()->create([
            'name'          => 'Extended License',
            'description'   => 'For agencies and SaaS products. Unlimited projects including commercial resale.',
            'billing_type'  => getConstant('BILLING_ONETIME'),
            'is_default'    => 0,
            'is_licensable' => 0,
            'features'      => ['Everything in Team', 'Unlimited Projects', 'Commercial / Resale Rights', 'Lifetime Updates'],
        ]);
        $this->seedPlanEntitlements($extendedPlan);
        $extendedPlan->pricingTiers()->create([
            'tier_name'    => 'One-time',
            'price'        => 249.00,
            'setup_fee'    => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'billing_cycle'=> null,
            'is_default'   => 1,
        ]);

        $product->meta()->create(['key' => 'seo_title', 'value' => 'Cloud Design Assets — UI Kits & Figma Templates']);
        $product->meta()->create(['key' => 'seo_description', 'value' => 'Premium UI kits and Figma templates. Personal, Team, and Extended licenses available.']);
    }

    // -------------------------------------------------------------------------
    // 5. Managed Web Hosting — Subscription service with 3 plans
    // -------------------------------------------------------------------------
    private function createManagedHostingProduct($categoryIds)
    {
        $checkoutFields = [
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'domain_name',
                'label'       => 'Domain Name',
                'type'        => 'url',
                'placeholder' => 'https://yourdomain.com',
                'help_text'   => 'We will configure your hosting environment for this domain. You can change it later from your account.',
                'required'    => true,
                'validation'  => ['min_length' => '', 'max_length' => '', 'regex' => '', 'regex_message' => ''],
                'options'     => [],
            ],
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'server_location',
                'label'       => 'Preferred Server Location',
                'type'        => 'select',
                'placeholder' => '',
                'help_text'   => 'Choose the data centre closest to your target audience for the best performance.',
                'required'    => true,
                'validation'  => ['min_length' => '', 'max_length' => '', 'regex' => '', 'regex_message' => ''],
                'options'     => [
                    ['value' => 'us-east',      'label' => 'US East (New York)'],
                    ['value' => 'us-west',      'label' => 'US West (San Francisco)'],
                    ['value' => 'eu-west',      'label' => 'EU West (London)'],
                    ['value' => 'ap-southeast', 'label' => 'Asia Pacific (Singapore)'],
                ],
            ],
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'technical_contact_email',
                'label'       => 'Technical Contact Email',
                'type'        => 'email',
                'placeholder' => 'dev@yourcompany.com',
                'help_text'   => 'Server credentials and setup notifications will be sent here. Leave blank to use your billing email.',
                'required'    => false,
                'validation'  => ['min_length' => '', 'max_length' => '', 'regex' => '', 'regex_message' => ''],
                'options'     => [],
            ],
        ];

        if (Product::where('name', 'Managed Web Hosting')->exists()) {
            Product::where('name', 'Managed Web Hosting')->first()
                ?->meta()->updateOrCreate(['key' => 'checkout_fields'], ['value' => json_encode($checkoutFields)]);
            return;
        }

        $product = Product::create([
            'name'         => 'Managed Web Hosting',
            'description'  => 'Fully managed cloud hosting with automatic backups, SSL, CDN, and 24/7 monitoring. Choose the plan that fits your traffic and storage needs.',
            'category_id'  => \Illuminate\Support\Arr::random($categoryIds),
            'product_type' => 'subscription', // SubscriptionMode — multiple plans, subscription billing only
            'user_id'      => 1,
            'status'       => 1,
            'features'     => json_encode([
                'support'    => true,
                'versioning' => false,
            ]),
        ]);

        // --- Starter Plan ---
        $starterPlan = $product->plans()->create([
            'name'         => 'Starter',
            'description'  => '1 website, 10 GB SSD, 50 GB bandwidth. Ideal for personal sites and small blogs.',
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'is_default'   => 1,
            'is_licensable'=> 0,
            'features'     => ['1 Website', '10 GB SSD Storage', '50 GB Bandwidth', 'Free SSL Certificate', 'Daily Backups'],
        ]);
        $this->seedPlanEntitlements($starterPlan);
        $starterPlan->pricingTiers()->create([
            'tier_name'    => 'Monthly',
            'price'        => 9.99,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle'=> getConstant('BILLING_CYCLE_MONTHLY'),
            'is_default'   => 1,
        ]);
        $starterPlan->pricingTiers()->create([
            'tier_name'    => 'Yearly',
            'price'        => 99.00,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle'=> getConstant('BILLING_CYCLE_YEARLY'),
            'is_default'   => 0,
        ]);

        // --- Pro Plan ---
        $proPlan = $product->plans()->create([
            'name'         => 'Pro',
            'description'  => '5 websites, 50 GB SSD, unlimited bandwidth. Great for growing businesses and agencies.',
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'is_default'   => 0,
            'is_licensable'=> 0,
            'features'     => ['5 Websites', '50 GB SSD Storage', 'Unlimited Bandwidth', 'Free SSL + CDN', 'Hourly Backups', 'Staging Environment'],
        ]);
        $this->seedPlanEntitlements($proPlan);
        $proPlan->pricingTiers()->create([
            'tier_name'    => 'Monthly',
            'price'        => 24.99,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle'=> getConstant('BILLING_CYCLE_MONTHLY'),
            'is_default'   => 1,
        ]);
        $proPlan->pricingTiers()->create([
            'tier_name'    => 'Yearly',
            'price'        => 249.00,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle'=> getConstant('BILLING_CYCLE_YEARLY'),
            'is_default'   => 0,
        ]);

        // --- Business Plan ---
        $businessPlan = $product->plans()->create([
            'name'         => 'Business',
            'description'  => 'Unlimited websites, 200 GB NVMe SSD, unlimited bandwidth, dedicated resources, and priority support.',
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'is_default'   => 0,
            'is_licensable'=> 0,
            'features'     => ['Unlimited Websites', '200 GB NVMe SSD', 'Unlimited Bandwidth', 'Free SSL + CDN + DDoS', 'Real-time Backups', 'Priority Support', 'Dedicated Resources'],
        ]);
        $this->seedPlanEntitlements($businessPlan);
        $businessPlan->pricingTiers()->create([
            'tier_name'    => 'Monthly',
            'price'        => 59.99,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle'=> getConstant('BILLING_CYCLE_MONTHLY'),
            'is_default'   => 1,
        ]);
        $businessPlan->pricingTiers()->create([
            'tier_name'    => 'Yearly',
            'price'        => 599.00,
            'billing_type' => getConstant('BILLING_SUBSCRIPTION'),
            'billing_cycle'=> getConstant('BILLING_CYCLE_YEARLY'),
            'is_default'   => 0,
        ]);

        $product->meta()->create(['key' => 'checkout_fields', 'value' => json_encode($checkoutFields)]);
    }

    // -------------------------------------------------------------------------
    // 6. SEO Audit Service — Simple product, variable pricing (3 plans, 1 one-time tier each)
    //    Rules: simple type + variable pricingMode = multiple plans, ONE tier per plan, one-time only
    // -------------------------------------------------------------------------
    private function createSeoAuditProduct($categoryIds)
    {
        $checkoutFields = [
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'website_url',
                'label'       => 'Website URL',
                'type'        => 'url',
                'placeholder' => 'https://yourwebsite.com',
                'help_text'   => 'The website you want audited. Make sure it is publicly accessible before submitting.',
                'required'    => true,
                'validation'  => ['min_length' => '', 'max_length' => '', 'regex' => '', 'regex_message' => ''],
                'options'     => [],
            ],
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'audit_goals',
                'label'       => 'What are your main SEO goals?',
                'type'        => 'textarea',
                'placeholder' => 'e.g. Rank higher for product keywords, fix crawl errors, improve page speed...',
                'help_text'   => 'The more detail you provide, the more targeted our recommendations will be.',
                'required'    => false,
                'validation'  => ['min_length' => '', 'max_length' => '500', 'regex' => '', 'regex_message' => ''],
                'options'     => [],
            ],
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'monthly_traffic',
                'label'       => 'Current Monthly Traffic (approx)',
                'type'        => 'select',
                'placeholder' => '',
                'help_text'   => 'Helps us benchmark your site against similar properties.',
                'required'    => false,
                'validation'  => ['min_length' => '', 'max_length' => '', 'regex' => '', 'regex_message' => ''],
                'options'     => [
                    ['value' => 'under-1k',  'label' => 'Under 1,000 visits/month'],
                    ['value' => '1k-10k',    'label' => '1,000 – 10,000 visits/month'],
                    ['value' => '10k-50k',   'label' => '10,000 – 50,000 visits/month'],
                    ['value' => 'over-50k',  'label' => 'Over 50,000 visits/month'],
                ],
            ],
            [
                'id'          => \Illuminate\Support\Str::uuid()->toString(),
                'name'        => 'has_google_analytics',
                'label'       => 'Do you have Google Analytics set up?',
                'type'        => 'radio',
                'placeholder' => '',
                'help_text'   => 'Access to analytics data helps us provide deeper traffic insights in the report.',
                'required'    => false,
                'validation'  => ['min_length' => '', 'max_length' => '', 'regex' => '', 'regex_message' => ''],
                'options'     => [
                    ['value' => 'yes',      'label' => 'Yes'],
                    ['value' => 'no',       'label' => 'No'],
                    ['value' => 'not-sure', 'label' => 'Not sure'],
                ],
            ],
        ];

        if (Product::where('name', 'SEO Audit Service')->exists()) {
            Product::where('name', 'SEO Audit Service')->first()
                ?->meta()->updateOrCreate(['key' => 'checkout_fields'], ['value' => json_encode($checkoutFields)]);
            return;
        }

        $product = Product::create([
            'name'         => 'SEO Audit Service',
            'description'  => 'A comprehensive analysis of your website\'s search engine performance. We audit technical SEO, on-page content, backlink profile, and deliver an actionable report with prioritised recommendations.',
            'category_id'  => \Illuminate\Support\Arr::random($categoryIds),
            'product_type' => 'simple', // OneTimeMode + variable pricingMode
            'user_id'      => 1,
            'status'       => 1,
            'features'     => json_encode([
                'support'    => false,
                'versioning' => false,
            ]),
        ]);

        // Variable pricing: 3 plans (audit scopes), each with exactly 1 one-time tier
        $essentialPlan = $product->plans()->create([
            'name'          => 'Essential',
            'description'   => 'Core technical SEO and on-page audit. Best for small sites.',
            'billing_type'  => getConstant('BILLING_ONETIME'),
            'is_default'    => 1,
            'is_licensable' => 0,
            'features'      => ['Up to 25 Pages', 'Technical SEO Review', 'On-Page Analysis', 'PDF Report', '3-Day Turnaround'],
        ]);
        $this->seedPlanEntitlements($essentialPlan);
        $essentialPlan->pricingTiers()->create([
            'tier_name'    => 'One-time',
            'price'        => 149.00,
            'setup_fee'    => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'billing_cycle'=> null,
            'is_default'   => 1,
        ]);

        $standardPlan = $product->plans()->create([
            'name'          => 'Standard',
            'description'   => 'Full SEO audit with competitor benchmarking. Best for growing businesses.',
            'billing_type'  => getConstant('BILLING_ONETIME'),
            'is_default'    => 0,
            'is_licensable' => 0,
            'features'      => ['Up to 100 Pages', 'Everything in Essential', 'Keyword Gap Analysis', 'Competitor Benchmarking', 'Backlink Profile Review', '5-Day Turnaround'],
        ]);
        $this->seedPlanEntitlements($standardPlan);
        $standardPlan->pricingTiers()->create([
            'tier_name'    => 'One-time',
            'price'        => 299.00,
            'setup_fee'    => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'billing_cycle'=> null,
            'is_default'   => 1,
        ]);

        $advancedPlan = $product->plans()->create([
            'name'          => 'Advanced',
            'description'   => 'Enterprise-grade audit with full action plan and 30-day follow-up.',
            'billing_type'  => getConstant('BILLING_ONETIME'),
            'is_default'    => 0,
            'is_licensable' => 0,
            'features'      => ['Unlimited Pages', 'Everything in Standard', 'Core Web Vitals Audit', 'Schema Markup Review', 'Prioritised Action Plan', '30-Day Follow-up Call'],
        ]);
        $this->seedPlanEntitlements($advancedPlan);
        $advancedPlan->pricingTiers()->create([
            'tier_name'    => 'One-time',
            'price'        => 599.00,
            'setup_fee'    => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'billing_cycle'=> null,
            'is_default'   => 1,
        ]);

        $product->meta()->create(['key' => 'checkout_fields', 'value' => json_encode($checkoutFields)]);

        $product->meta()->create(['key' => 'seo_title',       'value' => 'SEO Audit Service — Essential, Standard & Advanced']);
        $product->meta()->create(['key' => 'seo_description', 'value' => 'Professional SEO audits for every business size. One-time payment, no subscription.']);
    }

    // -------------------------------------------------------------------------
    // 7. Developer Toolkit Bundle — demonstrates the Bundle Products feature.
    //
    //    Bundles "Simple Ebook Download" and "Variable Server Software" — both
    //    already have product files, which is required: DownloadAccessService
    //    skips any included product whose files collection is empty.
    //
    //    The 'features' array is passed directly (no json_encode) because the
    //    Product model casts 'features' as 'array'. Passing a pre-encoded string
    //    causes Eloquent to double-encode it, so isBundle() would always return
    //    false and the bundle badge would never appear.
    // -------------------------------------------------------------------------
    private function createBundleProduct($categoryIds): void
    {
        if (Product::where('name', 'Developer Toolkit Bundle')->exists()) return;

        // Only products that already have files will be visible in the customer's
        // downloads page — DownloadAccessService skips empty-file products.
        $software = Product::where('name', 'Variable Server Software')->first();
        $ebook    = Product::where('name', 'Simple Ebook Download')->first();

        if (!$software || !$ebook) return;

        $product = Product::create([
            'name'         => 'Developer Toolkit Bundle',
            'description'  => 'Get our Variable Server Software and the accompanying Developer Fundamentals Ebook together in one discounted package. Everything you need to get started — the tool and the guide.',
            'category_id'  => \Illuminate\Support\Arr::random($categoryIds),
            'product_type' => 'simple',
            'user_id'      => 1,
            'status'       => 1,
            // Pass as array — Eloquent's 'array' cast will json_encode it correctly.
            // Do NOT wrap in json_encode() here or it will be double-encoded.
            'features'     => [
                'support'    => false,
                'versioning' => false,
                'bundle'     => true,
            ],
        ]);

        $plan = $product->plans()->create([
            'name'                 => 'Standard Bundle',
            'billing_type'         => getConstant('BILLING_ONETIME'),
            'is_default'           => 1,
            'is_licensable'        => 0,
            'daily_download_limit' => 10,
            'features'             => [
                'Variable Server Software (Personal License)',
                'Developer Fundamentals Ebook',
                'Lifetime Access',
                'Save 30% vs buying separately',
                '10 downloads per day',
            ],
        ]);
        $this->seedPlanEntitlements($plan);

        $plan->pricingTiers()->create([
            'tier_name'    => 'One-time',
            'price'        => 49.00, // vs $19.99 + $49.00 = $68.99 separately
            'setup_fee'    => 0.00,
            'billing_type' => getConstant('BILLING_ONETIME'),
            'is_default'   => 1,
        ]);

        // Link included products at the plan level via bundle_plan_products pivot.
        // This is what DownloadAccessService reads when expanding the bundle.
        $plan->bundleProducts()->attach([$software->id, $ebook->id]);

        $product->meta()->create(['key' => 'seo_title',       'value' => 'Developer Toolkit Bundle — Software + Ebook']);
        $product->meta()->create(['key' => 'seo_description', 'value' => 'Get Variable Server Software and the Developer Fundamentals Ebook together at a discounted price.']);
    }
}
