<?php
/**
 * Nesvra Ecosystem — Crypto Checkout Page
 */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ── 1. AUTHENTICATION GATE ──────────────────────────────────
// Require user to be logged in before accessing checkout
if (!isset($_SESSION['nesvra_user'])) {
    $params = [];
    if (!empty($_GET['product'])) $params['product'] = $_GET['product'];
    if (!empty($_GET['plan'])) $params['plan'] = $_GET['plan'];
    $queryString = !empty($params) ? '&' . http_build_query($params) : '';
    
    header("Location: auth?redirect=checkout" . $queryString);
    exit;
}

$user = $_SESSION['nesvra_user'];

// ── 2. COMPREHENSIVE PRODUCT & SERVICE CATALOG ─────────────
$catalog = [
    'tech-team' => [
        'name'        => 'Tech Team Subscription',
        'short_name'  => 'Tech Team for Hire',
        'type'        => 'subscription',
        'tag'         => 'Dedicated Engineering Squad',
        'back_url'    => 'solutions-tech-team-for-hire',
        'default_plan'=> 'growth',
        'addons'      => [],
        'plans'       => [
            'foundation' => [
                'name'     => 'Foundation Tier',
                'price'    => 2500,
                'period'   => '/mo',
                'badge'    => 'Basic Squad',
                'features' => [
                    '1 Dedicated Project Manager',
                    '1 UI/UX Designer (part-time)',
                    '2 Full-Stack Engineers',
                    'Up to 120 engineering hrs/mo',
                    'Weekly sprint reports & Slack channel',
                    'Full source code ownership'
                ]
            ],
            'growth' => [
                'name'     => 'Growth Tier',
                'price'    => 5500,
                'period'   => '/mo',
                'badge'    => 'Most Popular',
                'features' => [
                    '1 Senior Project Manager',
                    '3 Full-Stack Engineers',
                    'Up to 280 engineering hrs/mo',
                    'Mobile app development included',
                    '48-hour critical issue SLA',
                    'Real-time sprint dashboard & CI/CD'
                ]
            ],
            'enterprise' => [
                'name'     => 'Enterprise Tier',
                'price'    => 12000,
                'period'   => '/mo',
                'badge'    => 'Full Department',
                'features' => [
                    '1 Dedicated Technical Director',
                    '4–6 Full-Stack Engineers',
                    'Fractional CTO advisory (4 hrs/mo)',
                    '500+ engineering hrs/mo',
                    '24h critical / 4h P1 SLA',
                    '99.9% uptime guarantee'
                ]
            ],
            'enterprise-plus' => [
                'name'     => 'Enterprise+ Tier',
                'price'    => 25000,
                'period'   => '/mo',
                'badge'    => 'Bespoke Multi-Squad',
                'features' => [
                    'Fully bespoke squad composition',
                    'Multiple concurrent product streams',
                    'Board-level technology advisory',
                    'Custom SLA with penalty clauses',
                    'Regulatory & compliance engineering',
                    '24/7 priority executive response'
                ]
            ]
        ]
    ],

    'systems-erp' => [
        'name'        => 'Enterprise Resource Planning (ERP)',
        'short_name'  => 'Enterprise ERP',
        'type'        => 'license',
        'tag'         => 'Business Systems',
        'back_url'    => 'systems-erp',
        'default_plan'=> 'growth',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',         'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'Server & Cloud Infrastructure',   'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',              'price' => 350],
            ['name' => 'Extended Support (+6 Months)',     'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',    'price' => 500],
        ],
        'plans'       => [
            'starter' => [
                'name'     => 'ERP Starter License',
                'price'    => 10000,
                'period'   => 'one-time',
                'badge'    => 'Single Site',
                'features' => [
                    'Inventory & stock transfers',
                    'Purchase & sales orders',
                    'Single warehouse & costing',
                    'Reporting & dashboards',
                    'Source code ownership',
                    '90 days priority support'
                ]
            ],
            'growth' => [
                'name'     => 'ERP Growth License',
                'price'    => 22000,
                'period'   => 'one-time',
                'badge'    => 'Most Popular',
                'features' => [
                    'Multi-warehouse & manufacturing',
                    'Bill of materials & work orders',
                    'Demand planning & reorder rules',
                    'API access & mobile apps',
                    '180 days priority support'
                ]
            ],
            'enterprise' => [
                'name'     => 'ERP Enterprise License',
                'price'    => 45000,
                'period'   => 'one-time',
                'badge'    => 'Multi-Entity',
                'features' => [
                    'Multi-entity & multi-company',
                    'Production & capacity planning',
                    'Quality control & asset management',
                    'General ledger & tax modules',
                    '365 days priority support'
                ]
            ],
            'enterprise-plus' => [
                'name'     => 'ERP Enterprise+ License',
                'price'    => 75000,
                'period'   => 'one-time',
                'badge'    => 'Unlimited Scale',
                'features' => [
                    'Unlimited entities & subsidiaries',
                    'Custom modules & integrations',
                    'Dedicated engineering pod',
                    'On-premise architecture support',
                    '24/7 priority support'
                ]
            ]
        ]
    ],

    'systems-crm' => [
        'name'        => 'Customer Relationship Management (CRM)',
        'short_name'  => 'Enterprise CRM',
        'type'        => 'license',
        'tag'         => 'Business Systems',
        'back_url'    => 'systems-crm',
        'default_plan'=> 'growth',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',         'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'Server & Cloud Infrastructure',   'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',              'price' => 350],
            ['name' => 'Extended Support (+6 Months)',     'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',    'price' => 500],
        ],
        'plans'       => [
            'starter' => [
                'name'     => 'CRM Starter License',
                'price'    => 8000,
                'period'   => 'one-time',
                'badge'    => 'Single Pipeline',
                'features' => [
                    'Contacts, companies and deals',
                    'Single pipeline and forecasting',
                    'Tasks, activities and calendar',
                    'Reporting and dashboards',
                    'Source code ownership',
                    '90 days priority support'
                ]
            ],
            'growth' => [
                'name'     => 'CRM Growth License',
                'price'    => 18000,
                'period'   => 'one-time',
                'badge'    => 'Most Popular',
                'features' => [
                    'Multiple pipelines and lead scoring',
                    'Email marketing and campaigns',
                    'Automation and sequences',
                    'API access and mobile app',
                    'Source code ownership',
                    '180 days priority support'
                ]
            ],
            'enterprise' => [
                'name'     => 'CRM Enterprise License',
                'price'    => 30000,
                'period'   => 'one-time',
                'badge'    => 'Full Suite',
                'features' => [
                    'Support tickets, SLAs and live chat',
                    'Teams, territories and RBAC',
                    'Customer portal and knowledge base',
                    'Maker-checker and audit logs',
                    'Source code ownership',
                    '365 days priority support'
                ]
            ]
        ]
    ],

    'systems-accounting' => [
        'name'        => 'Accounting & Financial Management Platform',
        'short_name'  => 'Accounting Software',
        'type'        => 'license',
        'tag'         => 'Business Systems',
        'back_url'    => 'systems-accounting',
        'default_plan'=> 'growth',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',         'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'Server & Cloud Infrastructure',   'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',              'price' => 350],
            ['name' => 'Extended Support (+6 Months)',     'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',    'price' => 500],
        ],
        'plans'       => [
            'starter' => [
                'name'     => 'Accounting Starter License',
                'price'    => 6000,
                'period'   => 'one-time',
                'badge'    => 'Single Entity',
                'features' => [
                    'General ledger and journals',
                    'Invoicing and payables',
                    'Bank reconciliation',
                    'Tax and financial reports',
                    'Source code ownership',
                    '90 days priority support'
                ]
            ],
            'growth' => [
                'name'     => 'Accounting Growth License',
                'price'    => 14000,
                'period'   => 'one-time',
                'badge'    => 'Most Popular',
                'features' => [
                    'Multi-currency and FX revaluation',
                    'Projects and time billing',
                    'Expense claims and approvals',
                    'API access and mobile app',
                    'Source code ownership',
                    '180 days priority support'
                ]
            ],
            'enterprise' => [
                'name'     => 'Accounting Enterprise License',
                'price'    => 24000,
                'period'   => 'one-time',
                'badge'    => 'Multi-Entity',
                'features' => [
                    'Multi-entity and inter-company',
                    'Fixed assets and depreciation',
                    'Maker-checker and period locking',
                    'Cost centres and budgets',
                    'Source code ownership',
                    '365 days priority support'
                ]
            ]
        ]
    ],

    'systems-enterprise-os' => [
        'name'        => 'Enterprise Operating System (EOS)',
        'short_name'  => 'Enterprise OS',
        'type'        => 'license',
        'tag'         => 'Business Systems',
        'back_url'    => 'systems-enterprise-operating-system',
        'default_plan'=> 'growth',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',         'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'Server & Cloud Infrastructure',   'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',              'price' => 350],
            ['name' => 'Extended Support (+6 Months)',     'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',    'price' => 500],
        ],
        'plans'       => [
            'starter' => [
                'name'     => 'Enterprise OS Starter License',
                'price'    => 20000,
                'period'   => 'one-time',
                'badge'    => 'Single Company',
                'features' => [
                    'ERP, CRM, accounting & HR core',
                    'Single company, users & roles',
                    'Single sign-on & approvals',
                    'Reporting & dashboards',
                    'Source code ownership',
                    '90 days priority support'
                ]
            ],
            'growth' => [
                'name'     => 'Enterprise OS Growth License',
                'price'    => 40000,
                'period'   => 'one-time',
                'badge'    => 'Most Popular',
                'features' => [
                    'Full ERP, CRM & accounting modules',
                    'Payroll, projects & service desk',
                    'Automation & multi-currency',
                    'API access & mobile app',
                    'Source code ownership',
                    '180 days priority support'
                ]
            ],
            'enterprise' => [
                'name'     => 'Enterprise OS Enterprise License',
                'price'    => 80000,
                'period'   => 'one-time',
                'badge'    => 'Multi-Entity',
                'features' => [
                    'Multi-entity & consolidation',
                    'Advanced HR & analytics',
                    'API gateway & custom branding',
                    'Maker-checker controls',
                    'Source code ownership',
                    '365 days priority support'
                ]
            ]
        ]
    ],

    'remittance' => [
        'name'        => 'Money Transfer & Remittance Platform',
        'short_name'  => 'Remittance Platform',
        'type'        => 'license',
        'tag'         => 'Fintech Infrastructure',
        'back_url'    => 'remittance',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',            'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'App Store & Play Store Publishing',  'desc' => 'End-to-end publishing, review responses, and certificate signing.',                  'price' => 250],
            ['name' => 'Marketing & Growth Analytics Stack', 'desc' => 'Segment, Mixpanel, user onboarding funnels, and CRM setup.',                        'price' => 400],
            ['name' => 'Licensing & Compliance Roadmap',     'desc' => '1-on-1 regulatory strategy, AML policy docs, and partner banking intros.',           'price' => 600],
            ['name' => 'Server & Cloud Infrastructure',      'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',        'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'Remittance Platform License',
                'price'    => 8000,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    'Full source code repository access',
                    'Customer web portal & mobile apps (iOS/Android)',
                    'Multi-currency wallet ledger & corridor routing',
                    'Compliance engine, KYC/AML & tiered limits',
                    'Admin portal with liquidity & fee management',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ],

    'digital-wallet' => [
        'name'        => 'Digital Wallet Platform — Enterprise',
        'short_name'  => 'Digital Wallet',
        'type'        => 'license',
        'tag'         => 'Fintech Infrastructure',
        'back_url'    => 'digital-wallet',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',            'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'App Store & Play Store Publishing',  'desc' => 'End-to-end publishing, review responses, and certificate signing.',                  'price' => 250],
            ['name' => 'Marketing & Growth Analytics Stack', 'desc' => 'Segment, Mixpanel, user onboarding funnels, and CRM setup.',                        'price' => 400],
            ['name' => 'Licensing & Compliance Roadmap',     'desc' => '1-on-1 regulatory strategy, AML policy docs, and partner banking intros.',           'price' => 600],
            ['name' => 'Server & Cloud Infrastructure',      'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',        'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'Digital Wallet Platform License',
                'price'    => 8000,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    'Source code & architecture blueprints',
                    'Virtual accounts & P2P transfers engine',
                    'QR payments & merchant checkout',
                    'iOS & Android native customer apps',
                    'Admin dashboard & fraud monitoring',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ],

    'virtual-card' => [
        'name'        => 'Virtual & Physical Card Platform',
        'short_name'  => 'Virtual Card Issuing',
        'type'        => 'license',
        'tag'         => 'Card Issuing',
        'back_url'    => 'virtual-cards',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',            'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'App Store & Play Store Publishing',  'desc' => 'End-to-end publishing, review responses, and certificate signing.',                  'price' => 250],
            ['name' => 'Marketing & Growth Analytics Stack', 'desc' => 'Segment, Mixpanel, user onboarding funnels, and CRM setup.',                        'price' => 400],
            ['name' => 'Licensing & Compliance Roadmap',     'desc' => '1-on-1 regulatory strategy, AML policy docs, and partner banking intros.',           'price' => 600],
            ['name' => 'Server & Cloud Infrastructure',      'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',        'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'Virtual Card Issuing Platform',
                'price'    => 8000,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    'Visa/Mastercard issuing gateway integration',
                    'Granular spending controls & limits engine',
                    'Real-time webhook balance authorization',
                    'User mobile apps & admin back-office',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ],

    'payment-gateway' => [
        'name'        => 'Payment Gateway & Merchant Infrastructure',
        'short_name'  => 'Payment Gateway',
        'type'        => 'license',
        'tag'         => 'Fintech Infrastructure',
        'back_url'    => 'fintech',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',            'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'Marketing & Growth Analytics Stack', 'desc' => 'Segment, Mixpanel, user onboarding funnels, and CRM setup.',                        'price' => 400],
            ['name' => 'Server & Cloud Infrastructure',      'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',        'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'Payment Gateway Engine License',
                'price'    => 7500,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    'White-label checkout modal & developer SDKs',
                    'Merchant management dashboard & payout routing',
                    'Multi-currency processing & webhook dispatcher',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ],

    'gift-cards' => [
        'name'        => 'Airtime & Gift Card Platform',
        'short_name'  => 'Gift Card Platform',
        'type'        => 'license',
        'tag'         => 'Digital Assets',
        'back_url'    => 'gift-cards',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',            'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'App Store & Play Store Publishing',  'desc' => 'End-to-end publishing, review responses, and certificate signing.',                  'price' => 250],
            ['name' => 'Marketing & Growth Analytics Stack', 'desc' => 'Segment, Mixpanel, user onboarding funnels, and CRM setup.',                        'price' => 400],
            ['name' => 'Server & Cloud Infrastructure',      'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',        'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'Airtime & Gift Card License',
                'price'    => 6000,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    '500+ branded gift cards & global airtime rails',
                    'API distributor portal & end-user app',
                    'Automated stock inventory & margin controls',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ],

    'core-banking' => [
        'name'        => 'Core Banking & Ledger Engine',
        'short_name'  => 'Core Banking',
        'type'        => 'license',
        'tag'         => 'Banking Engine',
        'back_url'    => 'fintech-core-banking',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',            'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'Licensing & Compliance Roadmap',     'desc' => '1-on-1 regulatory strategy, AML policy docs, and partner banking intros.',           'price' => 600],
            ['name' => 'Server & Cloud Infrastructure',      'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',        'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'Core Banking Ledger License',
                'price'    => 12000,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    'Double-entry high throughput ledger',
                    'Multi-currency accounts & interest calculation',
                    'Audit trails & regulatory reporting modules',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ],

    'esim' => [
        'name'        => 'eSIM & Telecom Platform',
        'short_name'  => 'eSIM Platform',
        'type'        => 'license',
        'tag'         => 'Telecom Infrastructure',
        'back_url'    => 'solutions-esim-telecom',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',            'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'App Store & Play Store Publishing',  'desc' => 'End-to-end publishing, review responses, and certificate signing.',                  'price' => 250],
            ['name' => 'Server & Cloud Infrastructure',      'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',        'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'eSIM Platform License',
                'price'    => 7500,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    '150+ countries eSIM SM-DP+ provisioning',
                    'Reseller API, customer mobile apps & web portal',
                    'Real-time data usage tracking & top-ups',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ],

    'school' => [
        'name'        => 'School Management System (SIS)',
        'short_name'  => 'School Management',
        'type'        => 'license',
        'tag'         => 'EdTech System',
        'back_url'    => 'solutions-school-management',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',          'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'Server & Cloud Infrastructure',    'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',      'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'School Management License',
                'price'    => 8000,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    'Student Information System (SIS) & admissions',
                    'Automated fee collection & payment gateway',
                    'Parent, teacher & student dedicated portals',
                    'Grading, attendance & report cards',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ],

    'lms' => [
        'name'        => 'LMS & EdTech Platform',
        'short_name'  => 'LMS / EdTech',
        'type'        => 'license',
        'tag'         => 'EdTech',
        'back_url'    => 'solutions-lms-edtech',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',          'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'Server & Cloud Infrastructure',    'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',      'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'LMS Platform License',
                'price'    => 8000,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    'Interactive video courses, quizzes & certificates',
                    'Live classroom integration & tutor management',
                    'Subscription billing & course marketplace',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ],

    'ecommerce' => [
        'name'        => 'eCommerce & Multi-Vendor Marketplace',
        'short_name'  => 'eCommerce Marketplace',
        'type'        => 'license',
        'tag'         => 'Digital Commerce',
        'back_url'    => 'solutions-ecommerce-marketplace',
        'default_plan'=> 'standard',
        'addons'      => [
            ['name' => 'Branding & Identity Kit',            'desc' => 'Logo, custom colorway, white-label design assets & guidelines.',                     'price' => 250],
            ['name' => 'App Store & Play Store Publishing',  'desc' => 'End-to-end publishing, review responses, and certificate signing.',                  'price' => 250],
            ['name' => 'Marketing & Growth Analytics Stack', 'desc' => 'Segment, Mixpanel, user onboarding funnels, and CRM setup.',                        'price' => 400],
            ['name' => 'Server & Cloud Infrastructure',      'desc' => 'AWS/GCP provisioning, SSL, domain setup, CI/CD pipeline configuration.',             'price' => 350],
            ['name' => 'Extended Support (+6 Months)',        'desc' => 'Additional 6 months of priority engineering support & bug fixes beyond standard.',   'price' => 500],
        ],
        'plans'       => [
            'standard' => [
                'name'     => 'eCommerce Platform License',
                'price'    => 8500,
                'period'   => 'one-time',
                'badge'    => 'Full IP License',
                'features' => [
                    'Multi-vendor storefront & vendor payout split',
                    'Cart checkout, inventory tracking & logistics',
                    'Customer iOS/Android apps & merchant dashboard',
                    '120 days deployment & tech support'
                ]
            ]
        ]
    ]
];

