<?php
/**
 * XCHANGE 2025: MULTIPLE DELEGATE TYPES MIGRATION VERIFICATION
 * 
 * This script verifies the multiple delegate types migration was successful
 * and provides detailed information about the current state.
 * 
 * Usage: php verify_delegate_migration.php [--detailed] [--check-api]
 * 
 * Options:
 *   --detailed    Show detailed product information including metadata
 *   --check-api   Test API configuration endpoint
 *   --json        Output results in JSON format
 */

require_once 'db_config.php';

class DelegateMigrationVerifier {
    private $pdo;
    private $detailed = false;
    private $checkApi = false;
    private $jsonOutput = false;
    private $results = [];
    
    // Expected delegate types
    private $expectedDelegateTypes = [
        'DELEGATE_EARLY_BIRD' => ['name' => 'Early Bird Delegate', 'price' => 450.00],
        'DELEGATE_STANDARD' => ['name' => 'Standard Delegate', 'price' => 550.00],
        'DELEGATE_STUDENT' => ['name' => 'Student Delegate', 'price' => 300.00],
        'DELEGATE_SPEAKER' => ['name' => 'Speaker', 'price' => 0.00],
        'DELEGATE_VIP' => ['name' => 'VIP Delegate', 'price' => 800.00],
        'DELEGATE_ORGANIZER' => ['name' => 'Event Organizer', 'price' => 0.00]
    ];
    
    public function __construct() {
        $this->pdo = getDBConnection();
        
        // Parse command line arguments
        global $argv;
        if (isset($argv)) {
            $this->detailed = in_array('--detailed', $argv);
            $this->checkApi = in_array('--check-api', $argv);
            $this->jsonOutput = in_array('--json', $argv);
        }
    }
    
    public function verify() {
        try {
            if (!$this->jsonOutput) {
                $this->output("=== MULTIPLE DELEGATE TYPES MIGRATION VERIFICATION ===");
                $this->output("Timestamp: " . date('Y-m-d H:i:s'));
                $this->output("");
            }
            
            // Run all verification checks
            $this->checkDatabaseConnection();
            $this->checkDelegateProducts();
            $this->checkPricingTiers();
            $this->checkOldProductStatus();
            $this->checkRegistrationMigration();
            $this->checkCategoryConfiguration();
            
            if ($this->checkApi) {
                $this->checkApiConfiguration();
            }
            
            // Generate summary
            $this->generateSummary();
            
            if ($this->jsonOutput) {
                echo json_encode($this->results, JSON_PRETTY_PRINT);
            }
            
            return $this->results['overall_status'] === 'success';
            
        } catch (Exception $e) {
            $this->output("ERROR: " . $e->getMessage());
            if ($this->jsonOutput) {
                echo json_encode(['error' => $e->getMessage()]);
            }
            return false;
        }
    }
    
    private function checkDatabaseConnection() {
        $this->output("--- DATABASE CONNECTION ---");
        
        try {
            if (!$this->pdo) {
                throw new Exception("Database connection failed");
            }
            
            $stmt = $this->pdo->prepare("SELECT COUNT(*) as count FROM products");
            $stmt->execute();
            $productCount = $stmt->fetch()['count'];
            
            $this->output("✅ Database connection OK");
            $this->output("✅ Products table accessible ({$productCount} total products)");
            
            $this->results['database'] = [
                'status' => 'success',
                'connection' => 'ok',
                'total_products' => $productCount
            ];
            
        } catch (Exception $e) {
            $this->output("❌ Database connection failed: " . $e->getMessage());
            $this->results['database'] = [
                'status' => 'error',
                'error' => $e->getMessage()
            ];
            throw $e;
        }
    }
    
