<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

namespace Core\Lib;

class ProductSpec
{
    public static function ensureCartColumn($db)
    {
        return true;
    }

    public static function normalizeForStorage($input)
    {
        $groups = self::parseInput($input);
        return $groups ? json_encode($groups, JSON_UNESCAPED_UNICODE) : '';
    }

    public static function parseStored($raw)
    {
        return self::parseInput($raw);
    }

    public static function toTextarea($raw)
    {
        $groups = self::parseStored($raw);
        $lines = [];
        foreach ($groups as $group) {
            $lines[] = $group['name'] . ':' . implode(',', $group['values']);
        }
        return implode("\n", $lines);
    }

    public static function selectionText($rawSpecs, $selection)
    {
        $groups = self::parseStored($rawSpecs);
        if (!$groups) {
            return '';
        }
        if (is_string($selection)) {
            $decoded = json_decode($selection, true);
            if (is_array($decoded)) {
                $selection = $decoded;
            }
        }
        if (!is_array($selection)) {
            return '';
        }

        $parts = [];
        foreach ($groups as $group) {
            $name = $group['name'];
            $value = trim((string) ($selection[$name] ?? ''));
            if ($value === '') {
                return '';
            }
            if (!in_array($value, $group['values'], true)) {
                return '';
            }
            $parts[] = $name . ':' . $value;
        }
        return implode('；', $parts);
    }

    public static function requiredMessage($rawSpecs)
    {
        return self::parseStored($rawSpecs) ? '请选择商品规格' : '';
    }

    private static function parseInput($input)
    {
        if (is_array($input)) {
            return self::normalizeGroups($input);
        }

        $raw = trim((string) $input);
        if ($raw === '') {
            return [];
        }

        $decoded = json_decode($raw, true);
        if (is_array($decoded)) {
            return self::normalizeGroups($decoded);
        }

        $groups = [];
        foreach (preg_split('/\r\n|\r|\n/', $raw) as $line) {
            $line = trim($line);
            if ($line === '') {
                continue;
            }
            $parts = preg_split('/[:：]/u', $line, 2);
            if (count($parts) !== 2) {
                continue;
            }
            $name = trim($parts[0]);
            $values = array_filter(array_map('trim', preg_split('/[,，|、]/u', $parts[1])));
            if ($name !== '' && $values) {
                $groups[] = ['name' => $name, 'values' => array_values(array_unique($values))];
            }
        }
        return $groups;
    }

    private static function normalizeGroups(array $input)
    {
        $groups = [];
        foreach ($input as $key => $group) {
            if (is_array($group) && isset($group['name'])) {
                $name = trim((string) $group['name']);
                $values = $group['values'] ?? [];
            } else {
                $name = is_string($key) ? trim($key) : '';
                $values = $group;
            }
            if (is_string($values)) {
                $values = preg_split('/[,，|、]/u', $values);
            }
            if (!is_array($values)) {
                continue;
            }
            $values = array_values(array_unique(array_filter(array_map('trim', array_map('strval', $values)))));
            if ($name !== '' && $values) {
                $groups[] = ['name' => $name, 'values' => $values];
            }
        }
        return $groups;
    }
}
