<?php
namespace OxygenApp\Utils;
if ( ! defined( 'ABSPATH' ) ) exit;

use OxygenApp\Config\Config;
use OxygenApp\Config\DefaultLabels;
use OxygenApp\Utils\OptionUtils;

class LanguageSyncHelper {

    public static function getMergedLanguages(): ?array {
        $languagesMetaKey = Config::getInstance()->getSetting('languages_meta_key');
        $savedLanguages = OptionUtils::getInstance()->getOption($languagesMetaKey);

        if (!is_array($savedLanguages) || empty($savedLanguages)) {
            return null;
        }

        $defaultLanguage = DefaultLabels::getDefaultLanguage();
        $defaultLabels = $defaultLanguage['labels'] ?? [];

        $defaultLabelMap = [];
        foreach ($defaultLabels as $labelData) {
            $name = $labelData['name'] ?? '';
            $value = $labelData['value'] ?? '';
            if (!empty($name)) {
                $defaultLabelMap[$name] = $value;
            }
        }

        foreach ($savedLanguages as $langCode => &$languageData) {
            $existingLabels = $languageData['labels'] ?? [];

            foreach ($defaultLabelMap as $labelName => $defaultValue) {
                if (!isset($existingLabels[$labelName])) {
                    $languageData['labels'][$labelName] = $defaultValue;
                }
            }
        }

        return $savedLanguages;
    }
}
