<?php
/**
 * Scoring Layout Configuration Helper
 * Provides functions to manage and apply scoring layout configurations
 */

class ScoringLayoutConfig {
    
    /**
     * Get effective scoring layout configuration for a specific heat
     * Combines event-level and heat-level configurations with proper inheritance
     */
    public static function getEffectiveConfig($pdo, $event_id, $heat_number = null) {
        // Default configuration
        $defaultConfig = [
            'cards' => [
                'criteriaInputGrid' => ['enabled' => true],
                'finalCalculatedScore' => ['enabled' => true],
                'figuresCard' => ['enabled' => true],
                'latestScores' => ['enabled' => true],
                'otherHeatScores' => ['enabled' => true],
                'diversityValidation' => ['enabled' => true],
                'figureHistory' => ['enabled' => true],
                'formatInfo' => ['enabled' => false],
            ],
            'layout' => [
                'compactMode' => false,
                'hideEmptyCards' => true
            ]
        ];
        
        // Get configuration from scoring_layout_configs table
        $config = $defaultConfig;
        if ($event_id) {
            // First try to get heat-specific configuration
            if ($heat_number !== null) {
                $stmt = $pdo->prepare("SELECT configuration FROM scoring_layout_configs WHERE event_id = ? AND heat_number = ?");
                $stmt->execute([$event_id, $heat_number]);
                $configJson = $stmt->fetchColumn();
                
                if ($configJson) {
                    $decoded = json_decode($configJson, true);
                    if ($decoded && is_array($decoded)) {
                        return array_replace_recursive($defaultConfig, $decoded);
                    }
                }
            }
            
            // If no heat-specific config found, get event-level configuration (heat_number = NULL)
            $stmt = $pdo->prepare("SELECT configuration FROM scoring_layout_configs WHERE event_id = ? AND heat_number IS NULL");
            $stmt->execute([$event_id]);
            $configJson = $stmt->fetchColumn();
            
            if ($configJson) {
                $decoded = json_decode($configJson, true);
                if ($decoded && is_array($decoded)) {
                    return array_replace_recursive($defaultConfig, $decoded);
                }
            }
        }
        
        return $config;
    }
    
    /**
     * Check if a specific component should be visible
     */
    public static function isComponentEnabled($config, $componentKey) {
        return $config['cards'][$componentKey]['enabled'] ?? false;
    }
    
    /**
     * Get layout mode settings
     */
    public static function getLayoutMode($config) {
        return [
            'compactMode' => $config['layout']['compactMode'] ?? false,
            'hideEmptyCards' => $config['layout']['hideEmptyCards'] ?? true
        ];
    }
    
    /**
     * Generate CSS classes based on layout configuration
     */
    public static function getLayoutClasses($config) {
        $classes = [];
        
        $layout = self::getLayoutMode($config);
        
        if ($layout['compactMode']) {
            $classes[] = 'layout-compact';
        }
        
        if ($layout['hideEmptyCards']) {
            $classes[] = 'hide-empty-cards';
        }
        
        return implode(' ', $classes);
    }
    
