<?php
use Picqer\Barcode\BarcodeGeneratorPNG;
use Spatie\Color\Color;
use Spatie\Color\Hex;
use Spatie\Color\Rgb;

if (!function_exists('feature_enabled')) {
    /**
     * Check if a feature flag is enabled
     *
     * @param string $key
     * @param int|null $userId
     * @return bool
     */
    function feature_enabled(string $key, ?int $userId = null): bool
    {
        return app(\App\Services\FeatureFlagService::class)->isEnabled($key, $userId ?? auth()->id());
    }
}

if (!function_exists('generateBarcodeImage')) {
    function generateBarcodeImage($text) {
      try {
            $generator = new BarcodeGeneratorPNG();
            
            $barcodeData = $generator->getBarcode(
                $text,
                $generator::TYPE_CODE_128,
                2,
                50,
                [0, 0, 0]
            );

            return 'data:image/png;base64,' . base64_encode($barcodeData);
        } catch (\Exception $e) {
            throw new \RuntimeException('Failed to generate barcode: ' . $e->getMessage());
        }
    }
}

if (!function_exists('stringToColor')) {
    function stringToColor($string)
    {
        // Generate pastel fallback for unknown colors
        $hash = md5($string);
        $r = (hexdec(substr($hash, 0, 2)) + 255) / 2;
        $g = (hexdec(substr($hash, 2, 2)) + 255) / 2;
        $b = (hexdec(substr($hash, 4, 2)) + 255) / 2;
        return sprintf("#%02x%02x%02x", $r, $g, $b);
    }
}

if (!function_exists('getColorCode')) {
    function getColorCode($colorName)
    {
        $originalName = $colorName;
        $colorName = strtolower($colorName);

        // ✅ Fix typos
        $colorName = str_replace(['voilet', 'aash'], ['violet', 'ash'], $colorName);

        // ✅ Normalize spaces and dashes
        $colorName = str_replace(['-', '_'], ' ', $colorName);

        // ✅ Base color map
        $colors = [
            'black' => '#000000',
            'white' => '#ffffff',
            'red' => '#ff0000',
            'blue' => '#0000ff',
            'green' => '#008000',
            'light green' => '#90ee90',
            'dark green' => '#006400',
            'pink' => '#ffc0cb',
            'dark pink' => '#ff1493',
            'baby pink' => '#f4c2c2',
            'orange' => '#ffa500',
            'yellow' => '#ffff00',
            'purple' => '#800080',
            'violet' => '#8f00ff',
            'sky blue' => '#87ceeb',
            'cream' => '#fffdd0',
            'maroon' => '#800000',
            'ash' => '#b2beb5',
            'gold' => '#ffd700',
            'rose gold' => '#b76e79',
            'stone' => '#dcdcdc',
            'matte' => '#999999',
        ];

        // ✅ Handle multi-color names (split and match)
        if (isset($colors[$colorName])) {
            return $colors[$colorName];
        }

        if (in_array($colorName, ['multi color', 'multicolor', 'multi'])) {
            $multiColors = ['#ffc0cb', '#75e975', '#7070d1', '#ebeb32'];
            $count = count($multiColors);
            $angleStep = 360 / $count;
            $gradientParts = [];
            foreach ($multiColors as $index => $hex) {
                $start = $index * $angleStep;
                $end = ($index + 1) * $angleStep;
                $gradientParts[] = "$hex {$start}deg {$end}deg";
            }
            return 'conic-gradient(' . implode(', ', $gradientParts) . ')';
        }

        $parts = explode(' ', $colorName);
        $matchedColors = [];

        foreach ($parts as $part) {
            if (isset($colors[$part])) {
                $matchedColors[] = $colors[$part];
            }
        }

        if (count($matchedColors) > 1) {
            $count = count($matchedColors);
            $step = 100 / $count;
            $gradientParts = [];
            foreach ($matchedColors as $index => $color) {
                $start = $index * $step;
                $end = ($index + 1) * $step;
                $gradientParts[] = "$color {$start}% {$end}%";
            }
            return "linear-gradient(90deg, " . implode(', ', $gradientParts) . ")";
        }

        if (count($matchedColors) === 1) {
            return $matchedColors[0];
        }

        // ✅ Try HEX / RGB formats
        try {
            return Hex::fromString($colorName)->toHex();
        } catch (\Exception $e) {}

        try {
            return Rgb::fromString($colorName)->toHex();
        } catch (\Exception $e) {}

        // ✅ Fallback to pastel color
        return stringToColor($originalName);
    }
}

if (!function_exists('kiyoshorturl')) {
    /**
     * Shorten a URL via YOURLS API. Returns the original URL on failure.
     */
    function kiyoshorturl(string $before_enc_url): string
    {
        $username = 'KiyoUser';
        $password = 'KiyoUser';
        $api_url = 'https://kiyosnap.com/yourls-api.php';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, [
            'format' => 'json',
            'action' => 'shorturl',
            'username' => $username,
            'password' => $password,
            'url' => $before_enc_url,
        ]);

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            \Illuminate\Support\Facades\Log::warning('kiyoshorturl failed', [
                'error' => curl_error($ch),
                'url' => $before_enc_url,
            ]);
            curl_close($ch);

            return $before_enc_url;
        }

        curl_close($ch);

        $data = json_decode($response);
        if (!is_object($data) || empty($data->shorturl)) {
            \Illuminate\Support\Facades\Log::warning('kiyoshorturl returned invalid response', [
                'response' => $response,
                'url' => $before_enc_url,
            ]);

            return $before_enc_url;
        }

        return str_replace('https://', '', (string) $data->shorturl);
    }
}

if (!function_exists('storage_url')) {
    /**
     * Build a public URL for a file on the public storage disk, with optional cache-busting version.
     */
    function storage_url(string $path, ?string $version = null): string
    {
        $url = asset('storage/' . ltrim($path, '/'));

        return $version ? $url . '?v=' . $version : $url;
    }
}