<?php
/**
 * Color Generator System
 * Generate all color variations from 1 root color
 */

class ColorGenerator 
{
    /**
     * Generate complete color palette from one root color
     */
    public static function generatePalette($rootColor) 
    {
        // Ensure color starts with #
        $rootColor = ltrim($rootColor, '#');
        if (strlen($rootColor) !== 6) {
            throw new Exception("Invalid color format. Use 6-digit hex color.");
        }
        
        // Convert hex to RGB
        $rgb = self::hexToRgb($rootColor);
        $hsl = self::rgbToHsl($rgb['r'], $rgb['g'], $rgb['b']);
        
        // Generate color variations
        $palette = [
            'root_color' => '#' . $rootColor,
            'primary_color' => '#' . $rootColor, // Original color
            'secondary_color' => self::generateSecondary($hsl),
            'accent_color' => self::generateAccent($hsl),
            'background_color' => self::generateBackground($hsl),
            'text_color' => self::generateTextColor($hsl),
            
            // Additional variations for advanced theming
            'light_variant' => self::generateLightVariant($hsl),
            'dark_variant' => self::generateDarkVariant($hsl),
            'muted_variant' => self::generateMutedVariant($hsl),
        ];
        
        return $palette;
    }
    
    /**
     * Generate secondary color (darker version of primary)
     */
    private static function generateSecondary($hsl) 
    {
        $newHsl = $hsl;
        $newHsl['l'] = max(0.1, $hsl['l'] - 0.15); // Make it darker
        $newHsl['s'] = min(1.0, $hsl['s'] + 0.05); // Slightly more saturated
        
        return self::hslToHex($newHsl['h'], $newHsl['s'], $newHsl['l']);
    }
    
    /**
     * Generate accent color (complementary or analogous)
     */
    private static function generateAccent($hsl) 
    {
        $newHsl = $hsl;
        
        // If primary is dark, make accent bright
        if ($hsl['l'] < 0.5) {
            $newHsl['h'] = fmod($hsl['h'] + 0.16, 1.0); // Shift hue
            $newHsl['l'] = min(0.9, $hsl['l'] + 0.3); // Much brighter
            $newHsl['s'] = max(0.6, $hsl['s']); // Good saturation
        } else {
            // If primary is bright, make accent darker but still vibrant
            $newHsl['h'] = fmod($hsl['h'] + 0.08, 1.0); // Small hue shift
            $newHsl['l'] = max(0.3, $hsl['l'] - 0.2); // Darker
            $newHsl['s'] = min(1.0, $hsl['s'] + 0.1); // More saturated
        }
        
        return self::hslToHex($newHsl['h'], $newHsl['s'], $newHsl['l']);
    }
    
    /**
     * Generate background color (very dark version)
     */
    private static function generateBackground($hsl) 
    {
        $newHsl = $hsl;
        $newHsl['l'] = 0.08; // Very dark
        $newHsl['s'] = min(0.3, $hsl['s']); // Low saturation
        
        return self::hslToHex($newHsl['h'], $newHsl['s'], $newHsl['l']);
    }
    
    /**
     * Generate text color (high contrast)
     */
    private static function generateTextColor($hsl) 
    {
        // Always use light text for dark themes
        return '#ffffff';
    }
    
    /**
     * Generate light variant
     */
    private static function generateLightVariant($hsl) 
    {
        $newHsl = $hsl;
        $newHsl['l'] = min(0.95, $hsl['l'] + 0.25);
        $newHsl['s'] = max(0.2, $hsl['s'] - 0.3);
        
        return self::hslToHex($newHsl['h'], $newHsl['s'], $newHsl['l']);
    }
    
    /**
     * Generate dark variant
     */
    private static function generateDarkVariant($hsl) 
    {
        $newHsl = $hsl;
        $newHsl['l'] = max(0.05, $hsl['l'] - 0.3);
        $newHsl['s'] = min(1.0, $hsl['s'] + 0.1);
        
        return self::hslToHex($newHsl['h'], $newHsl['s'], $newHsl['l']);
    }
    
    /**
     * Generate muted variant
     */
    private static function generateMutedVariant($hsl) 
    {
        $newHsl = $hsl;
        $newHsl['s'] = max(0.1, $hsl['s'] - 0.4); // Much less saturated
        $newHsl['l'] = 0.4; // Medium lightness
        
        return self::hslToHex($newHsl['h'], $newHsl['s'], $newHsl['l']);
    }
    
    /**
     * Convert hex color to RGB
     */
    private static function hexToRgb($hex) 
    {
        return [
            'r' => hexdec(substr($hex, 0, 2)) / 255,
            'g' => hexdec(substr($hex, 2, 2)) / 255,
            'b' => hexdec(substr($hex, 4, 2)) / 255
        ];
    }
    
