<?php

namespace Database\Seeders;

use App\Models\MexcoAddon;
use App\Models\MexcoFeature;
use App\Models\MexcoPlan;
use App\Models\MexcoPlanFeature;
use Illuminate\Database\Seeder;

class MexcoCatalogSeeder extends Seeder
{
    public function run(): void
    {
        // Ordered: shared core → starter+ → plus+ → pro+
        $features = [
            ['participant_management', 'Participant Management', 'core', 10, 'Register, import, and manage visitors, presenters, exhibitors, and staff in one place.'],
            ['session_management', 'Session Management', 'core', 20, 'Build the programme with rooms, speakers, schedules, and role-based session access.'],
            ['booth_management', 'Booth Management', 'core', 30, 'Set up exhibition booths with QR codes for stamping, visits, and on-floor engagement.'],
            ['qr_attendance', 'QR Attendance', 'core', 40, 'Verify entry and session attendance quickly with MeXCo Attend and digital QR passes.'],
            ['digital_pass', 'Digital Pass', 'core', 50, 'Give every participant a mobile event pass for entry, sessions, stamps, and certificates.'],
            ['digital_stamps', 'Digital Stamps', 'core', 60, 'Collect booth and activity stamps to drive floor traffic and unlock requirements.'],
            ['certificates', 'Certificates', 'core', 70, 'Issue digital certificates when attendance and stamp requirements are completed.'],
            ['booth_voting', 'Booth Voting', 'engagement', 80, 'Let participants vote for favourite booths and surface live popularity during the event.'],
            ['gamification', 'Gamification', 'engagement', 90, 'Motivate exploration with challenges, progress goals, and reward-style participation.'],
            ['floor_plan', 'Floor Plan', 'engagement', 100, 'Publish an interactive venue map so attendees can find halls, booths, and facilities.'],
            ['analytics', 'Advanced Analytics', 'engagement', 110, 'Track attendance, engagement, booth traffic, and participation trends after the event.'],
            ['sponsor_engagement', 'Sponsor Engagement', 'engagement', 120, 'Give sponsors visibility into booth visits, interactions, and audience reach.'],
        ];

        foreach ($features as [$code, $name, $category, $sort, $description]) {
            MexcoFeature::query()->updateOrCreate(
                ['code' => $code],
                [
                    'name' => $name,
                    'category' => $category,
                    'sort_order' => $sort,
                    'description' => $description,
                    'is_active' => true,
                ]
            );
        }

        // Retired from the commercial catalog.
        MexcoFeature::query()
            ->whereIn('code', [
                'custom_certificate',
                'custom_branding',
                'custom_domain',
                'ai_assistant',
                'api_access',
                'white_label',
            ])
            ->update(['is_active' => false]);

        // Packages: demo (try full features) → commercial fewest→most → special.
        $plans = [
            ['demo', 'Demo', 'Full MeXCo features with capacity and time limits - free to try', 0, false, 0, 25, 5, 5, 50, 10],
            ['starter', 'Starter', 'Small events getting started with MeXCo', 19900, false, 1, 100, 10, 10, 100, 90],
            ['plus', 'Plus', 'Growing events with more capacity', 49900, false, 2, 500, 30, 20, 500, 180],
            ['pro', 'Pro', 'Large professional conferences', 99900, false, 3, 2000, 100, 50, 2048, 365],
            ['campus', 'Campus', 'Sponsored student events - full functionality', 0, false, 4, 500, 50, 30, 500, 30],
            ['enterprise', 'Enterprise', 'Custom pricing for large institutions', 0, true, 5, null, null, null, null, null],
        ];

        foreach ($plans as [$code, $name, $desc, $price, $custom, $sort, $pax, $sess, $booth, $storage, $retention]) {
            MexcoPlan::query()->updateOrCreate(
                ['code' => $code],
                [
                    'name' => $name,
                    'description' => $desc,
                    'price_cents' => $price,
                    'is_custom_pricing' => $custom,
                    'sort_order' => $sort,
                    'participant_limit' => $pax,
                    'session_limit' => $sess,
                    'booth_limit' => $booth,
                    'storage_limit_mb' => $storage,
                    'retention_days' => $retention,
                    'default_duration_days' => $retention,
                    'is_active' => true,
                ]
            );
        }

        $core = [
            'participant_management' => true,
            'session_management' => true,
            'booth_management' => true,
            'qr_attendance' => true,
            'digital_pass' => true,
            'digital_stamps' => true,
            'certificates' => true,
        ];

        $fullFeatures = array_fill_keys(array_column($features, 0), true);

        $planMatrix = [
            'demo' => $fullFeatures,
            'campus' => $fullFeatures,
            'starter' => array_merge($core, [
                'booth_voting' => true,
            ]),
            'plus' => array_merge($core, [
                'booth_voting' => true,
                'gamification' => true,
            ]),
            'pro' => array_merge($core, [
                'booth_voting' => true,
                'gamification' => true,
                'floor_plan' => true,
                'analytics' => true,
                'sponsor_engagement' => true,
            ]),
            'enterprise' => $fullFeatures,
        ];

        foreach ($planMatrix as $planCode => $enabledFeatures) {
            $plan = MexcoPlan::query()->where('code', $planCode)->first();
            if (! $plan) {
                continue;
            }
            foreach (MexcoFeature::query()->get() as $feature) {
                MexcoPlanFeature::query()->updateOrCreate(
                    ['plan_id' => $plan->id, 'feature_id' => $feature->id],
                    ['enabled' => (bool) ($enabledFeatures[$feature->code] ?? false)]
                );
            }
        }

        $addons = [
            ['advanced_analytics', 'Advanced Analytics', 9900, 10, ['analytics'], true],
            ['floor_plan', 'Floor Plan', 9900, 20, ['floor_plan'], true],
            ['booth_voting', 'Booth Voting', 9900, 30, ['booth_voting'], true],
            ['gamification', 'Gamification', 19900, 40, ['gamification'], true],
            ['whatsapp_notification', 'WhatsApp Notification', 19900, 70, [], true],
            ['certificate_archive', 'Certificate Archive', 4900, 100, [], true],
            // Retired add-ons
            ['custom_certificate', 'Custom Certificate', 9900, 60, ['custom_certificate'], false],
            ['custom_branding', 'Custom Branding', 9900, 50, ['custom_branding'], false],
            ['ai_assistant', 'AI Event Assistant', 29900, 80, ['ai_assistant'], false],
            ['custom_domain', 'Custom Domain', 29900, 90, ['custom_domain'], false],
        ];

        foreach ($addons as [$code, $name, $price, $sort, $featureCodes, $active]) {
            $addon = MexcoAddon::query()->updateOrCreate(
                ['code' => $code],
                ['name' => $name, 'price_cents' => $price, 'sort_order' => $sort, 'is_active' => $active]
            );
            foreach ($featureCodes as $fc) {
                $feature = MexcoFeature::query()->where('code', $fc)->first();
                if ($feature) {
                    $addon->features()->syncWithoutDetaching([
                        $feature->id => ['enabled' => true],
                    ]);
                }
            }
        }

        $eligibleAddons = [
            // Included: booth_voting
            'starter' => [
                'floor_plan',
                'gamification',
                'whatsapp_notification',
                'certificate_archive',
                'advanced_analytics',
            ],
            // Included: booth_voting, gamification
            'plus' => [
                'floor_plan',
                'whatsapp_notification',
                'certificate_archive',
                'advanced_analytics',
            ],
            // Included: booth_voting, gamification, floor_plan, analytics, sponsor_engagement
            'pro' => [
                'whatsapp_notification',
                'certificate_archive',
            ],
            'demo' => [],
            'campus' => [],
            'enterprise' => [],
        ];

        foreach ($eligibleAddons as $planCode => $addonCodes) {
            $plan = MexcoPlan::query()->where('code', $planCode)->first();
            if (! $plan) {
                continue;
            }
            $ids = MexcoAddon::query()->whereIn('code', $addonCodes)->where('is_active', true)->pluck('id');
            $sync = [];
            foreach ($ids as $id) {
                $sync[$id] = ['is_active' => true];
            }
            $plan->addons()->sync($sync);
        }
    }
}