// Aliases for alternate route naming
$catalog['systems-enterprise-operating-system'] = &$catalog['systems-enterprise-os'];

// Determine Active Selection
$selectedSlug = isset($_GET['product']) && isset($catalog[$_GET['product']]) ? $_GET['product'] : 'tech-team';
$activeProduct = $catalog[$selectedSlug];

$selectedPlanSlug = isset($_GET['plan']) && isset($activeProduct['plans'][$_GET['plan']]) ? $_GET['plan'] : $activeProduct['default_plan'];
$activePlan = $activeProduct['plans'][$selectedPlanSlug];

// Crypto Conversion Rates
$rates = [
    'USDT' => 1.0,
    'BTC'  => 62000.0,
    'ETH'  => 3400.0,
];

// Wallet Addresses
$wallets = [
    'USDT_TRC20' => 'TQ9x7cNesvraEnterpriseWalletTRC20Address8472',
    'USDT_ERC20' => '0x71C8a97F00c598F56708b7e28A816223B81e5927',
    'BTC'        => 'bc1qnesvraenterprisepayments98234710293847120',
    'ETH'        => '0x71C8a97F00c598F56708b7e28A816223B81e5927',
];

// Handle Checkout Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $orderRef = 'NES-' . strtoupper(substr(uniqid(), -6));
    $submittedProductSlug = $_POST['product_slug'] ?? $selectedSlug;
    $submittedPlanSlug    = $_POST['plan_slug'] ?? $selectedPlanSlug;
    
    $productObj = $catalog[$submittedProductSlug] ?? $activeProduct;
    $planObj    = $productObj['plans'][$submittedPlanSlug] ?? $activePlan;
    
    $_SESSION['latest_order'] = [
        'ref'          => $orderRef,
        'product'      => $productObj['name'],
        'plan_name'    => $planObj['name'],
        'price_usd'    => floatval($_POST['total_usd'] ?? $planObj['price']),
        'crypto_type'  => $_POST['crypto_type'] ?? 'USDT',
        'network'      => $_POST['crypto_network'] ?? 'TRC20',
        'crypto_amt'   => $_POST['total_crypto'] ?? ($planObj['price'] . ' USDT'),
        'txid'         => trim($_POST['txid'] ?? ''),
        'customer'     => [
            'name'    => trim($_POST['fullname'] ?? $user['fullname']),
            'email'   => trim($_POST['email'] ?? $user['email']),
            'phone'   => trim($_POST['phone'] ?? $user['phone']),
            'company' => trim($_POST['company'] ?? $user['company']),
            'country' => trim($_POST['country'] ?? $user['country']),
            'notes'   => trim($_POST['notes'] ?? ''),
        ],
        'addons'       => $_POST['addons'] ?? [],
        'timestamp'    => date('Y-m-d H:i:s'),
    ];

    header('Location: order-success');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<?php