    /**
     * Convert RGB to HSL
     */
    private static function rgbToHsl($r, $g, $b) 
    {
        $max = max($r, $g, $b);
        $min = min($r, $g, $b);
        $diff = $max - $min;
        
        // Lightness
        $l = ($max + $min) / 2;
        
        if ($diff == 0) {
            $h = $s = 0; // Achromatic
        } else {
            // Saturation
            $s = $l > 0.5 ? $diff / (2 - $max - $min) : $diff / ($max + $min);
            
            // Hue
            switch ($max) {
                case $r:
                    $h = (($g - $b) / $diff + ($g < $b ? 6 : 0)) / 6;
                    break;
                case $g:
                    $h = (($b - $r) / $diff + 2) / 6;
                    break;
                case $b:
                    $h = (($r - $g) / $diff + 4) / 6;
                    break;
            }
        }
        
        return ['h' => $h, 's' => $s, 'l' => $l];
    }
    
    /**
     * Convert HSL to hex color
     */
    private static function hslToHex($h, $s, $l) 
    {
        if ($s == 0) {
            $r = $g = $b = $l; // Achromatic
        } else {
            $hue2rgb = function($p, $q, $t) {
                if ($t < 0) $t += 1;
                if ($t > 1) $t -= 1;
                if ($t < 1/6) return $p + ($q - $p) * 6 * $t;
                if ($t < 1/2) return $q;
                if ($t < 2/3) return $p + ($q - $p) * (2/3 - $t) * 6;
                return $p;
            };
            
            $q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
            $p = 2 * $l - $q;
            $r = $hue2rgb($p, $q, $h + 1/3);
            $g = $hue2rgb($p, $q, $h);
            $b = $hue2rgb($p, $q, $h - 1/3);
        }
        
        $r = round($r * 255);
        $g = round($g * 255);
        $b = round($b * 255);
        
        return sprintf("#%02x%02x%02x", $r, $g, $b);
    }
    
    /**
     * Get predefined color schemes for quick selection
     */
    public static function getPresetColors() 
    {
        return [
            'emerald' => '#10b981',
            'blue' => '#3b82f6',
            'purple' => '#8b5cf6',
            'pink' => '#ec4899',
            'red' => '#ef4444',
            'orange' => '#f97316',
            'yellow' => '#eab308',
            'teal' => '#14b8a6',
            'indigo' => '#6366f1',
            'rose' => '#f43f5e',
            'amber' => '#f59e0b',
            'lime' => '#84cc16',
            'cyan' => '#06b6d4',
            'violet' => '#7c3aed',
            'fuchsia' => '#d946ef',
            'sky' => '#0ea5e9'
        ];
    }
    
    /**
     * Preview color palette
     */
    public static function previewPalette($rootColor) 
    {
        try {
            $palette = self::generatePalette($rootColor);
            
            $html = "<div style='font-family: Arial, sans-serif; max-width: 800px; margin: 20px auto;'>";
            $html .= "<h2 style='text-align: center; color: #333;'>Color Palette Preview</h2>";
            $html .= "<p style='text-align: center; color: #666;'>Root Color: <strong>{$palette['root_color']}</strong></p>";
            
            $html .= "<div style='display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0;'>";
            
            foreach ($palette as $name => $color) {
                if ($name === 'root_color') continue;
                
                $textColor = self::getContrastColor($color);
                $displayName = ucwords(str_replace('_', ' ', $name));
                
                $html .= "<div style='background: {$color}; color: {$textColor}; padding: 20px; border-radius: 8px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1);'>";
                $html .= "<strong>{$displayName}</strong><br>";
                $html .= "<code style='background: rgba(255,255,255,0.2); padding: 2px 6px; border-radius: 3px; font-size: 12px;'>{$color}</code>";
                $html .= "</div>";
            }
            
            $html .= "</div>";
            $html .= "</div>";
            
            return $html;
            
        } catch (Exception $e) {
            return "<div style='color: red; text-align: center; padding: 20px;'>Error: " . $e->getMessage() . "</div>";
        }
    }
    
    /**
     * Get contrast color (black or white) for readable text
     */
    private static function getContrastColor($hexColor) 
    {
        $hex = ltrim($hexColor, '#');
        $rgb = self::hexToRgb($hex);
        
        // Calculate relative luminance
        $luminance = 0.299 * $rgb['r'] + 0.587 * $rgb['g'] + 0.114 * $rgb['b'];
        
        return $luminance > 0.5 ? '#000000' : '#ffffff';
    }
}

// Demo usage
if (isset($_GET['demo'])) {
    $testColor = $_GET['color'] ?? '#10b981';
    echo ColorGenerator::previewPalette($testColor);
    exit;
}

// Test with different colors
if (isset($_GET['test'])) {
    echo "<h1>Color Generator Test</h1>";
    
    $testColors = ['#10b981', '#3b82f6', '#8b5cf6', '#ec4899', '#f97316'];
    
    foreach ($testColors as $color) {
        echo "<h3>Testing: $color</h3>";
        echo ColorGenerator::previewPalette($color);
        echo "<hr>";
    }
}
?>