    /**
     * Get all available component definitions
     */
    public static function getAvailableComponents() {
        return [
            'criteriaInputGrid' => [
                'title' => 'Criteria Scoring Grid',
                'description' => 'Individual criteria input fields with sliders',
                'selector' => '.criteria-input-grid',
                'fallback_selector' => '#criteria-input-grid'
            ],
            'finalCalculatedScore' => [
                'title' => 'Final Score Display', 
                'description' => 'Calculated final score display',
                'selector' => '.final-calculated-score',
                'fallback_selector' => '#final-calculated-score'
            ],
            'figuresCard' => [
                'title' => 'Figures Selection Card',
                'description' => 'Figure selection chips and controls',
                'selector' => '.figures-card',
                'fallback_selector' => '#figures-card'
            ],
            'latestScores' => [
                'title' => 'Latest Scores Table',
                'description' => 'Recent scores with edit functionality',
                'selector' => '.latest-scores',
                'fallback_selector' => '#score-history-table'
            ],
            'otherHeatScores' => [
                'title' => 'Other Judges Scores',
                'description' => 'Scores from other judges',
                'selector' => '.other-heat-scores',
                'fallback_selector' => '#otherHeatScores'
            ],
            'diversityValidation' => [
                'title' => 'Diversity Validation',
                'description' => 'Figure diversity rule checking',
                'selector' => '.diversity-validation',
                'fallback_selector' => '#diversity-validation-panel'
            ],
            'figureHistory' => [
                'title' => 'Figure History',
                'description' => 'Previous figure selections',
                'selector' => '.figure-history',
                'fallback_selector' => '#figureHistoryCard'
            ],
            'formatInfo' => [
                'title' => 'Format Information',
                'description' => 'Scoring format details',
                'selector' => '.format-info',
                'fallback_selector' => '#formatInfoCard'
            ]
        ];
    }
    
    /**
     * Generate JavaScript for applying layout configuration
     */
    public static function generateApplyScript($config) {
        $components = self::getAvailableComponents();
        $js = "// Apply scoring layout configuration\n";
        $js .= "document.addEventListener('DOMContentLoaded', function() {\n";
        
        foreach ($components as $key => $component) {
            $enabled = self::isComponentEnabled($config, $key);
            $selector = $component['selector'];
            $fallbackSelector = $component['fallback_selector'];
            
            if (!$enabled) {
                $js .= "    // Hide {$component['title']}\n";
                $js .= "    let {$key}Element = document.querySelector('{$selector}');\n";
                $js .= "    if (!{$key}Element) {$key}Element = document.querySelector('{$fallbackSelector}');\n";
                $js .= "    if ({$key}Element) {\n";
                $js .= "        {$key}Element.style.display = 'none';\n";
                $js .= "        {$key}Element.classList.add('layout-hidden');\n";
                $js .= "    }\n\n";
            }
        }
        
        $layout = self::getLayoutMode($config);
        if ($layout['compactMode']) {
            $js .= "    // Apply compact mode\n";
            $js .= "    document.body.classList.add('layout-compact');\n";
            $js .= "    document.querySelectorAll('.card').forEach(card => {\n";
            $js .= "        card.classList.add('card-compact');\n";
            $js .= "    });\n\n";
        }
        
        if ($layout['hideEmptyCards']) {
            $js .= "    // Hide empty cards\n";
            $js .= "    setTimeout(() => {\n";
            $js .= "        document.querySelectorAll('.card').forEach(card => {\n";
            $js .= "            const cardBody = card.querySelector('.card-body');\n";
            $js .= "            if (cardBody && cardBody.children.length === 0) {\n";
            $js .= "                card.style.display = 'none';\n";
            $js .= "                card.classList.add('layout-hidden-empty');\n";
            $js .= "            }\n";
            $js .= "        });\n";
            $js .= "    }, 100);\n\n";
        }
        
        $js .= "    console.log('Scoring layout configuration applied:', " . json_encode($config) . ");\n";
        $js .= "});\n";
        
        return $js;
    }
    
    /**
     * Generate CSS for layout modes
     */
    public static function generateLayoutCSS($config) {
        $css = "/* Scoring Layout Configuration Styles */\n";
        
        $layout = self::getLayoutMode($config);
        
        if ($layout['compactMode']) {
            $css .= ".layout-compact .card { margin-bottom: 0.5rem !important; }\n";
            $css .= ".layout-compact .card-body { padding: 0.75rem !important; }\n";
            $css .= ".layout-compact .card-header { padding: 0.5rem 0.75rem !important; }\n";
            $css .= ".card-compact { margin-bottom: 0.5rem !important; }\n";
            $css .= ".card-compact .card-body { padding: 0.75rem !important; }\n";
        }
        
        $css .= ".layout-hidden { display: none !important; }\n";
        $css .= ".layout-hidden-empty { display: none !important; }\n";
        
        return $css;
    }
}
?>