<?php
/**
 * Complete Badge System Migration
 * 
 * This single script sets up the entire badge generation system including:
 * - Badge settings table
 * - Badge generation log table
 * - Print tracking functionality
 * - Default settings
 * - Directory structure
 * 
 * Run this once to set up the complete badge system.
 */

require_once 'db_config.php';

echo "🎫 Complete Badge System Migration\n";
echo "==================================\n\n";

try {
    $pdo = getDBConnection();
    
    echo "🔧 Setting up Badge Generation System...\n\n";
    
    // Step 1: Create badge_settings table
    echo "📊 Creating badge_settings table...\n";
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS badge_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            setting_key VARCHAR(100) NOT NULL UNIQUE COMMENT 'Unique identifier for the setting',
            setting_value TEXT NULL COMMENT 'Value of the setting (JSON for complex data)',
            setting_type ENUM('text', 'image', 'json', 'boolean') DEFAULT 'text' COMMENT 'Type of setting value',
            description TEXT NULL COMMENT 'Description of what this setting controls',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_setting_key (setting_key)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci 
        COMMENT='Stores badge generation settings and event configuration'
    ");
    echo "   ✅ badge_settings table created\n";
    
    // Step 2: Create badge_generation_log table
    echo "\n📝 Creating badge_generation_log table...\n";
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS badge_generation_log (
            id INT AUTO_INCREMENT PRIMARY KEY,
            delegate_id INT NULL COMMENT 'Delegate ID if single badge generated',
            registration_id INT NULL COMMENT 'Registration ID',
            generation_type ENUM('single', 'batch', 'preview') DEFAULT 'single',
            generated_by INT NULL COMMENT 'Admin user who generated the badge',
            file_path VARCHAR(500) NULL COMMENT 'Path to generated badge file',
            download_count INT DEFAULT 0 COMMENT 'Number of times badge was downloaded',
            is_printed BOOLEAN DEFAULT FALSE COMMENT 'Whether badge has been physically printed',
            printed_at TIMESTAMP NULL COMMENT 'When the badge was marked as printed',
            printed_by INT NULL COMMENT 'Admin user who marked the badge as printed',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_delegate_id (delegate_id),
            INDEX idx_registration_id (registration_id),
            INDEX idx_created_at (created_at),
            INDEX idx_is_printed (is_printed),
            INDEX idx_printed_at (printed_at),
            FOREIGN KEY (delegate_id) REFERENCES delegates(id) ON DELETE SET NULL,
            FOREIGN KEY (registration_id) REFERENCES registrations(id) ON DELETE SET NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci 
        COMMENT='Tracks badge generation history, downloads, and print status'
    ");
    echo "   ✅ badge_generation_log table created with print tracking\n";
    
    // Step 3: Insert default badge settings
    echo "\n⚙️ Inserting default badge settings...\n";
    $default_settings = [
        ['event_name', 'Applied HE>X CHANGE', 'text', 'Event name displayed on badge'],
        ['event_dates', '27-28 FEB 2025', 'text', 'Event dates displayed on badge'],
        ['event_location', 'MANILA, PHILIPPINES', 'text', 'Event location displayed on badge'],
        ['badge_width', '340', 'text', 'Badge width in pixels'],
        ['badge_height', '500', 'text', 'Badge height in pixels'],
        ['enable_qr_code', 'true', 'boolean', 'Enable QR code on badges'],
        ['qr_code_base_url', '', 'text', 'Base URL for QR code (e.g., https://yoursite.com/verify/)'],
        ['event_logo_path', '', 'image', 'Path to main event logo'],
        ['university_logo_path', '', 'image', 'Path to hosting university logo'],
        ['partner_logo_path', '', 'image', 'Path to partner organization logo'],
        ['badge_background_color', '#ffffff', 'text', 'Badge background color'],
        ['badge_text_color', '#000000', 'text', 'Badge primary text color'],
        ['badge_accent_color', '#6B9F3E', 'text', 'Badge accent color for highlights'],
        ['show_hosting_logo', 'true', 'boolean', 'Show hosting university logo on badge'],
        ['show_partner_logo', 'true', 'boolean', 'Show partner organization logo on badge'],
        ['footer_decoration', 'true', 'boolean', 'Show decorative footer illustration']
    ];
    
    $stmt = $pdo->prepare("
        INSERT INTO badge_settings (setting_key, setting_value, setting_type, description) 
        VALUES (?, ?, ?, ?) 
        ON DUPLICATE KEY UPDATE 
            setting_value = VALUES(setting_value),
            updated_at = CURRENT_TIMESTAMP
    ");
    
    foreach ($default_settings as $setting) {
        $stmt->execute($setting);
    }
    echo "   ✅ Default settings inserted/updated\n";
    
    // Step 4: Create directory structure
    echo "\n📁 Creating upload directories...\n";
    $directories = [
        'uploads/badges/logos',
        'uploads/badges/generated'
    ];
    
    foreach ($directories as $dir) {
        if (!is_dir($dir)) {
            if (mkdir($dir, 0755, true)) {
                echo "   ✅ Created directory: {$dir}\n";
            } else {
                echo "   ⚠️  Could not create directory: {$dir}\n";
            }
        } else {
            echo "   ✅ Directory already exists: {$dir}\n";
        }
    }
    
    // Step 5: Verify setup
    echo "\n🔍 Verifying setup...\n";
    
    // Check tables exist
    $tables = $pdo->query("SHOW TABLES LIKE 'badge%'")->fetchAll(PDO::FETCH_COLUMN);
    echo "   📊 Badge tables found: " . implode(', ', $tables) . "\n";
    
    // Check settings count
    $settings_count = $pdo->query("SELECT COUNT(*) FROM badge_settings")->fetchColumn();
    echo "   ⚙️ Badge settings: {$settings_count} configured\n";
    
    // Check directories
    $logos_dir = __DIR__ . '/uploads/badges/logos';
    $generated_dir = __DIR__ . '/uploads/badges/generated';
    echo "   📁 Upload directories:\n";
    echo "      " . (is_dir($logos_dir) ? "✅" : "❌") . " uploads/badges/logos/\n";
    echo "      " . (is_dir($generated_dir) ? "✅" : "❌") . " uploads/badges/generated/\n";
    
    echo "\n🎉 Complete Badge System Migration Successful!\n";
    echo "=============================================\n\n";
    
    echo "✅ What's been set up:\n";
    echo "   📊 Badge settings table with default configuration\n";
    echo "   📝 Badge generation log with print tracking\n";
    echo "   🖨️ Print status tracking (is_printed, printed_at, printed_by)\n";
    echo "   📁 Upload directories for logos and generated badges\n";
    echo "   ⚙️ Default event settings (Applied HE>X CHANGE)\n\n";
    
    echo "🚀 Next Steps:\n";
    echo "   1. Go to: admin/badges.php\n";
    echo "   2. Click '⚙️ Badge Settings' to upload logos\n";
    echo "   3. Configure event details if needed\n";
    echo "   4. Start generating badges!\n\n";
    
    echo "📖 Documentation:\n";
    echo "   - BADGE_GENERATION_SYSTEM.md (complete guide)\n";
    echo "   - BADGE_PRINT_TRACKING_FEATURE.md (print tracking)\n";
    echo "   - BADGE_PRINT_QUICK_START.md (quick start)\n\n";
    
    echo "🎯 Features Available:\n";
    echo "   ✅ Generate individual badges\n";
    echo "   ✅ Batch generate all badges\n";
    echo "   ✅ Print tracking and status management\n";
    echo "   ✅ Badge preview and designer\n";
    echo "   ✅ Statistics dashboard\n";
    echo "   ✅ Filter by print status\n";
    echo "   ✅ Bulk print operations\n\n";
    
    echo "🔗 Access your badge system at:\n";
    echo "   https://apps.appliedhe.one/xchange_reg/admin/badges\n\n";
    
} catch (PDOException $e) {
    echo "❌ Database Error: " . $e->getMessage() . "\n";
    echo "   Please check your database connection and try again.\n";
    exit(1);
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
    exit(1);
}
?>
