<?php
/**
 * News service for Noesia Smart Waiter.
 *
 * Extracted from the legacy Dashboard data helper so News-related mapping can
 * live inside the News module instead of the central kernel or Dashboard
 * module.
 *
 * This is the first News extraction step. It keeps the same behavior while
 * moving ownership of News language/country resolution into the News module.
 *
 * @package Noesia_Smart_Waiter
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! class_exists( 'Noesia_SWA_News_Service' ) ) {
    /**
     * News service.
     */
    class Noesia_SWA_News_Service {

        /**
         * Resolve the dashboard/news country code from settings or language.
         *
         * @param string              $news_language News language code.
         * @param array<string,mixed> $options       Optional plugin settings.
         * @return string
         */
        public function get_news_country( $news_language, $options = array() ) {
            $news_language = sanitize_key( (string) $news_language );
            $options       = is_array( $options ) ? $options : array();

            $country_map = array(
                'en' => 'US',
                'el' => 'GR',
                'fr' => 'FR',
                'de' => 'DE',
                'it' => 'IT',
                'es' => 'ES',
            );

            $explicit_country = '';

            if ( isset( $options['news_country'] ) ) {
                $explicit_country = strtoupper( preg_replace( '/[^A-Z]/', '', sanitize_text_field( (string) $options['news_country'] ) ) );
            }

            if ( '' === $explicit_country && isset( $options['weather_country'] ) ) {
                $explicit_country = strtoupper( preg_replace( '/[^A-Z]/', '', sanitize_text_field( (string) $options['weather_country'] ) ) );
            }

            $explicit_country = substr( (string) $explicit_country, 0, 2 );

            if ( '' !== $explicit_country ) {
                return $explicit_country;
            }

            return isset( $country_map[ $news_language ] ) ? $country_map[ $news_language ] : 'US';
        }
    }
}
