<?php
/**
 * Category Colors Utility Functions
 * 
 * Provides easy access to category colors throughout the StyleScore system
 */

/**
 * Get category colors by category name or ID
 * 
 * @param PDO $pdo Database connection
 * @param mixed $identifier Category name (string) or ID (int)
 * @param int $event_id Event ID (required if using category name)
 * @return array|null Category colors or null if not found
 */
function getCategoryColors($pdo, $identifier, $event_id = null) {
    try {
        if (is_numeric($identifier)) {
            // Search by category ID
            $stmt = $pdo->prepare("SELECT colors, category_name FROM event_categories WHERE id = ?");
            $stmt->execute([$identifier]);
        } else {
            // Search by category name
            if (!$event_id) {
                throw new Exception("Event ID required when searching by category name");
            }
            $stmt = $pdo->prepare("SELECT colors, category_name FROM event_categories WHERE category_name = ? AND event_id = ?");
            $stmt->execute([$identifier, $event_id]);
        }
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$result) {
            return null;
        }
        
        $colors = json_decode($result['colors'] ?? '{}', true);
        if (empty($colors)) {
            // Generate colors if not exist
            include_once '../admin/event_categories.php';
            $colors = generateCategoryColor($result['category_name']);
        }
        
        return $colors;
    } catch (Exception $e) {
        error_log("Error getting category colors: " . $e->getMessage());
        return null;
    }
}

/**
 * Get all category colors for an event
 * 
 * @param PDO $pdo Database connection
 * @param int $event_id Event ID
 * @return array Associative array [category_name => colors]
 */
function getAllCategoryColors($pdo, $event_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT id, category_name, colors 
            FROM event_categories 
            WHERE event_id = ? 
            ORDER BY category_name
        ");
        $stmt->execute([$event_id]);
        $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $colors_map = [];
        foreach ($categories as $category) {
            $colors = json_decode($category['colors'] ?? '{}', true);
            if (empty($colors)) {
                // Generate colors if not exist
                include_once '../admin/event_categories.php';
                $colors = generateCategoryColor($category['category_name']);
                
                // Update database
                $update_stmt = $pdo->prepare("UPDATE event_categories SET colors = ? WHERE id = ?");
                $update_stmt->execute([json_encode($colors), $category['id']]);
            }
            
            $colors_map[$category['category_name']] = $colors;
        }
        
        return $colors_map;
    } catch (Exception $e) {
        error_log("Error getting all category colors: " . $e->getMessage());
        return [];
    }
}

/**
 * Generate CSS for category colors
 * 
 * @param array $category_colors Array of category colors from getAllCategoryColors()
 * @return string CSS styles
 */
function generateCategoryColorsCSS($category_colors) {
    $css = "/* Dynamic Category Colors */\n";
    
    foreach ($category_colors as $category_name => $colors) {
        $css_class = $colors['css_class'] ?? ('category-' . slugify($category_name));
        $bg_color = $colors['background-color'] ?? '#6c757d';
        $text_color = $colors['color'] ?? '#ffffff';
        $border_color = $colors['border-color'] ?? '#495057';
        $bg_light = $colors['background-light'] ?? '#e9ecef';
        
        $css .= ".{$css_class} {\n";
        $css .= "    background-color: {$bg_color} !important;\n";
        $css .= "    color: {$text_color} !important;\n";
        $css .= "    border-color: {$border_color} !important;\n";
        $css .= "}\n\n";
        
        $css .= ".{$css_class}-light {\n";
        $css .= "    background-color: {$bg_light} !important;\n";
        $css .= "    color: {$border_color} !important;\n";
        $css .= "    border-color: {$bg_color} !important;\n";
        $css .= "}\n\n";
        
        $css .= ".{$css_class}-border {\n";
        $css .= "    border: 2px solid {$bg_color} !important;\n";
        $css .= "}\n\n";
        
        $css .= ".{$css_class}-text {\n";
        $css .= "    color: {$bg_color} !important;\n";
        $css .= "}\n\n";
    }
    
    return $css;
}

/**
 * Get category color style attribute
 * 
 * @param array $colors Category colors array
 * @param string $variant 'default', 'light', 'border', 'text'
 * @return string CSS style attribute
 */
