<?php

namespace EstatebudConnect\Services;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Traits\Singleton;

class Polylang
{
    use Singleton;

    public function __construct() {}

    public function get_enabled_languages()
    {
        if (!function_exists('pll_languages_list')) {
            return [];
        }

        $languages = pll_languages_list(['fields' => []]);

        if (empty($languages)) {
            return [];
        }

        $enabled_languages = [];
        foreach ($languages as $index => $language) {
            $enabled_languages[] = [
                'code' => $language->locale,
                'name' => $language->name ?? '',
                'flag' => $language->flag_url ?? '',
                'home_url' => rtrim($language->home_url ?? '', '/'),
                'slug' => $language->slug ?? '',
                'active' => $this->get_locale() === $language->locale,
            ];
        }

        return $enabled_languages;
    }

    public function get_locale()
    {
        return get_locale();
    }
    
    public function set_urls($languages = [], $language_slug)
    {
        $slugs = array_column($languages, 'slug');
        $index = array_search($language_slug, $slugs);

        if ($index === false) {
            return null;
        }

        return $languages[$index]['url'];
    }
}
