<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Condition\Wordpress\Rule\Language;

use ZOOlanders\YOOessentials\Condition\ConditionRule;

class LanguageRule extends ConditionRule
{
    public function resolve($props, $node): bool
    {
        if (!isset($props->languages)) {
            throw new \RuntimeException('Not Valid Input');
        }

        $current = \determine_locale();
        $selection = (array) $props->languages;

        return in_array($current, $selection);
    }

    public function fields(): array
    {
        return [
            'languages' => [
                'label' => 'Selection',
                'type' => 'select',
                'source' => true,
                'description' => 'The languages that the site current language must match. Use the shift or ctrl/cmd key to select multiple entries.',
                'attrs' => [
                    'multiple' => true,
                    'class' => 'uk-height-small uk-resize-vertical',
                ],
                'options' => $this->getAvailableLanguages(),
            ],
        ];
    }

    public function logArgs(): array
    {
        return [
            'Active Language' => \determine_locale(),
        ];
    }

    protected function getAvailableLanguages(): array
    {
        static $availableLanguages = [];

        if (empty($availableLanguages)) {
            require_once \ABSPATH . 'wp-admin/includes/translation-install.php';

            $languages = \get_available_languages();
            $translations = \wp_get_available_translations();

            $availableLanguages['English (United States)'] = 'en_US';

            foreach ($languages as $language) {
                $name = $translations[$language]['native_name'] ?? $language;
                $availableLanguages[$name] = $language;
            }
        }

        return $availableLanguages;
    }
}