$pagetitle = "Checkout — " . $activeProduct['name'] . " | Nesvra";
include 'components/head.php';
?>

<style>
    .plan-pill-btn {
        transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1);
    }
    .plan-pill-btn.active {
        background-color: #081F5C;
        color: #ffffff;
        border-color: #081F5C;
        box-shadow: 0 10px 25px -5px rgba(8, 31, 92, 0.25);
    }
</style>

<body class="bg-[#F8FAFC] min-h-screen text-slate-900 selection:bg-brandOrange selection:text-white pb-20">

    <!-- ═══ TOP BAR: CRYPTO TICKER & BACK LINK ═══ -->
    <div class="bg-royal text-white py-3 px-4 sm:px-8 text-xs">
        <div class="max-w-6xl mx-auto flex flex-wrap items-center justify-between gap-3">
            <a href="<?= htmlspecialchars($activeProduct['back_url']) ?>" onclick="if (window.history.length > 1) { event.preventDefault(); window.history.back(); }" class="inline-flex items-center gap-1.5 text-white/80 hover:text-white font-semibold transition-colors group">
                <i class="ri-arrow-left-line group-hover:-translate-x-0.5 transition-transform"></i> Back to previous page
            </a>

            <div class="flex items-center gap-2 text-white/90">
                <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full bg-emerald-500/20 text-emerald-300 font-mono text-[11px] font-semibold border border-emerald-500/30">
                    <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span> Secure crypto checkout
                </span>
                <span class="hidden md:inline text-white/50">|</span>
                <span class="hidden md:inline text-white/70">Logged in as: <strong class="text-white"><?= htmlspecialchars($user['email']) ?></strong></span>
            </div>

            <div class="hidden lg:flex items-center gap-4 font-mono text-[11px] text-white/70">
                <span>1 USDT = <strong class="text-white">$1</strong></span>
                <span>1 BTC ≈ <strong class="text-white">$62,000</strong></span>
                <span>1 ETH ≈ <strong class="text-white">$3,400</strong></span>
            </div>
        </div>
    </div>

    <!-- ═══ MAIN HEADER ═══ -->
    <div class="max-w-6xl mx-auto px-4 sm:px-8 pt-10 pb-6">
        <h1 class="text-3xl sm:text-4xl font-extrabold text-royal tracking-tight">Complete Your Checkout</h1>
        <p class="text-soft text-sm sm:text-base mt-2 max-w-3xl leading-relaxed">
            Review your selected package, advance or customize your plan, select add-ons, and complete your order to proceed with onboarding.
        </p>
    </div>

    <!-- ═══ CHECKOUT FORM & LAYOUT ═══ -->
    <div class="max-w-6xl mx-auto px-4 sm:px-8">
        <form id="checkoutForm" method="POST" action="checkout" class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
            
            <input type="hidden" name="product_slug" id="productSlugHidden" value="<?= htmlspecialchars($selectedSlug) ?>" />
            <input type="hidden" name="plan_slug" id="planSlugHidden" value="<?= htmlspecialchars($selectedPlanSlug) ?>" />
            <input type="hidden" name="total_usd" id="totalUsdHidden" value="<?= $activePlan['price'] ?>" />
            <input type="hidden" name="total_crypto" id="totalCryptoHidden" value="<?= $activePlan['price'] ?> USDT" />
            <input type="hidden" name="crypto_type" id="cryptoTypeHidden" value="USDT" />
            <input type="hidden" name="crypto_network" id="cryptoNetworkHidden" value="TRC20" />

            <!-- ── LEFT COLUMN (PACKAGE DETAILS, PLAN ADVANCEMENT & CUSTOMER) ── -->
            <div class="lg:col-span-7 flex flex-col gap-6">

                <!-- 1. SELECTED PRODUCT & PLAN ADVANCEMENT BOX -->
                <div class="bg-white border border-slate-200/90 rounded-[28px] p-6 sm:p-8 shadow-sm">
                    <div class="flex items-center justify-between mb-4">
                        <span class="font-mono text-[11px] font-bold uppercase tracking-wider text-brandOrange">Selected Package</span>
                        <span class="text-xs font-semibold text-royal bg-slate-100 px-3 py-1.5 rounded-full border border-slate-200"><?= htmlspecialchars($activeProduct['tag']) ?></span>
                    </div>

                    <!-- Plan Advance / Upgrade Switcher Bar -->
                    <div id="planSwitcherContainer" class="mb-6 <?= count($activeProduct['plans']) > 1 ? '' : 'hidden' ?>">
                        <p class="text-xs font-bold text-slate-700 uppercase tracking-wider mb-2.5 flex items-center justify-between">
                            <span>Select / Advance Plan:</span>
                            <span class="text-brandOrange text-[11px] font-mono lowercase">click to switch tier</span>
                        </p>
                        <div id="planPillButtons" class="grid grid-cols-2 sm:grid-cols-4 gap-2">
                            <?php foreach ($activeProduct['plans'] as $pSlug => $pData): 
                                $isActive = ($pSlug === $selectedPlanSlug);
                            ?>
                                <button type="button" 
                                        class="plan-pill-btn p-3 rounded-2xl border text-left flex flex-col justify-between <?= $isActive ? 'active' : 'border-slate-200 bg-slate-50/70 text-slate-700 hover:bg-slate-100' ?>"
                                        data-planslug="<?= $pSlug ?>"
                                        onclick="selectPlan('<?= $pSlug ?>')">
                                    <div class="flex items-center justify-between">
                                        <span class="text-xs font-bold"><?= $pData['name'] ?></span>
                                    </div>
                                    <div class="mt-2 font-mono text-xs font-bold">
                                        $<?= number_format($pData['price']) ?><span class="text-[10px] font-normal opacity-80"><?= $pData['period'] ?></span>
                                    </div>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Product Summary Header Box -->
                    <div class="p-6 rounded-2xl bg-gradient-to-br from-slate-50 to-slate-100/60 border border-slate-200/80">
                        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                            <div>
                                <div class="flex items-center gap-2">
                                    <h3 id="productTitleDisplay" class="text-xl font-bold text-royal tracking-tight"><?= htmlspecialchars($activeProduct['name']) ?></h3>
                                </div>
                                <p id="planNameDisplay" class="text-sm font-bold text-brandOrange mt-0.5"><?= htmlspecialchars($activePlan['name']) ?> (<span id="planPeriodDisplay"><?= $activePlan['period'] ?></span>)</p>
                            </div>
                            <div class="text-left sm:text-right flex-shrink-0">
                                <span id="productPriceDisplay" class="text-3xl font-extrabold text-royal font-mono">$<?= number_format($activePlan['price']) ?></span>
                                <span id="productUsdtDisplay" class="block text-xs font-semibold text-emerald-600 font-mono mt-0.5">≈ <?= number_format($activePlan['price'], 2) ?> USDT</span>
                            </div>
                        </div>

                        <!-- Included Features Breakdown -->
                        <div class="mt-5 pt-5 border-t border-slate-200/80">
                            <p class="text-xs font-bold uppercase tracking-wider text-slate-500 mb-3">What is included in this package:</p>
                            <ul id="includedFeaturesList" class="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-slate-700">
                                <?php foreach ($activePlan['features'] as $feat): ?>
                                    <li class="flex items-center gap-2">
                                        <i class="ri-checkbox-circle-fill text-emerald-500 text-sm shrink-0"></i>
                                        <span><?= htmlspecialchars($feat) ?></span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                </div>

                <!-- 2. CUSTOMER DETAILS (PRE-FILLED) -->
                <div class="bg-white border border-slate-200/90 rounded-[28px] p-6 sm:p-8 shadow-sm">
                    <div class="mb-5">
                        <h2 class="text-lg font-bold text-royal tracking-tight">Customer Details</h2>
                        <p class="text-xs text-soft mt-0.5">Your order receipts, onboarding invitation, and source code access will be sent here.</p>
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-semibold text-slate-700 mb-1.5">Full Name <span class="text-brandOrange">*</span></label>
                            <input type="text" name="fullname" required value="<?= htmlspecialchars($user['fullname']) ?>" placeholder="John Doe"
                                   class="w-full px-4 py-3 text-sm border border-slate-200 rounded-2xl outline-none focus:border-electric focus:ring-2 focus:ring-electric/10 transition-all text-slate-800 placeholder:text-slate-300" />
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-slate-700 mb-1.5">Email Address <span class="text-brandOrange">*</span></label>
                            <input type="email" name="email" required value="<?= htmlspecialchars($user['email']) ?>" placeholder="john@company.com"
                                   class="w-full px-4 py-3 text-sm border border-slate-200 rounded-2xl outline-none focus:border-electric focus:ring-2 focus:ring-electric/10 transition-all text-slate-800 placeholder:text-slate-300" />
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-slate-700 mb-1.5">Phone Number <span class="text-brandOrange">*</span></label>
                            <input type="tel" name="phone" required value="<?= htmlspecialchars($user['phone'] ?? '') ?>" placeholder="+1 000 000 0000"
                                   class="w-full px-4 py-3 text-sm border border-slate-200 rounded-2xl outline-none focus:border-electric focus:ring-2 focus:ring-electric/10 transition-all text-slate-800 placeholder:text-slate-300" />
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-slate-700 mb-1.5">Company Name</label>
                            <input type="text" name="company" value="<?= htmlspecialchars($user['company'] ?? '') ?>" placeholder="Acme Financial Ltd"
                                   class="w-full px-4 py-3 text-sm border border-slate-200 rounded-2xl outline-none focus:border-electric focus:ring-2 focus:ring-electric/10 transition-all text-slate-800 placeholder:text-slate-300" />
                        </div>
                        <div class="sm:col-span-2">
                            <label class="block text-xs font-semibold text-slate-700 mb-1.5">Country <span class="text-brandOrange">*</span></label>
                            <div class="relative">
                                <select name="country" class="w-full px-4 py-3 text-sm border border-slate-200 rounded-2xl outline-none focus:border-electric focus:ring-2 focus:ring-electric/10 transition-all text-slate-800 appearance-none bg-white">
                                    <option value="United States">United States</option>
                                    <option value="United Kingdom">United Kingdom</option>
                                    <option value="Nigeria" <?= ($user['country'] ?? '') === 'Nigeria' ? 'selected' : '' ?>>Nigeria</option>
                                    <option value="Ghana" <?= ($user['country'] ?? '') === 'Ghana' ? 'selected' : '' ?>>Ghana</option>
                                    <option value="Kenya" <?= ($user['country'] ?? '') === 'Kenya' ? 'selected' : '' ?>>Kenya</option>
                                    <option value="South Africa" <?= ($user['country'] ?? '') === 'South Africa' ? 'selected' : '' ?>>South Africa</option>
                                    <option value="Canada">Canada</option>
                                    <option value="United Arab Emirates">United Arab Emirates</option>
                                    <option value="Other">Other Country</option>
                                </select>
                                <i class="ri-arrow-down-s-line absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"></i>
                            </div>
                        </div>
                        <div class="sm:col-span-2">
                            <label class="block text-xs font-semibold text-slate-700 mb-1.5">Extra Notes <span class="text-slate-400 font-normal">(Optional)</span></label>
                            <textarea name="notes" rows="2" placeholder="Specific integrations, cloud deployment preferences, or custom requirements..."
                                      class="w-full px-4 py-3 text-sm border border-slate-200 rounded-2xl outline-none focus:border-electric focus:ring-2 focus:ring-electric/10 transition-all text-slate-800 placeholder:text-slate-300 resize-none"></textarea>
                        </div>
                    </div>
                </div>

                <!-- 3. AVAILABLE ADD-ONS (CONTEXTUAL PER PRODUCT) -->
                <?php $addons = $activeProduct['addons'] ?? []; ?>
                <div id="addonsSection" class="bg-white border border-slate-200/90 rounded-[28px] p-6 sm:p-8 shadow-sm <?= empty($addons) ? 'hidden' : '' ?>">
                    <div class="mb-5">
                        <h2 class="text-lg font-bold text-royal tracking-tight">Available Add-ons</h2>
                        <p class="text-xs text-soft mt-0.5">Optional packages relevant to your selected product.</p>
                    </div>

                    <div id="addonsContainer" class="flex flex-col gap-3">
                        <?php foreach ($addons as $addon): ?>
                            <label class="flex items-start justify-between gap-4 p-4 rounded-2xl border border-slate-200/80 hover:border-slate-300 transition-all cursor-pointer bg-slate-50/50">
                                <div class="flex items-start gap-3">
                                    <input type="checkbox" name="addons[]" value="<?= htmlspecialchars($addon['name']) ?>" data-price="<?= $addon['price'] ?>" class="addon-checkbox mt-1 w-4 h-4 rounded accent-electric cursor-pointer" />
                                    <div>
                                        <span class="text-sm font-bold text-slate-900 block"><?= htmlspecialchars($addon['name']) ?></span>
                                        <span class="text-xs text-soft"><?= htmlspecialchars($addon['desc']) ?></span>
                                    </div>
                                </div>
                                <div class="text-right flex-shrink-0">
                                    <span class="text-sm font-bold text-royal font-mono">+$<?= number_format($addon['price']) ?></span>
                                    <span class="block text-[10px] text-emerald-600 font-mono">≈ <?= number_format($addon['price'], 2) ?> USDT</span>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

            </div>

            <!-- ── RIGHT COLUMN (PAYMENT METHOD & SUBMIT) ── -->
            <div class="lg:col-span-5 flex flex-col gap-6 sticky top-8">
                <div class="bg-white border border-slate-200/90 rounded-[28px] p-6 sm:p-8 shadow-sm">
                    <div class="mb-5">
                        <h2 class="text-lg font-bold text-royal tracking-tight">Payment Details</h2>
                        <p class="text-xs text-soft mt-0.5">Select your crypto asset to view the deposit address.</p>
                    </div>

                    <!-- 1. Select Cryptocurrency -->
                    <div class="mb-5">
                        <label class="block text-xs font-semibold text-slate-700 mb-2">1. Select Cryptocurrency</label>
                        <div class="grid grid-cols-3 gap-2">
                            <!-- USDT -->
                            <label class="crypto-btn border-2 border-electric bg-electric/5 rounded-2xl p-3 text-center cursor-pointer transition-all flex flex-col items-center justify-center">
                                <input type="radio" name="crypto_select" value="USDT" checked class="hidden" />
                                <span class="text-xs font-bold text-slate-900">USDT</span>
                                <span class="text-[10px] text-slate-500 font-mono mt-0.5" id="btnAmtUSDT">$<?= number_format($activePlan['price']) ?></span>
                            </label>
                            <!-- BTC -->
                            <label class="crypto-btn border border-slate-200 rounded-2xl p-3 text-center cursor-pointer transition-all flex flex-col items-center justify-center">
                                <input type="radio" name="crypto_select" value="BTC" class="hidden" />
                                <span class="text-xs font-bold text-slate-900">BTC</span>
                                <span class="text-[10px] text-slate-500 font-mono mt-0.5" id="btnAmtBTC">0.129 BTC</span>
                            </label>
                            <!-- ETH -->
                            <label class="crypto-btn border border-slate-200 rounded-2xl p-3 text-center cursor-pointer transition-all flex flex-col items-center justify-center">
                                <input type="radio" name="crypto_select" value="ETH" class="hidden" />
                                <span class="text-xs font-bold text-slate-900">ETH</span>
                                <span class="text-[10px] text-slate-500 font-mono mt-0.5" id="btnAmtETH">2.35 ETH</span>
                            </label>
                        </div>
                    </div>

                    <!-- 2. USDT Network Switcher (When USDT is active) -->
                    <div id="networkSelectorContainer" class="mb-5">
                        <label class="block text-xs font-semibold text-slate-700 mb-2">2. USDT Network</label>
                        <div class="grid grid-cols-2 gap-2">
                            <label class="net-btn border-2 border-royal bg-slate-50 rounded-2xl p-3 text-center cursor-pointer transition-all">
                                <input type="radio" name="usdt_net" value="TRC20" checked class="hidden" />
                                <span class="text-xs font-bold text-royal block">TRC20 (Tron)</span>
                                <span class="text-[10px] text-emerald-600 font-medium">Recommended · Low fees</span>
                            </label>
                            <label class="net-btn border border-slate-200 rounded-2xl p-3 text-center cursor-pointer transition-all">
                                <input type="radio" name="usdt_net" value="ERC20" class="hidden" />
                                <span class="text-xs font-bold text-slate-700 block">ERC20 (Ethereum)</span>
                                <span class="text-[10px] text-slate-400 font-medium">Standard network</span>
                            </label>
                        </div>
                    </div>

                    <!-- 3. Deposit Box (Wallet + Total) -->
                    <div class="p-5 rounded-2xl bg-slate-900 text-white mb-5 shadow-inner">
                        <div class="flex items-center justify-between pb-3 border-b border-slate-800 text-xs">
                            <span class="text-slate-400" id="boxPaymentVia">Payment via USDT (TRC20)</span>
                            <span class="text-emerald-400 font-mono font-bold" id="boxTotalCrypto"><?= number_format($activePlan['price'], 2) ?> USDT</span>
                        </div>
                        <div class="py-3">
                            <span class="block text-[10px] text-slate-400 uppercase tracking-widest font-mono mb-1.5" id="boxWalletLabel">USDT (TRC20) Wallet Address</span>
                            <div class="flex items-center gap-2 bg-slate-950 p-2.5 rounded-xl border border-slate-800">
                                <input type="text" id="walletAddressInput" readonly value="<?= $wallets['USDT_TRC20'] ?>"
                                       class="bg-transparent text-xs text-white font-mono flex-1 outline-none select-all" />
                                <button type="button" id="copyWalletBtn" class="px-3 py-1 bg-royal text-white rounded-lg text-xs font-semibold hover:bg-electric transition-colors shrink-0 flex items-center gap-1">
                                    <i class="ri-file-copy-line"></i> <span>Copy</span>
                                </button>
                            </div>
                        </div>
                        <div class="pt-3 border-t border-slate-800 flex items-center justify-between text-xs">
                            <span class="text-slate-400">Total USD Equivalent</span>
                            <span class="text-white font-bold font-mono text-sm" id="boxTotalUsd">$<?= number_format($activePlan['price']) ?> USD</span>
                        </div>
                    </div>

                    <!-- 4. TxID / Hash Input -->
                    <div class="mb-5">
                        <label class="block text-xs font-semibold text-slate-700 mb-1.5">Transaction Hash / TxID <span class="text-brandOrange">*</span></label>
                        <input type="text" name="txid" required placeholder="e.g. 8f4b23c91d8e7a0f..."
                               class="w-full px-4 py-3 text-xs font-mono border border-slate-200 rounded-2xl outline-none focus:border-electric focus:ring-2 focus:ring-electric/10 transition-all text-slate-800 placeholder:text-slate-300" />
                        <span class="block text-[11px] text-soft mt-1">Paste your blockchain transaction hash once sent.</span>
                    </div>

                    <!-- 5. Submit Order Button -->
                    <button type="submit" class="w-full py-4 rounded-2xl bg-royal text-white font-bold text-sm hover:bg-electric active:scale-[0.99] transition-all duration-200 shadow-xl shadow-royal/20 flex items-center justify-center gap-2">
                        <i class="ri-shield-check-line text-lg"></i>
                        <span>Complete Order Submission</span>
                    </button>

                    <p class="text-center text-[11px] text-soft mt-3">
                        Instant onboarding & confirmation dispatch upon blockchain verification.
                    </p>
                </div>
            </div>

        </form>
    </div>

    <!-- ═══ DYNAMIC CLIENT-SIDE CALCULATOR & INTERACTIVE UPGRADE SCRIPT ═══ -->
    <script>
        const catalog = <?= json_encode($catalog) ?>;
        const rates = <?= json_encode($rates) ?>;
        const wallets = <?= json_encode($wallets) ?>;

        let activeSlug = "<?= $selectedSlug ?>";
        let activePlanSlug = "<?= $selectedPlanSlug ?>";
        let activeCrypto = 'USDT';
        let activeNetwork = 'TRC20';

        // DOM elements
        const productSlugHidden = document.getElementById('productSlugHidden');
        const planSlugHidden = document.getElementById('planSlugHidden');
        const totalUsdHidden = document.getElementById('totalUsdHidden');
        const totalCryptoHidden = document.getElementById('totalCryptoHidden');
        const cryptoTypeHidden = document.getElementById('cryptoTypeHidden');
        const cryptoNetworkHidden = document.getElementById('cryptoNetworkHidden');

        const planSwitcherContainer = document.getElementById('planSwitcherContainer');
        const planPillButtons = document.getElementById('planPillButtons');

        const productTitleDisplay = document.getElementById('productTitleDisplay');
        const planNameDisplay = document.getElementById('planNameDisplay');
        const planPeriodDisplay = document.getElementById('planPeriodDisplay');
        const productPriceDisplay = document.getElementById('productPriceDisplay');
        const productUsdtDisplay = document.getElementById('productUsdtDisplay');
        const includedFeaturesList = document.getElementById('includedFeaturesList');

        const btnAmtUSDT = document.getElementById('btnAmtUSDT');
        const btnAmtBTC = document.getElementById('btnAmtBTC');
        const btnAmtETH = document.getElementById('btnAmtETH');

        const networkSelectorContainer = document.getElementById('networkSelectorContainer');
        const boxPaymentVia = document.getElementById('boxPaymentVia');
        const boxWalletLabel = document.getElementById('boxWalletLabel');
        const walletAddressInput = document.getElementById('walletAddressInput');
        const boxTotalCrypto = document.getElementById('boxTotalCrypto');
        const boxTotalUsd = document.getElementById('boxTotalUsd');

        function renderPlanButtons() {
            const product = catalog[activeSlug];
            const planKeys = Object.keys(product.plans);
            
            if (planKeys.length <= 1) {
                planSwitcherContainer.classList.add('hidden');
                activePlanSlug = planKeys[0];
            } else {
                planSwitcherContainer.classList.remove('hidden');
                if (!product.plans[activePlanSlug]) {
                    activePlanSlug = product.default_plan || planKeys[0];
                }
                
                let html = '';
                planKeys.forEach(pKey => {
                    const p = product.plans[pKey];
                    const isActive = (pKey === activePlanSlug);
                    html += `
                        <button type="button" 
                                class="plan-pill-btn p-3 rounded-2xl border text-left flex flex-col justify-between ${isActive ? 'active' : 'border-slate-200 bg-slate-50/70 text-slate-700 hover:bg-slate-100'}"
                                onclick="selectPlan('${pKey}')">
                            <div class="flex items-center justify-between">
                                <span class="text-xs font-bold">${p.name}</span>
                            </div>
                            <div class="mt-2 font-mono text-xs font-bold">
                                $${p.price.toLocaleString()}<span class="text-[10px] font-normal opacity-80">${p.period}</span>
                            </div>
                        </button>
                    `;
                });
                planPillButtons.innerHTML = html;
            }
        }

        function renderAddons() {
            const product = catalog[activeSlug];
            const addons = product.addons || [];
            const addonsSection = document.getElementById('addonsSection');
            const addonsContainer = document.getElementById('addonsContainer');

            if (addons.length === 0) {
                addonsSection.classList.add('hidden');
                addonsContainer.innerHTML = '';
                return;
            }

            addonsSection.classList.remove('hidden');
            let html = '';
            addons.forEach(addon => {
                html += `
                    <label class="flex items-start justify-between gap-4 p-4 rounded-2xl border border-slate-200/80 hover:border-slate-300 transition-all cursor-pointer bg-slate-50/50">
                        <div class="flex items-start gap-3">
                            <input type="checkbox" name="addons[]" value="${addon.name}" data-price="${addon.price}" class="addon-checkbox mt-1 w-4 h-4 rounded accent-electric cursor-pointer" />
                            <div>
                                <span class="text-sm font-bold text-slate-900 block">${addon.name}</span>
                                <span class="text-xs text-soft">${addon.desc}</span>
                            </div>
                        </div>
                        <div class="text-right flex-shrink-0">
                            <span class="text-sm font-bold text-royal font-mono">+$${addon.price.toLocaleString()}</span>
                            <span class="block text-[10px] text-emerald-600 font-mono">≈ ${addon.price.toFixed(2)} USDT</span>
                        </div>
                    </label>
                `;
            });
            addonsContainer.innerHTML = html;

            // Re-bind addon checkbox listeners
            addonsContainer.querySelectorAll('.addon-checkbox').forEach(cb => {
                cb.addEventListener('change', updateUI);
            });
        }

        function selectPlan(pSlug) {
            activePlanSlug = pSlug;
            renderPlanButtons();
            updateUI();
        }

        function updateUI() {
            const product = catalog[activeSlug];
            const plan = product.plans[activePlanSlug] || product.plans[product.default_plan];

            // Base Price
            let basePrice = plan.price;

            // Calculate Add-ons
            let addonsTotal = 0;
            document.querySelectorAll('.addon-checkbox:checked').forEach(cb => {
                addonsTotal += parseFloat(cb.getAttribute('data-price')) || 0;
            });

            const totalUSD = basePrice + addonsTotal;
            const totalUSDT = totalUSD.toFixed(2);
            const totalBTC = (totalUSD / rates['BTC']).toFixed(6);
            const totalETH = (totalUSD / rates['ETH']).toFixed(4);

            // Update Product Card Display
            productTitleDisplay.textContent = product.name;
            planNameDisplay.textContent = `${plan.name} (${plan.period})`;
            planPeriodDisplay.textContent = plan.period;
            productPriceDisplay.textContent = '$' + totalUSD.toLocaleString();
            productUsdtDisplay.textContent = '≈ ' + totalUSDT + ' USDT';

            // Update Included Features
            let featHtml = '';
            plan.features.forEach(f => {
                featHtml += `
                    <li class="flex items-center gap-2">
                        <i class="ri-checkbox-circle-fill text-emerald-500 text-sm shrink-0"></i>
                        <span>${f}</span>
                    </li>
                `;
            });
            includedFeaturesList.innerHTML = featHtml;

            // Update Crypto Buttons Values
            btnAmtUSDT.textContent = totalUSDT + ' USDT';
            btnAmtBTC.textContent = totalBTC + ' BTC';
            btnAmtETH.textContent = totalETH + ' ETH';

            // Determine Active Crypto Amount & Wallet
            let cryptoAmountFormatted = '';
            let walletKey = activeCrypto;

            if (activeCrypto === 'USDT') {
                cryptoAmountFormatted = totalUSDT + ' USDT';
                walletKey = 'USDT_' + activeNetwork;
                networkSelectorContainer.classList.remove('hidden');
                boxWalletLabel.textContent = `USDT (${activeNetwork}) Wallet Address`;
                boxPaymentVia.textContent = `Payment via USDT (${activeNetwork})`;
            } else {
                networkSelectorContainer.classList.add('hidden');
                if (activeCrypto === 'BTC') {
                    cryptoAmountFormatted = totalBTC + ' BTC';
                    boxWalletLabel.textContent = 'BTC (Bitcoin) Wallet Address';
                    boxPaymentVia.textContent = 'Payment via Bitcoin (BTC)';
                } else {
                    cryptoAmountFormatted = totalETH + ' ETH';
                    boxWalletLabel.textContent = 'ETH (Ethereum) Wallet Address';
                    boxPaymentVia.textContent = 'Payment via Ethereum (ETH)';
                }
            }

            walletAddressInput.value = wallets[walletKey] || wallets['USDT_TRC20'];
            boxTotalCrypto.textContent = cryptoAmountFormatted;
            boxTotalUsd.textContent = `≈ $${totalUSD.toLocaleString()} USD`;

            // Hidden Inputs for Form Submission
            productSlugHidden.value = activeSlug;
            planSlugHidden.value = activePlanSlug;
            totalUsdHidden.value = totalUSD;
            totalCryptoHidden.value = cryptoAmountFormatted;
            cryptoTypeHidden.value = activeCrypto;
            cryptoNetworkHidden.value = activeNetwork;
        }

        // Initial Addon Toggles (server-rendered)
        document.querySelectorAll('.addon-checkbox').forEach(cb => {
            cb.addEventListener('change', updateUI);
        });

        // Crypto Radios
        document.querySelectorAll('input[name="crypto_select"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                activeCrypto = e.target.value;
                document.querySelectorAll('.crypto-btn').forEach(btn => {
                    btn.classList.remove('border-electric', 'bg-electric/5');
                    btn.classList.add('border-slate-200');
                });
                const selectedBtn = radio.closest('.crypto-btn');
                selectedBtn.classList.remove('border-slate-200');
                selectedBtn.classList.add('border-electric', 'bg-electric/5');
                updateUI();
            });
        });

        // Network Radios
        document.querySelectorAll('input[name="usdt_net"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                activeNetwork = e.target.value;
                document.querySelectorAll('.net-btn').forEach(btn => {
                    btn.classList.remove('border-2', 'border-royal', 'bg-slate-50');
                    btn.classList.add('border', 'border-slate-200');
                });
                const selectedBtn = radio.closest('.net-btn');
                selectedBtn.classList.remove('border-slate-200');
                selectedBtn.classList.add('border-2', 'border-royal', 'bg-slate-50');
                updateUI();
            });
        });

        // Copy Wallet Address
        const copyBtn = document.getElementById('copyWalletBtn');
        copyBtn.addEventListener('click', () => {
            navigator.clipboard.writeText(walletAddressInput.value).then(() => {
                const origHtml = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i class="ri-check-line text-emerald-400"></i> <span>Copied!</span>';
                copyBtn.classList.add('bg-emerald-500/20');
                setTimeout(() => {
                    copyBtn.innerHTML = origHtml;
                    copyBtn.classList.remove('bg-emerald-500/20');
                }, 2000);
            });
        });

        // Initialize UI
        renderPlanButtons();
        updateUI();
    </script>
</body>
</html>