function getCategoryColorStyle($colors, $variant = 'default') {
    if (empty($colors)) {
        return '';
    }
    
    switch ($variant) {
        case 'light':
            return sprintf(
                'background-color: %s; color: %s; border-color: %s;',
                $colors['background-light'] ?? '#e9ecef',
                $colors['border-color'] ?? '#495057',
                $colors['background-color'] ?? '#6c757d'
            );
            
        case 'border':
            return sprintf(
                'border-color: %s;',
                $colors['background-color'] ?? '#6c757d'
            );
            
        case 'text':
            return sprintf(
                'color: %s;',
                $colors['background-color'] ?? '#6c757d'
            );
            
        case 'default':
        default:
            return sprintf(
                'background-color: %s; color: %s; border-color: %s;',
                $colors['background-color'] ?? '#6c757d',
                $colors['color'] ?? '#ffffff',
                $colors['border-color'] ?? '#495057'
            );
    }
}

/**
 * Create category badge HTML with colors
 * 
 * @param string $category_name Category name to display
 * @param array $colors Category colors (optional, will fetch if not provided)
 * @param PDO $pdo Database connection (required if colors not provided)
 * @param int $event_id Event ID (required if colors not provided)
 * @param string $size Badge size: 'sm', 'md', 'lg'
 * @return string HTML badge element
 */
function createCategoryBadge($category_name, $colors = null, $pdo = null, $event_id = null, $size = 'md') {
    // Get colors if not provided
    if (empty($colors) && $pdo && $event_id) {
        $colors = getCategoryColors($pdo, $category_name, $event_id);
    }
    
    if (empty($colors)) {
        // Fallback to default badge
        return '<span class="badge bg-secondary">' . htmlspecialchars($category_name) . '</span>';
    }
    
    $size_classes = [
        'sm' => 'badge-sm',
        'md' => '',
        'lg' => 'badge-lg'
    ];
    
    $size_class = $size_classes[$size] ?? '';
    $style = getCategoryColorStyle($colors);
    
    return sprintf(
        '<span class="badge %s" style="%s">%s</span>',
        $size_class,
        $style,
        htmlspecialchars($category_name)
    );
}

/**
 * Create category color dot/indicator
 * 
 * @param array $colors Category colors
 * @param int $size Size in pixels
 * @return string HTML color dot element
 */
function createCategoryColorDot($colors, $size = 16) {
    if (empty($colors)) {
        return '';
    }
    
    $bg_color = $colors['background-color'] ?? '#6c757d';
    $border_color = $colors['border-color'] ?? '#495057';
    
    return sprintf(
        '<span class="category-color-dot" style="
            display: inline-block;
            width: %dpx;
            height: %dpx;
            background-color: %s;
            border: 1px solid %s;
            border-radius: 50%%;
            margin-right: 4px;
        "></span>',
        $size, $size, $bg_color, $border_color
    );
}

/**
 * Helper function to create slug (if not already defined)
 */
if (!function_exists('slugify')) {
    function slugify($text) {
        $text = preg_replace('/[^a-zA-Z0-9]+/', '-', $text);
        return strtolower(trim($text, '-'));
    }
}

/**
 * Example usage functions for common scenarios
 */

/**
 * Example: Get category colors for participant display
 */
function getParticipantCategoryColors($pdo, $participant_category, $event_id) {
    return getCategoryColors($pdo, $participant_category, $event_id);
}

/**
 * Example: Generate category-specific CSS for results tables
 */
function generateResultsTableCSS($pdo, $event_id) {
    $category_colors = getAllCategoryColors($pdo, $event_id);
    return generateCategoryColorsCSS($category_colors);
}

/**
 * Example: Create category legend for dashboards
 */
function createCategoryLegend($pdo, $event_id) {
    $category_colors = getAllCategoryColors($pdo, $event_id);
    
    $html = '<div class="category-legend">';
    $html .= '<h6><i class="fas fa-palette me-2"></i>Categories</h6>';
    $html .= '<div class="d-flex flex-wrap gap-2">';
    
    foreach ($category_colors as $category_name => $colors) {
        $html .= createCategoryBadge($category_name, $colors);
    }
    
    $html .= '</div></div>';
    
    return $html;
}
?>
