<?php

if (!function_exists('getAvgRating')) {
    function getAvgRating(WP_Query $posts): float
    {
        $total_ratings = 0;
        if ($posts->have_posts()) {
            while ($posts->have_posts()) {
                $posts->the_post();
                $total_ratings += get_field('rating_number');
            }
        }

        $total_posts = $posts->post_count;
        $average_rating = 0;
        if ($total_posts > 0) {
            $average_rating = round($total_ratings / $total_posts, 1);
        }
        return $average_rating;
    }
}

if (!function_exists('getFlagUriBySlug')) {
    function getFlagUriBySlug(string|null $slug): string
    {
        $base_url = '/shop/wp-content/plugins/sitepress-multilingual-cms/res/flags/';
        $flug_files = [
            'DE' => 'de.svg',
            'EN' => 'en.svg',
            'FR' => 'fr.svg',
            'NL' => 'nl.svg',
            'BE' => 'de.svg',
            'IE' => 'ie.svg',
        ];
        if (array_key_exists($slug, $flug_files)) {
            return $base_url . $flug_files[$slug];
        }
        return '';
    }
}

if (!function_exists('getCountryBySlug')) {
    function getCountryBySlug(string|null $slug): string
    {
        $countries = [
            'DE' => __('Germany', 'fitsmartio_en'),
            'EN' => __('United Kingdom', 'fitsmartio_en'),
            'FR' => __('France', 'fitsmartio_en'),
            'NL' => __('Netherlands', 'fitsmartio_en'),
            'BE' => __('Belgium', 'fitsmartio_en'),
            'IE' => __('Ireland', 'fitsmartio_en'),
        ];
        if (array_key_exists($slug, $countries)) {
            return $countries[$slug];
        }
        return '';
    }
}

if (!function_exists('printStars')) {
    function printStars(int|null $amount, string|null $star_html): void
    {
        if (!$amount or !$star_html) {
            return;
        }
        echo str_repeat($star_html, $amount);
    }
}
