<?php
/**
 * Delegate Page Configuration
 * XChange 2025 Registration System
 * 
 * This page allows administrators to configure which product categories
 * are displayed on the frontend registration form's delegate passes section.
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';

// Get database connection
$conn = getDBConnection();

// Check authentication and permissions
$auth = new AdminAuth($conn);
$auth->requirePermission('registrations');

$currentPage = 'delegate-page';

// Handle form submissions
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$auth->hasPermission('payments')) {
        header('Location: access_denied.php');
        exit;
    }
    
    if (isset($_POST['action'])) {
        try {
            switch ($_POST['action']) {
                case 'update_delegate_config':
                    // Get selected categories for delegate passes
                    $selectedCategories = $_POST['delegate_categories'] ?? [];
                    $delegateDescription = trim($_POST['delegate_description'] ?? '');
                    
                    // Begin transaction
                    $conn->beginTransaction();
                    
                    // Clear existing delegate pass configurations
                    $clearSql = "DELETE FROM frontend_display_config WHERE page_section = 'delegate_passes'";
                    $conn->prepare($clearSql)->execute();
                    
                    // Insert new configurations
                    if (!empty($selectedCategories)) {
                        $insertSql = "INSERT INTO frontend_display_config (page_section, category_id, display_order, is_active) VALUES (?, ?, ?, 1)";
                        $insertStmt = $conn->prepare($insertSql);
                        
                        foreach ($selectedCategories as $index => $categoryId) {
                            $insertStmt->execute(['delegate_passes', intval($categoryId), $index]);
                        }
                    } else {
                        // If no categories selected, insert NULL to show all categories
                        $insertSql = "INSERT INTO frontend_display_config (page_section, category_id, display_order, is_active) VALUES ('delegate_passes', NULL, 0, 1)";
                        $conn->prepare($insertSql)->execute();
                    }
                    
                    // Update section description - handle both old and new schema
                    try {
                        // First check if the section_descriptions table exists
                        $tableCheckSql = "SHOW TABLES LIKE 'section_descriptions'";
                        $tableExists = $conn->query($tableCheckSql)->rowCount() > 0;
                        
                        if ($tableExists) {
                            // Use the new table structure
                            $updateDescSql = "INSERT INTO section_descriptions (page_section, description) VALUES (?, ?) ON DUPLICATE KEY UPDATE description = ?";
                            $conn->prepare($updateDescSql)->execute(['delegate_passes', $delegateDescription, $delegateDescription]);
                        } else {
                            // Fall back to the old column-based approach
                            $updateOldDescSql = "UPDATE frontend_display_config SET delegate_description = ? WHERE page_section = 'delegate_passes'";
                            $conn->prepare($updateOldDescSql)->execute([$delegateDescription]);
                        }
                    } catch (Exception $e) {
                        // Log error but continue - this is not critical
                        error_log("Failed to update delegate description: " . $e->getMessage());
                    }
                    
                    $conn->commit();
                    
                    $message = "Delegate page configuration updated successfully.";
                    $messageType = "success";
                    
                    // Log activity
                    $auth->logActivity('update_delegate_config', "Updated delegate page category configuration");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: delegate-page.php');
                    exit;
                    break;
                    
                case 'update_table_config':
                    // Get selected categories for table presentations
                    $selectedCategories = $_POST['table_categories'] ?? [];
                    $tableDescription = trim($_POST['table_description'] ?? '');
                    
                    // Begin transaction
                    $conn->beginTransaction();
                    
                    // Clear existing table presentation configurations
                    $clearSql = "DELETE FROM frontend_display_config WHERE page_section = 'table_presentations'";
                    $conn->prepare($clearSql)->execute();
                    
                    // Insert new configurations
                    if (!empty($selectedCategories)) {
                        $insertSql = "INSERT INTO frontend_display_config (page_section, category_id, display_order, is_active) VALUES (?, ?, ?, 1)";
                        $insertStmt = $conn->prepare($insertSql);
                        
                        foreach ($selectedCategories as $index => $categoryId) {
                            $insertStmt->execute(['table_presentations', intval($categoryId), $index]);
                        }
                    } else {
                        // If no categories selected, insert NULL to show all categories
                        $insertSql = "INSERT INTO frontend_display_config (page_section, category_id, display_order, is_active) VALUES ('table_presentations', NULL, 0, 1)";
                        $conn->prepare($insertSql)->execute();
                    }
                    
                    // Update section description - handle both old and new schema
                    try {
                        // First check if the section_descriptions table exists
                        $tableCheckSql = "SHOW TABLES LIKE 'section_descriptions'";
                        $tableExists = $conn->query($tableCheckSql)->rowCount() > 0;
                        
                        if ($tableExists) {
                            // Use the new table structure
                            $updateDescSql = "INSERT INTO section_descriptions (page_section, description) VALUES (?, ?) ON DUPLICATE KEY UPDATE description = ?";
                            $conn->prepare($updateDescSql)->execute(['table_presentations', $tableDescription, $tableDescription]);
                        } else {
                            // Fall back to the old column-based approach
                            $updateOldDescSql = "UPDATE frontend_display_config SET table_description = ? WHERE page_section = 'table_presentations'";
                            $conn->prepare($updateOldDescSql)->execute([$tableDescription]);
                        }
                    } catch (Exception $e) {
                        // Log error but continue - this is not critical
                        error_log("Failed to update table presentation description: " . $e->getMessage());
                    }
                    
                    $conn->commit();
                    
                    $message = "Table presentations configuration updated successfully.";
                    $messageType = "success";
                    
                    // Log activity
                    $auth->logActivity('update_table_config', "Updated table presentations category configuration");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: delegate-page.php');
                    exit;
                    break;
                    
                case 'update_sponsorship_config':
                    // Get selected categories for sponsorship
                    $selectedCategories = $_POST['sponsorship_categories'] ?? [];
                    $sponsorshipDescription = trim($_POST['sponsorship_description'] ?? '');
                    
                    // Begin transaction
                    $conn->beginTransaction();
                    
                    // Clear existing sponsorship configurations
                    $clearSql = "DELETE FROM frontend_display_config WHERE page_section = 'sponsorship'";
                    $conn->prepare($clearSql)->execute();
                    
                    // Insert new configurations
                    if (!empty($selectedCategories)) {
                        $insertSql = "INSERT INTO frontend_display_config (page_section, category_id, display_order, is_active) VALUES (?, ?, ?, 1)";
                        $insertStmt = $conn->prepare($insertSql);
                        
                        foreach ($selectedCategories as $index => $categoryId) {
                            $insertStmt->execute(['sponsorship', intval($categoryId), $index]);
                        }
                    } else {
                        // If no categories selected, insert NULL to show all categories
                        $insertSql = "INSERT INTO frontend_display_config (page_section, category_id, display_order, is_active) VALUES ('sponsorship', NULL, 0, 1)";
                        $conn->prepare($insertSql)->execute();
                    }
                    
                    // Update section description - handle both old and new schema
                    try {
                        // First check if the section_descriptions table exists
                        $tableCheckSql = "SHOW TABLES LIKE 'section_descriptions'";
                        $tableExists = $conn->query($tableCheckSql)->rowCount() > 0;
                        
                        if ($tableExists) {
                            // Use the new table structure
                            $updateDescSql = "INSERT INTO section_descriptions (page_section, description) VALUES (?, ?) ON DUPLICATE KEY UPDATE description = ?";
                            $conn->prepare($updateDescSql)->execute(['sponsorship', $sponsorshipDescription, $sponsorshipDescription]);
                        } else {
                            // Store in session temporarily until table is created
                            $_SESSION['temp_sponsorship_description'] = $sponsorshipDescription;
                        }
                    } catch (Exception $e) {
                        // Log error but continue - this is not critical
                        error_log("Failed to update sponsorship description: " . $e->getMessage());
                    }
                    
                    $conn->commit();
                    
                    $message = "Sponsorship configuration updated successfully.";
                    $messageType = "success";
                    
                    // Log activity
                    $auth->logActivity('update_sponsorship_config', "Updated sponsorship category configuration");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: delegate-page.php');
                    exit;
                    break;
                    
                case 'update_other_sponsorship_config':
                    // Get selected categories for other sponsorship
                    $selectedCategories = $_POST['other_sponsorship_categories'] ?? [];
                    $otherSponsorshipDescription = trim($_POST['other_sponsorship_description'] ?? '');
                    
                    // Begin transaction
                    $conn->beginTransaction();
                    
                    // Clear existing other sponsorship configurations
                    $clearSql = "DELETE FROM frontend_display_config WHERE page_section = 'other_sponsorship'";
                    $conn->prepare($clearSql)->execute();
                    
                    // Insert new configurations
                    if (!empty($selectedCategories)) {
                        $insertSql = "INSERT INTO frontend_display_config (page_section, category_id, display_order, is_active) VALUES (?, ?, ?, 1)";
                        $insertStmt = $conn->prepare($insertSql);
                        
                        foreach ($selectedCategories as $index => $categoryId) {
                            $insertStmt->execute(['other_sponsorship', intval($categoryId), $index]);
                        }
                    } else {
                        // If no categories selected, insert NULL to show all categories
                        $insertSql = "INSERT INTO frontend_display_config (page_section, category_id, display_order, is_active) VALUES ('other_sponsorship', NULL, 0, 1)";
                        $conn->prepare($insertSql)->execute();
                    }
                    
                    // Update section description - handle both old and new schema
                    try {
                        // First check if the section_descriptions table exists
                        $tableCheckSql = "SHOW TABLES LIKE 'section_descriptions'";
                        $tableExists = $conn->query($tableCheckSql)->rowCount() > 0;
                        
                        if ($tableExists) {
                            // Use the new table structure
                            $updateDescSql = "INSERT INTO section_descriptions (page_section, description) VALUES (?, ?) ON DUPLICATE KEY UPDATE description = ?";
                            $conn->prepare($updateDescSql)->execute(['other_sponsorship', $otherSponsorshipDescription, $otherSponsorshipDescription]);
                        } else {
                            // Store in session temporarily until table is created
                            $_SESSION['temp_other_sponsorship_description'] = $otherSponsorshipDescription;
                        }
                    } catch (Exception $e) {
                        // Log error but continue - this is not critical
                        error_log("Failed to update other sponsorship description: " . $e->getMessage());
                    }
                    
                    $conn->commit();
                    
                    $message = "Other Sponsorship configuration updated successfully.";
                    $messageType = "success";
                    
                    // Log activity
                    $auth->logActivity('update_other_sponsorship_config', "Updated other sponsorship category configuration");
                    
                    // Redirect to prevent form resubmission
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $messageType;
                    header('Location: delegate-page.php');
                    exit;
                    break;
            }
        } catch (Exception $e) {
            if ($conn->inTransaction()) {
                $conn->rollBack();
            }
            $message = "Error: " . $e->getMessage();
            $messageType = "error";
        }
    }
}

// Handle flash messages from redirects
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'];
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

// Get all product categories
$categoriesSql = "SELECT id, name, description, display_order, is_active FROM product_categories ORDER BY display_order, name";
$categoriesStmt = $conn->prepare($categoriesSql);
$categoriesStmt->execute();
$allCategories = $categoriesStmt->fetchAll(PDO::FETCH_ASSOC);

// Get current delegate pass configuration
$delegateConfigSql = "SELECT category_id FROM frontend_display_config WHERE page_section = 'delegate_passes' AND is_active = 1 ORDER BY display_order";
$delegateConfigStmt = $conn->prepare($delegateConfigSql);
$delegateConfigStmt->execute();
$delegateConfig = $delegateConfigStmt->fetchAll(PDO::FETCH_COLUMN);

// Get current table presentations configuration
$tableConfigSql = "SELECT category_id FROM frontend_display_config WHERE page_section = 'table_presentations' AND is_active = 1 ORDER BY display_order";
$tableConfigStmt = $conn->prepare($tableConfigSql);
$tableConfigStmt->execute();
$tableConfig = $tableConfigStmt->fetchAll(PDO::FETCH_COLUMN);

// Get current sponsorship configuration
$sponsorshipConfigSql = "SELECT category_id FROM frontend_display_config WHERE page_section = 'sponsorship' AND is_active = 1 ORDER BY display_order";
$sponsorshipConfigStmt = $conn->prepare($sponsorshipConfigSql);
$sponsorshipConfigStmt->execute();
$sponsorshipConfig = $sponsorshipConfigStmt->fetchAll(PDO::FETCH_COLUMN);

// Get current other sponsorship configuration
$otherSponsorshipConfigSql = "SELECT category_id FROM frontend_display_config WHERE page_section = 'other_sponsorship' AND is_active = 1 ORDER BY display_order";
$otherSponsorshipConfigStmt = $conn->prepare($otherSponsorshipConfigSql);
$otherSponsorshipConfigStmt->execute();
$otherSponsorshipConfig = $otherSponsorshipConfigStmt->fetchAll(PDO::FETCH_COLUMN);

// Get section descriptions - handle case where table might not exist yet
$sectionDescriptions = [];
try {
    // First check if the table exists
    $tableCheckSql = "SHOW TABLES LIKE 'section_descriptions'";
    $tableExists = $conn->query($tableCheckSql)->rowCount() > 0;
    
    if (!$tableExists) {
        // Create the section_descriptions table if it doesn't exist
        $createTableSql = "CREATE TABLE section_descriptions (
            page_section VARCHAR(50) NOT NULL PRIMARY KEY COMMENT 'Identifier for the page section (e.g., delegate_passes)',
            description TEXT NULL COMMENT 'Custom description text for the section',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'When this record was created',
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'When this record was last updated'
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Stores descriptions for registration form sections'";
        
        $conn->exec($createTableSql);
        
        // Check if delegate_description column exists in frontend_display_config
        $columnCheckSql = "SHOW COLUMNS FROM frontend_display_config LIKE 'delegate_description'";
        $columnExists = $conn->query($columnCheckSql)->rowCount() > 0;
        
        if ($columnExists) {
            // Migrate existing descriptions from frontend_display_config
            $migrateDelegatesSql = "INSERT INTO section_descriptions (page_section, description)
                SELECT DISTINCT page_section, delegate_description 
                FROM frontend_display_config 
                WHERE page_section = 'delegate_passes' AND delegate_description IS NOT NULL
                LIMIT 1";
            $conn->exec($migrateDelegatesSql);
            
            $migrateTableSql = "INSERT INTO section_descriptions (page_section, description)
                SELECT DISTINCT page_section, table_description 
                FROM frontend_display_config 
                WHERE page_section = 'table_presentations' AND table_description IS NOT NULL
                LIMIT 1";
            $conn->exec($migrateTableSql);
        }
        
        // Insert default descriptions
        $insertDefaultsSql = "INSERT IGNORE INTO section_descriptions (page_section, description) VALUES
            ('delegate_passes', 'Choose the number of delegate passes'),
            ('table_presentations', 'Showcase your programs and partnerships'),
            ('sponsorship', 'Select your sponsorship options'),
            ('other_sponsorship', 'Select additional sponsorship options')";
        $conn->exec($insertDefaultsSql);
        
        // Table now exists
        $tableExists = true;
    }
    
    // Now get descriptions from the table
    if ($tableExists) {
        $sectionDescSql = "SELECT page_section, description FROM section_descriptions WHERE page_section IN ('delegate_passes', 'table_presentations', 'sponsorship', 'other_sponsorship')";
        $sectionDescStmt = $conn->prepare($sectionDescSql);
        $sectionDescStmt->execute();
        $sectionDescriptions = $sectionDescStmt->fetchAll(PDO::FETCH_KEY_PAIR);
    } else {
        // Fallback to get descriptions from frontend_display_config (should not happen now)
        $legacyDescSql = "SELECT DISTINCT page_section, delegate_description, table_description FROM frontend_display_config WHERE page_section IN ('delegate_passes', 'table_presentations') LIMIT 1";
        $legacyDescStmt = $conn->prepare($legacyDescSql);
        $legacyDescStmt->execute();
        $legacyDesc = $legacyDescStmt->fetch(PDO::FETCH_ASSOC);
        
        if ($legacyDesc) {
            if (!empty($legacyDesc['delegate_description'])) {
                $sectionDescriptions['delegate_passes'] = $legacyDesc['delegate_description'];
            }
            if (!empty($legacyDesc['table_description'])) {
                $sectionDescriptions['table_presentations'] = $legacyDesc['table_description'];
            }
        }
    }
} catch (Exception $e) {
    // Silently handle any errors - we'll use defaults if needed
}

// Set descriptions for each section
$delegateDescription = $sectionDescriptions['delegate_passes'] ?? 'Choose the number of delegate passes';
$tableDescription = $sectionDescriptions['table_presentations'] ?? 'Showcase your programs and partnerships';
$sponsorshipDescription = $sectionDescriptions['sponsorship'] ?? 'Select your sponsorship options';
$otherSponsorshipDescription = $sectionDescriptions['other_sponsorship'] ?? 'Select additional sponsorship options';

// Check if showing all categories (NULL value means show all)
$showAllDelegateCategories = in_array(null, $delegateConfig);
$showAllTableCategories = in_array(null, $tableConfig);
$showAllSponsorshipCategories = in_array(null, $sponsorshipConfig);
$showAllOtherSponsorshipCategories = in_array(null, $otherSponsorshipConfig);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delegate Page Configuration - XChange Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>
    
    <div class="admin-content">
        <div class="page-header">
            <h1>Delegate Page Configuration</h1>
            <p>Configure which product categories are displayed on the frontend registration form</p>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?> mb-4">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <!-- Configuration Sections - Grid Layout -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-bottom: 2rem;">
            <!-- Delegate Passes Configuration -->
            <div style="background: white; border-radius: 12px; box-shadow: var(--shadow); overflow: hidden;">
                <div style="padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e9ecef;">
                    <h2 style="margin: 0 0 0.5rem 0; color: #2c3e50; font-size: 1.25rem; font-weight: 600;">🎓 Delegate Passes</h2>
                    <p style="margin: 0; color: #6c757d; font-size: 0.9rem;">Configure categories for delegate passes section</p>
                </div>
                
                <form method="POST" style="padding: 1.5rem;">
                    <input type="hidden" name="action" value="update_delegate_config">
                    
                    <!-- Section Description -->
                    <div style="margin-bottom: 1.5rem;">
                        <label style="display: block; margin-bottom: 0.5rem; font-weight: 500; color: #495057;">Section Description:</label>
                        <textarea name="delegate_description" rows="2" style="width: 100%; padding: 0.75rem; border: 1px solid #e9ecef; border-radius: 4px; font-size: 0.9rem; resize: vertical;" placeholder="Enter description for delegate passes section"><?php echo htmlspecialchars($delegateDescription ?? 'Choose the number of delegate passes'); ?></textarea>
                        <small style="color: #6c757d; font-size: 0.8rem;">This text appears below the "Delegate Passes" title on the registration form.</small>
                    </div>

                    <div style="margin-bottom: 1.5rem;">
                        <div style="margin-bottom: 1rem;">
                            <label style="display: flex; align-items: center; margin-bottom: 0.75rem; cursor: pointer; font-weight: 500;">
                                <input type="radio" name="delegate_display_mode" value="all" 
                                       <?php echo $showAllDelegateCategories ? 'checked' : ''; ?>
                                       onchange="toggleCategorySelection('delegate')" style="margin-right: 0.5rem; transform: scale(1.1);">
                                <span style="color: #495057;">Show all categories</span>
                            </label>
                            <label style="display: flex; align-items: center; margin-bottom: 0.75rem; cursor: pointer; font-weight: 500;">
                                <input type="radio" name="delegate_display_mode" value="selected" 
                                       <?php echo !$showAllDelegateCategories ? 'checked' : ''; ?>
                                       onchange="toggleCategorySelection('delegate')" style="margin-right: 0.5rem; transform: scale(1.1);">
                                <span style="color: #495057;">Show selected only</span>
                            </label>
                        </div>
                        
                        <div id="delegate-category-list" style="display: <?php echo $showAllDelegateCategories ? 'none' : 'block'; ?>; background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 1rem; margin-top: 1rem;">
                            <h4 style="margin: 0 0 1rem 0; color: #495057; font-size: 1rem; font-weight: 600;">Select Categories:</h4>
                            <?php foreach ($allCategories as $category): ?>
                                <label style="display: flex; align-items: flex-start; margin-bottom: 1rem; cursor: pointer; padding: 0.75rem; background: white; border: 1px solid #e9ecef; border-radius: 4px; transition: all 0.2s ease;">
                                    <input type="checkbox" name="delegate_categories[]" 
                                           value="<?php echo $category['id']; ?>"
                                           <?php echo in_array($category['id'], $delegateConfig) ? 'checked' : ''; ?>
                                           style="margin-right: 0.75rem; margin-top: 0.25rem; transform: scale(1.1);">
                                    <div style="flex: 1;">
                                        <strong style="display: block; color: #2c3e50; font-size: 0.9rem; margin-bottom: 0.25rem;"><?php echo htmlspecialchars($category['name']); ?></strong>
                                        <?php if ($category['description']): ?>
                                            <small style="display: block; color: #6c757d; font-size: 0.8rem; margin-bottom: 0.5rem; line-height: 1.4;"><?php echo htmlspecialchars($category['description']); ?></small>
                                        <?php endif; ?>
                                        <span class="badge <?php echo $category['is_active'] ? 'badge-success' : 'badge-secondary'; ?>" style="font-size: 0.7rem;">
                                            <?php echo $category['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div style="padding-top: 1rem; border-top: 1px solid #e9ecef;">
                        <button type="submit" class="btn btn-primary">Update Delegate Config</button>
                    </div>
                </form>
            </div>

            <!-- Table Presentations Configuration -->
            <div style="background: white; border-radius: 12px; box-shadow: var(--shadow); overflow: hidden;">
                <div style="padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e9ecef;">
                    <h2 style="margin: 0 0 0.5rem 0; color: #2c3e50; font-size: 1.25rem; font-weight: 600;">📋 Table Presentations</h2>
                    <p style="margin: 0; color: #6c757d; font-size: 0.9rem;">Configure categories for table presentations section</p>
                </div>
                
                <form method="POST" style="padding: 1.5rem;">
                    <input type="hidden" name="action" value="update_table_config">
                    
                    <!-- Section Description -->
                    <div style="margin-bottom: 1.5rem;">
                        <label style="display: block; margin-bottom: 0.5rem; font-weight: 500; color: #495057;">Section Description:</label>
                        <textarea name="table_description" rows="2" style="width: 100%; padding: 0.75rem; border: 1px solid #e9ecef; border-radius: 4px; font-size: 0.9rem; resize: vertical;" placeholder="Enter description for table presentations section"><?php echo htmlspecialchars($tableDescription ?? 'Showcase your programs and partnerships'); ?></textarea>
                        <small style="color: #6c757d; font-size: 0.8rem;">This text appears below the "Table-top Presentations" title on the registration form.</small>
                    </div>

                    <div style="margin-bottom: 1.5rem;">
                        <div style="margin-bottom: 1rem;">
                            <label style="display: flex; align-items: center; margin-bottom: 0.75rem; cursor: pointer; font-weight: 500;">
                                <input type="radio" name="table_display_mode" value="all" 
                                       <?php echo $showAllTableCategories ? 'checked' : ''; ?>
                                       onchange="toggleCategorySelection('table')" style="margin-right: 0.5rem; transform: scale(1.1);">
                                <span style="color: #495057;">Show all categories</span>
                            </label>
                            <label style="display: flex; align-items: center; margin-bottom: 0.75rem; cursor: pointer; font-weight: 500;">
                                <input type="radio" name="table_display_mode" value="selected" 
                                       <?php echo !$showAllTableCategories ? 'checked' : ''; ?>
                                       onchange="toggleCategorySelection('table')" style="margin-right: 0.5rem; transform: scale(1.1);">
                                <span style="color: #495057;">Show selected only</span>
                            </label>
                        </div>
                        
                        <div id="table-category-list" style="display: <?php echo $showAllTableCategories ? 'none' : 'block'; ?>; background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 1rem; margin-top: 1rem;">
                            <h4 style="margin: 0 0 1rem 0; color: #495057; font-size: 1rem; font-weight: 600;">Select Categories:</h4>
                            <?php foreach ($allCategories as $category): ?>
                                <label style="display: flex; align-items: flex-start; margin-bottom: 1rem; cursor: pointer; padding: 0.75rem; background: white; border: 1px solid #e9ecef; border-radius: 4px; transition: all 0.2s ease;">
                                    <input type="checkbox" name="table_categories[]" 
                                           value="<?php echo $category['id']; ?>"
                                           <?php echo in_array($category['id'], $tableConfig) ? 'checked' : ''; ?>
                                           style="margin-right: 0.75rem; margin-top: 0.25rem; transform: scale(1.1);">
                                    <div style="flex: 1;">
                                        <strong style="display: block; color: #2c3e50; font-size: 0.9rem; margin-bottom: 0.25rem;"><?php echo htmlspecialchars($category['name']); ?></strong>
                                        <?php if ($category['description']): ?>
                                            <small style="display: block; color: #6c757d; font-size: 0.8rem; margin-bottom: 0.5rem; line-height: 1.4;"><?php echo htmlspecialchars($category['description']); ?></small>
                                        <?php endif; ?>
                                        <span class="badge <?php echo $category['is_active'] ? 'badge-success' : 'badge-secondary'; ?>" style="font-size: 0.7rem;">
                                            <?php echo $category['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div style="padding-top: 1rem; border-top: 1px solid #e9ecef;">
                        <button type="submit" class="btn btn-primary">Update Table Config</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Second row of configuration sections -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-bottom: 2rem;">
            <!-- Sponsorship Configuration -->
            <div style="background: white; border-radius: 12px; box-shadow: var(--shadow); overflow: hidden;">
                <div style="padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e9ecef;">
                    <h2 style="margin: 0 0 0.5rem 0; color: #2c3e50; font-size: 1.25rem; font-weight: 600;">💼 Sponsorship</h2>
                    <p style="margin: 0; color: #6c757d; font-size: 0.9rem;">Configure categories for sponsorship section</p>
                </div>
                
                <form method="POST" style="padding: 1.5rem;">
                    <input type="hidden" name="action" value="update_sponsorship_config">
                    
                    <!-- Section Description -->
                    <div style="margin-bottom: 1.5rem;">
                        <label style="display: block; margin-bottom: 0.5rem; font-weight: 500; color: #495057;">Section Description:</label>
                        <textarea name="sponsorship_description" rows="2" style="width: 100%; padding: 0.75rem; border: 1px solid #e9ecef; border-radius: 4px; font-size: 0.9rem; resize: vertical;" placeholder="Enter description for sponsorship section"><?php echo htmlspecialchars($sponsorshipDescription ?? 'Select your sponsorship options'); ?></textarea>
                        <small style="color: #6c757d; font-size: 0.8rem;">This text appears below the "Sponsorship" title on the registration form.</small>
                    </div>

                    <div style="margin-bottom: 1.5rem;">
                        <div style="margin-bottom: 1rem;">
                            <label style="display: flex; align-items: center; margin-bottom: 0.75rem; cursor: pointer; font-weight: 500;">
                                <input type="radio" name="sponsorship_display_mode" value="all" 
                                       <?php echo $showAllSponsorshipCategories ? 'checked' : ''; ?>
                                       onchange="toggleCategorySelection('sponsorship')" style="margin-right: 0.5rem; transform: scale(1.1);">
                                <span style="color: #495057;">Show all categories</span>
                            </label>
                            <label style="display: flex; align-items: center; margin-bottom: 0.75rem; cursor: pointer; font-weight: 500;">
                                <input type="radio" name="sponsorship_display_mode" value="selected" 
                                       <?php echo !$showAllSponsorshipCategories ? 'checked' : ''; ?>
                                       onchange="toggleCategorySelection('sponsorship')" style="margin-right: 0.5rem; transform: scale(1.1);">
                                <span style="color: #495057;">Show selected only</span>
                            </label>
                        </div>
                        
                        <div id="sponsorship-category-list" style="display: <?php echo $showAllSponsorshipCategories ? 'none' : 'block'; ?>; background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 1rem; margin-top: 1rem;">
                            <h4 style="margin: 0 0 1rem 0; color: #495057; font-size: 1rem; font-weight: 600;">Select Categories:</h4>
                            <?php foreach ($allCategories as $category): ?>
                                <label style="display: flex; align-items: flex-start; margin-bottom: 1rem; cursor: pointer; padding: 0.75rem; background: white; border: 1px solid #e9ecef; border-radius: 4px; transition: all 0.2s ease;">
                                    <input type="checkbox" name="sponsorship_categories[]" 
                                           value="<?php echo $category['id']; ?>"
                                           <?php echo in_array($category['id'], $sponsorshipConfig) ? 'checked' : ''; ?>
                                           style="margin-right: 0.75rem; margin-top: 0.25rem; transform: scale(1.1);">
                                    <div style="flex: 1;">
                                        <strong style="display: block; color: #2c3e50; font-size: 0.9rem; margin-bottom: 0.25rem;"><?php echo htmlspecialchars($category['name']); ?></strong>
                                        <?php if ($category['description']): ?>
                                            <small style="display: block; color: #6c757d; font-size: 0.8rem; margin-bottom: 0.5rem; line-height: 1.4;"><?php echo htmlspecialchars($category['description']); ?></small>
                                        <?php endif; ?>
                                        <span class="badge <?php echo $category['is_active'] ? 'badge-success' : 'badge-secondary'; ?>" style="font-size: 0.7rem;">
                                            <?php echo $category['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div style="padding-top: 1rem; border-top: 1px solid #e9ecef;">
                        <button type="submit" class="btn btn-primary">Update Sponsorship Config</button>
                    </div>
                </form>
            </div>

            <!-- Other Sponsorship Configuration -->
            <div style="background: white; border-radius: 12px; box-shadow: var(--shadow); overflow: hidden;">
                <div style="padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e9ecef;">
                    <h2 style="margin: 0 0 0.5rem 0; color: #2c3e50; font-size: 1.25rem; font-weight: 600;">🏆 Other Sponsorship</h2>
                    <p style="margin: 0; color: #6c757d; font-size: 0.9rem;">Configure categories for other sponsorship section</p>
                </div>
                
                <form method="POST" style="padding: 1.5rem;">
                    <input type="hidden" name="action" value="update_other_sponsorship_config">
                    
                    <!-- Section Description -->
                    <div style="margin-bottom: 1.5rem;">
                        <label style="display: block; margin-bottom: 0.5rem; font-weight: 500; color: #495057;">Section Description:</label>
                        <textarea name="other_sponsorship_description" rows="2" style="width: 100%; padding: 0.75rem; border: 1px solid #e9ecef; border-radius: 4px; font-size: 0.9rem; resize: vertical;" placeholder="Enter description for other sponsorship section"><?php echo htmlspecialchars($otherSponsorshipDescription ?? 'Select additional sponsorship options'); ?></textarea>
                        <small style="color: #6c757d; font-size: 0.8rem;">This text appears below the "Other Sponsorship" title on the registration form.</small>
                    </div>

                    <div style="margin-bottom: 1.5rem;">
                        <div style="margin-bottom: 1rem;">
                            <label style="display: flex; align-items: center; margin-bottom: 0.75rem; cursor: pointer; font-weight: 500;">
                                <input type="radio" name="other_sponsorship_display_mode" value="all" 
                                       <?php echo $showAllOtherSponsorshipCategories ? 'checked' : ''; ?>
                                       onchange="toggleCategorySelection('other_sponsorship')" style="margin-right: 0.5rem; transform: scale(1.1);">
                                <span style="color: #495057;">Show all categories</span>
                            </label>
                            <label style="display: flex; align-items: center; margin-bottom: 0.75rem; cursor: pointer; font-weight: 500;">
                                <input type="radio" name="other_sponsorship_display_mode" value="selected" 
                                       <?php echo !$showAllOtherSponsorshipCategories ? 'checked' : ''; ?>
                                       onchange="toggleCategorySelection('other_sponsorship')" style="margin-right: 0.5rem; transform: scale(1.1);">
                                <span style="color: #495057;">Show selected only</span>
                            </label>
                        </div>
                        
                        <div id="other_sponsorship-category-list" style="display: <?php echo $showAllOtherSponsorshipCategories ? 'none' : 'block'; ?>; background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 1rem; margin-top: 1rem;">
                            <h4 style="margin: 0 0 1rem 0; color: #495057; font-size: 1rem; font-weight: 600;">Select Categories:</h4>
                            <?php foreach ($allCategories as $category): ?>
                                <label style="display: flex; align-items: flex-start; margin-bottom: 1rem; cursor: pointer; padding: 0.75rem; background: white; border: 1px solid #e9ecef; border-radius: 4px; transition: all 0.2s ease;">
                                    <input type="checkbox" name="other_sponsorship_categories[]" 
                                           value="<?php echo $category['id']; ?>"
                                           <?php echo in_array($category['id'], $otherSponsorshipConfig) ? 'checked' : ''; ?>
                                           style="margin-right: 0.75rem; margin-top: 0.25rem; transform: scale(1.1);">
                                    <div style="flex: 1;">
                                        <strong style="display: block; color: #2c3e50; font-size: 0.9rem; margin-bottom: 0.25rem;"><?php echo htmlspecialchars($category['name']); ?></strong>
                                        <?php if ($category['description']): ?>
                                            <small style="display: block; color: #6c757d; font-size: 0.8rem; margin-bottom: 0.5rem; line-height: 1.4;"><?php echo htmlspecialchars($category['description']); ?></small>
                                        <?php endif; ?>
                                        <span class="badge <?php echo $category['is_active'] ? 'badge-success' : 'badge-secondary'; ?>" style="font-size: 0.7rem;">
                                            <?php echo $category['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div style="padding-top: 1rem; border-top: 1px solid #e9ecef;">
                        <button type="submit" class="btn btn-primary">Update Other Sponsorship Config</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Preview Section -->
        <div style="background: white; border-radius: 12px; box-shadow: var(--shadow); padding: 1.5rem; margin-top: 2rem;">
            <h2 style="margin: 0 0 0.5rem 0; color: #2c3e50; font-size: 1.25rem; font-weight: 600;">👁️ Frontend Preview</h2>
            <p style="margin: 0 0 1.5rem 0; color: #6c757d; font-size: 0.9rem;">This is how the selected categories will appear on the registration form:</p>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-bottom: 2rem;">
                <div style="background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 1rem;">
                    <h3 style="margin: 0 0 1rem 0; color: #495057; font-size: 1rem; font-weight: 600;">🎓 Delegate Passes</h3>
                    <div style="display: flex; flex-direction: column; gap: 0.5rem;">
                        <?php if ($showAllDelegateCategories): ?>
                            <div style="color: #6c757d; font-style: italic; font-size: 0.9rem; padding: 0.5rem; text-align: center;">All product categories will be displayed</div>
                            <?php foreach ($allCategories as $category): ?>
                                <?php if ($category['is_active']): ?>
                                    <div style="background: white; border: 1px solid #dee2e6; border-radius: 4px; padding: 0.5rem 0.75rem; color: #495057; font-size: 0.9rem;"><?php echo htmlspecialchars($category['name']); ?></div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <?php 
                            $selectedDelegateCategories = array_filter($allCategories, function($cat) use ($delegateConfig) {
                                return in_array($cat['id'], $delegateConfig) && $cat['is_active'];
                            });
                            ?>
                            <?php if (empty($selectedDelegateCategories)): ?>
                                <div style="color: #6c757d; font-style: italic; font-size: 0.9rem; padding: 0.5rem; text-align: center;">No categories selected</div>
                            <?php else: ?>
                                <?php foreach ($selectedDelegateCategories as $category): ?>
                                    <div style="background: white; border: 1px solid #dee2e6; border-radius: 4px; padding: 0.5rem 0.75rem; color: #495057; font-size: 0.9rem;"><?php echo htmlspecialchars($category['name']); ?></div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div style="background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 1rem;">
                    <h3 style="margin: 0 0 1rem 0; color: #495057; font-size: 1rem; font-weight: 600;">📋 Table Presentations</h3>
                    <div style="display: flex; flex-direction: column; gap: 0.5rem;">
                        <?php if ($showAllTableCategories): ?>
                            <div style="color: #6c757d; font-style: italic; font-size: 0.9rem; padding: 0.5rem; text-align: center;">All product categories will be displayed</div>
                            <?php foreach ($allCategories as $category): ?>
                                <?php if ($category['is_active']): ?>
                                    <div style="background: white; border: 1px solid #dee2e6; border-radius: 4px; padding: 0.5rem 0.75rem; color: #495057; font-size: 0.9rem;"><?php echo htmlspecialchars($category['name']); ?></div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <?php 
                            $selectedTableCategories = array_filter($allCategories, function($cat) use ($tableConfig) {
                                return in_array($cat['id'], $tableConfig) && $cat['is_active'];
                            });
                            ?>
                            <?php if (empty($selectedTableCategories)): ?>
                                <div style="color: #6c757d; font-style: italic; font-size: 0.9rem; padding: 0.5rem; text-align: center;">No categories selected</div>
                            <?php else: ?>
                                <?php foreach ($selectedTableCategories as $category): ?>
                                    <div style="background: white; border: 1px solid #dee2e6; border-radius: 4px; padding: 0.5rem 0.75rem; color: #495057; font-size: 0.9rem;"><?php echo htmlspecialchars($category['name']); ?></div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem;">
                <div style="background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 1rem;">
                    <h3 style="margin: 0 0 1rem 0; color: #495057; font-size: 1rem; font-weight: 600;">💼 Sponsorship</h3>
                    <div style="display: flex; flex-direction: column; gap: 0.5rem;">
                        <?php if ($showAllSponsorshipCategories): ?>
                            <div style="color: #6c757d; font-style: italic; font-size: 0.9rem; padding: 0.5rem; text-align: center;">All product categories will be displayed</div>
                            <?php foreach ($allCategories as $category): ?>
                                <?php if ($category['is_active']): ?>
                                    <div style="background: white; border: 1px solid #dee2e6; border-radius: 4px; padding: 0.5rem 0.75rem; color: #495057; font-size: 0.9rem;"><?php echo htmlspecialchars($category['name']); ?></div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <?php 
                            $selectedSponsorshipCategories = array_filter($allCategories, function($cat) use ($sponsorshipConfig) {
                                return in_array($cat['id'], $sponsorshipConfig) && $cat['is_active'];
                            });
                            ?>
                            <?php if (empty($selectedSponsorshipCategories)): ?>
                                <div style="color: #6c757d; font-style: italic; font-size: 0.9rem; padding: 0.5rem; text-align: center;">No categories selected</div>
                            <?php else: ?>
                                <?php foreach ($selectedSponsorshipCategories as $category): ?>
                                    <div style="background: white; border: 1px solid #dee2e6; border-radius: 4px; padding: 0.5rem 0.75rem; color: #495057; font-size: 0.9rem;"><?php echo htmlspecialchars($category['name']); ?></div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div style="background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 1rem;">
                    <h3 style="margin: 0 0 1rem 0; color: #495057; font-size: 1rem; font-weight: 600;">🏆 Other Sponsorship</h3>
                    <div style="display: flex; flex-direction: column; gap: 0.5rem;">
                        <?php if ($showAllOtherSponsorshipCategories): ?>
                            <div style="color: #6c757d; font-style: italic; font-size: 0.9rem; padding: 0.5rem; text-align: center;">All product categories will be displayed</div>
                            <?php foreach ($allCategories as $category): ?>
                                <?php if ($category['is_active']): ?>
                                    <div style="background: white; border: 1px solid #dee2e6; border-radius: 4px; padding: 0.5rem 0.75rem; color: #495057; font-size: 0.9rem;"><?php echo htmlspecialchars($category['name']); ?></div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <?php 
                            $selectedOtherSponsorshipCategories = array_filter($allCategories, function($cat) use ($otherSponsorshipConfig) {
                                return in_array($cat['id'], $otherSponsorshipConfig) && $cat['is_active'];
                            });
                            ?>
                            <?php if (empty($selectedOtherSponsorshipCategories)): ?>
                                <div style="color: #6c757d; font-style: italic; font-size: 0.9rem; padding: 0.5rem; text-align: center;">No categories selected</div>
                            <?php else: ?>
                                <?php foreach ($selectedOtherSponsorshipCategories as $category): ?>
                                    <div style="background: white; border: 1px solid #dee2e6; border-radius: 4px; padding: 0.5rem 0.75rem; color: #495057; font-size: 0.9rem;"><?php echo htmlspecialchars($category['name']); ?></div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function toggleCategorySelection(section) {
            const showAllRadio = document.querySelector(`input[name="${section}_display_mode"][value="all"]`);
            const categoryList = document.getElementById(`${section}-category-list`);
            
            if (showAllRadio.checked) {
                categoryList.style.display = 'none';
            } else {
                categoryList.style.display = 'block';
            }
        }
        
        // Initialize all category selection toggles
        document.addEventListener('DOMContentLoaded', function() {
            const sections = ['delegate', 'table', 'sponsorship', 'other_sponsorship'];
            sections.forEach(section => {
                const radioButtons = document.querySelectorAll(`input[name="${section}_display_mode"]`);
                if (radioButtons.length > 0) {
                    radioButtons.forEach(radio => {
                        radio.addEventListener('change', function() {
                            toggleCategorySelection(section);
                        });
                    });
                }
            });
        });
    </script>
</body>
</html>