    private function checkDelegateProducts() {
        $this->output("\n--- DELEGATE PRODUCTS ---");
        
        $stmt = $this->pdo->prepare("
            SELECT id, product_code, name, description, base_price, currency, 
                   total_stock, is_active, max_per_registration, display_order, metadata
            FROM products 
            WHERE category_id = 3 AND is_active = 1
            ORDER BY display_order
        ");
        $stmt->execute();
        $products = $stmt->fetchAll();
        
        $foundProducts = [];
        $missingProducts = [];
        
        foreach ($products as $product) {
            $code = $product['product_code'];
            $foundProducts[] = $code;
            
            if ($code === 'DELEGATE_PASS') {
                $this->output("⚠️  Old DELEGATE_PASS product is still active (should be deactivated)");
                continue;
            }
            
            $status = "✅";
            $notes = [];
            
            // Check if this is an expected delegate type
            if (isset($this->expectedDelegateTypes[$code])) {
                $expected = $this->expectedDelegateTypes[$code];
                
                // Check name
                if ($product['name'] !== $expected['name']) {
                    $status = "⚠️ ";
                    $notes[] = "Name mismatch (expected: {$expected['name']})";
                }
                
                // Check price
                if (floatval($product['base_price']) !== $expected['price']) {
                    $status = "⚠️ ";
                    $notes[] = "Price mismatch (expected: \${$expected['price']})";
                }
            }
            
            $stock = $product['total_stock'] ? $product['total_stock'] : 'Unlimited';
            $notesStr = !empty($notes) ? ' - ' . implode(', ', $notes) : '';
            
            $this->output("{$status} {$code} | {$product['name']} | \${$product['base_price']} | Stock: {$stock}{$notesStr}");
            
            if ($this->detailed && $product['metadata']) {
                $metadata = json_decode($product['metadata'], true);
                if ($metadata) {
                    $this->output("    Metadata: " . json_encode($metadata, JSON_UNESCAPED_SLASHES));
                }
            }
        }
        
        // Check for missing products
        foreach ($this->expectedDelegateTypes as $code => $expected) {
            if (!in_array($code, $foundProducts)) {
                $missingProducts[] = $code;
                $this->output("❌ Missing: {$code} ({$expected['name']})");
            }
        }
        
        $this->results['delegate_products'] = [
            'status' => empty($missingProducts) ? 'success' : 'partial',
            'found_count' => count($foundProducts),
            'expected_count' => count($this->expectedDelegateTypes),
            'found_products' => $foundProducts,
            'missing_products' => $missingProducts,
            'products' => $products
        ];
        
        $this->output("Found: " . count($foundProducts) . "/" . count($this->expectedDelegateTypes) . " expected delegate products");
    }
    
    private function checkPricingTiers() {
        $this->output("\n--- PRICING TIERS ---");
        
        $stmt = $this->pdo->prepare("
            SELECT p.product_code, p.name as product_name, pp.pricing_tier, pp.price, 
                   pp.valid_from, pp.valid_until, pp.is_active
            FROM product_pricing pp 
            JOIN products p ON pp.product_id = p.id 
            WHERE p.category_id = 3 AND pp.is_active = 1
            ORDER BY p.display_order, pp.valid_from
        ");
        $stmt->execute();
        $tiers = $stmt->fetchAll();
        
        if (empty($tiers)) {
            $this->output("⚠️  No pricing tiers found");
            $this->results['pricing_tiers'] = [
                'status' => 'warning',
                'count' => 0,
                'tiers' => []
            ];
        } else {
            $this->output("Found " . count($tiers) . " pricing tiers:");
            
            foreach ($tiers as $tier) {
                $validFrom = $tier['valid_from'] ? date('M j, Y', strtotime($tier['valid_from'])) : 'No start date';
                $validUntil = $tier['valid_until'] ? date('M j, Y', strtotime($tier['valid_until'])) : 'No end date';
                
                $this->output("  ✅ {$tier['product_name']} | {$tier['pricing_tier']} | \${$tier['price']} | {$validFrom} to {$validUntil}");
            }
            
            $this->results['pricing_tiers'] = [
                'status' => 'success',
                'count' => count($tiers),
                'tiers' => $tiers
            ];
        }
    }
    
    private function checkOldProductStatus() {
        $this->output("\n--- OLD PRODUCT STATUS ---");
        
        $stmt = $this->pdo->prepare("
            SELECT id, name, is_active, updated_at 
            FROM products 
            WHERE product_code = 'DELEGATE_PASS'
        ");
        $stmt->execute();
        $oldProduct = $stmt->fetch();
        
        if (!$oldProduct) {
            $this->output("❌ Old DELEGATE_PASS product not found");
            $this->results['old_product'] = [
                'status' => 'error',
                'error' => 'Product not found'
            ];
        } else {
            $status = $oldProduct['is_active'] ? 'Active' : 'Deactivated';
            $statusIcon = $oldProduct['is_active'] ? '⚠️ ' : '✅';
            $lastUpdated = date('M j, Y H:i', strtotime($oldProduct['updated_at']));
            
            $this->output("{$statusIcon} DELEGATE_PASS | {$oldProduct['name']} | {$status} | Updated: {$lastUpdated}");
            
            $this->results['old_product'] = [
                'status' => $oldProduct['is_active'] ? 'warning' : 'success',
                'is_active' => $oldProduct['is_active'],
                'name' => $oldProduct['name'],
                'updated_at' => $oldProduct['updated_at']
            ];
        }
    }
    
    private function checkRegistrationMigration() {
        $this->output("\n--- REGISTRATION MIGRATION ---");
        
        // Check migrated registrations
        $stmt = $this->pdo->prepare("
            SELECT r.registration_number, r.delegate_type as old_type, r.delegate_count,
                   p.name as new_product, p.product_code, rp.quantity, rp.unit_price
            FROM registrations r
            JOIN registration_products rp ON r.id = rp.registration_id
            JOIN products p ON rp.product_id = p.id
            WHERE p.category_id = 3 AND p.product_code != 'DELEGATE_PASS'
            ORDER BY r.created_at DESC
        ");
        $stmt->execute();
        $migratedRegistrations = $stmt->fetchAll();
        
        // Check if any registrations still point to old product
        $stmt = $this->pdo->prepare("
            SELECT COUNT(*) as count
            FROM registration_products rp
            JOIN products p ON rp.product_id = p.id
            WHERE p.product_code = 'DELEGATE_PASS'
        ");
        $stmt->execute();
        $unmigrated = $stmt->fetch()['count'];
        
        if ($unmigrated > 0) {
            $this->output("❌ {$unmigrated} registration products still pointing to old DELEGATE_PASS");
        } else {
            $this->output("✅ No registrations pointing to old DELEGATE_PASS product");
        }
        
        $this->output("✅ Found " . count($migratedRegistrations) . " migrated registrations:");
        
        foreach ($migratedRegistrations as $reg) {
            $this->output("  {$reg['registration_number']} | Old: {$reg['old_type']} | New: {$reg['new_product']} | Qty: {$reg['quantity']} | \${$reg['unit_price']}");
        }
        
        $this->results['registration_migration'] = [
            'status' => $unmigrated > 0 ? 'error' : 'success',
            'migrated_count' => count($migratedRegistrations),
            'unmigrated_count' => $unmigrated,
            'migrated_registrations' => $migratedRegistrations
        ];
    }
    
    private function checkCategoryConfiguration() {
        $this->output("\n--- CATEGORY CONFIGURATION ---");
        
        // Check delegate pass category
        $stmt = $this->pdo->prepare("
            SELECT id, name, description, is_active 
            FROM product_categories 
            WHERE id = 3
        ");
        $stmt->execute();
        $category = $stmt->fetch();
        
        if (!$category) {
            $this->output("❌ Delegate Pass category (ID: 3) not found");
            $this->results['category'] = [
                'status' => 'error',
                'error' => 'Category not found'
            ];
        } else {
            $status = $category['is_active'] ? 'Active' : 'Inactive';
            $statusIcon = $category['is_active'] ? '✅' : '⚠️ ';
            
            $this->output("{$statusIcon} Category: {$category['name']} | {$status}");
            
            $this->results['category'] = [
                'status' => $category['is_active'] ? 'success' : 'warning',
                'id' => $category['id'],
                'name' => $category['name'],
                'is_active' => $category['is_active']
            ];
        }
    }
    
    private function checkApiConfiguration() {
        $this->output("\n--- API CONFIGURATION ---");
        
        try {
            // Test the API configuration endpoint
            $apiUrl = 'http://localhost/Xchange_version_2/api.php?action=get_config';
            
            $context = stream_context_create([
                'http' => [
                    'timeout' => 10,
                    'method' => 'GET'
                ]
            ]);
            
            $response = file_get_contents($apiUrl, false, $context);
            
            if ($response === false) {
                throw new Exception("Failed to fetch API configuration");
            }
            
            $config = json_decode($response, true);
            
            if (!$config) {
                throw new Exception("Invalid JSON response from API");
            }
            
            // Check delegate passes configuration
            if (!isset($config['frontend']['delegatePasses']['products'])) {
                throw new Exception("No delegate passes products in API configuration");
            }
            
            $apiDelegateProducts = $config['frontend']['delegatePasses']['products'];
            $this->output("✅ API configuration loaded successfully");
            $this->output("✅ Found " . count($apiDelegateProducts) . " delegate products in API");
            
            // List API products
            foreach ($apiDelegateProducts as $product) {
                $this->output("  - {$product['product_code']} | {$product['name']} | \${$product['base_price']}");
            }
            
            $this->results['api_configuration'] = [
                'status' => 'success',
                'delegate_products_count' => count($apiDelegateProducts),
                'products' => $apiDelegateProducts
            ];
            
        } catch (Exception $e) {
            $this->output("❌ API configuration check failed: " . $e->getMessage());
            $this->results['api_configuration'] = [
                'status' => 'error',
                'error' => $e->getMessage()
            ];
        }
    }
    
    private function generateSummary() {
        if (!$this->jsonOutput) {
            $this->output("\n=== VERIFICATION SUMMARY ===");
        }
        
        $checks = [
            'database' => 'Database Connection',
            'delegate_products' => 'Delegate Products',
            'pricing_tiers' => 'Pricing Tiers',
            'old_product' => 'Old Product Status',
            'registration_migration' => 'Registration Migration',
            'category' => 'Category Configuration'
        ];
        
        if ($this->checkApi) {
            $checks['api_configuration'] = 'API Configuration';
        }
        
        $overallStatus = 'success';
        $successCount = 0;
        $warningCount = 0;
        $errorCount = 0;
        
        foreach ($checks as $key => $label) {
            if (!isset($this->results[$key])) {
                continue;
            }
            
            $status = $this->results[$key]['status'];
            
            if (!$this->jsonOutput) {
                $icon = $status === 'success' ? '✅' : ($status === 'warning' ? '⚠️ ' : '❌');
                $this->output("{$icon} {$label}: " . ucfirst($status));
            }
            
            if ($status === 'success') {
                $successCount++;
            } elseif ($status === 'warning') {
                $warningCount++;
                if ($overallStatus === 'success') {
                    $overallStatus = 'warning';
                }
            } else {
                $errorCount++;
                $overallStatus = 'error';
            }
        }
        
        $this->results['summary'] = [
            'total_checks' => count($checks),
            'success_count' => $successCount,
            'warning_count' => $warningCount,
            'error_count' => $errorCount
        ];
        
        $this->results['overall_status'] = $overallStatus;
        
        if (!$this->jsonOutput) {
            $this->output("\nOverall Status: " . strtoupper($overallStatus));
            $this->output("Checks: {$successCount} success, {$warningCount} warnings, {$errorCount} errors");
            
            if ($overallStatus === 'success') {
                $this->output("\n🎉 Migration verification PASSED! Multiple delegate types are ready to use.");
            } elseif ($overallStatus === 'warning') {
                $this->output("\n⚠️  Migration verification completed with warnings. Review issues above.");
            } else {
                $this->output("\n❌ Migration verification FAILED. Critical issues found.");
            }
        }
    }
    
    private function output($message) {
        if (!$this->jsonOutput) {
            echo $message . "\n";
        }
    }
}

// Run verification if called directly
if (basename(__FILE__) == basename($_SERVER["SCRIPT_NAME"])) {
    $verifier = new DelegateMigrationVerifier();
    $success = $verifier->verify();
    exit($success ? 0 : 1);
}
?>
