<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * Implements available wiaas countries
 *
 * Class Wiaas_Countries
 */
class Wiaas_Countries {

	/**
	 * Default available countries for wiaas
	 * @var array
	 */
	private static $default_countries = array(
		'se' => array(
			'vat' => 9 ,
			'currency' => 'SEK'
		),
		'dk' => array(
			'vat' => 9 ,
			'currency' => 'DKK'
		),
		'fi' => array(
			'vat' => 9 ,
			'currency' => 'EUR'
		),
	);

	public static function init() {

		add_action('woocommerce_after_register_taxonomy', array(__CLASS__, 'register_product_countries_taxonomy'));
	}

	/**
	 * Retrieve all possible country choices
	 *
	 * @return array
	 */
	public static function get_country_choices() {
		$countries = new WC_Countries();
		$choices = array();

		foreach ($countries->get_countries() as $code => $name) {
			$choices[strtolower($code)] = $name;
		}

		return $choices;
	}

	/**
	 * Retrieve all possible currency choices
	 *
	 * @return array
	 */
	public static function get_currency_choices() {
		return get_woocommerce_currencies();
	}

	/**
	 * Retrieve list of available countries setup by administrator
	 *
	 * @return array
	 */
	public static function get_available_countries() {
		$available_countries = [];

		$available_country_terms = get_terms(array(
			'taxonomy' => 'product_country',
            'hide_empty' => false,
		));

		foreach($available_country_terms as $country_term) {
			$code = get_term_meta($country_term->term_id, '_wiaas_country_code', true);
			$currency  = get_term_meta($country_term->term_id, '_wiaas_country_currency', true);
			$vat = get_term_meta($country_term->term_id, '_wiaas_country_vat', true);

			$available_countries[] = array(
				'id' => $country_term->term_id,
				'name' => $country_term->name,
				'code' => $code,
				'currency' => $currency,
				'vat' => $vat
			);
		}

		return $available_countries;
	}

	/**
	 * Retrieve country name by code for available country
	 *
	 * @param string $code
	 *
	 * @return string|null
	 */
	public static function get_available_country_name_by_code($code) {
		$available_countries = self::get_available_countries();

		foreach ($available_countries as $available_country) {

			if ($available_country['code'] === $code) {

				return $available_country['name'];
			}
		}

		return null;
	}

	/**
	 * Retrieve country code by currency for available country
	 *
	 * @param string $currency
	 *
	 * @return string|null
	 */
	public static function get_available_country_code_by_currency($currency) {
		$available_countries = self::get_available_countries();

		foreach ($available_countries as $available_country) {

			if ($available_country['currency'] === $currency) {

				return $available_country['code'];
			}
		}

		return null;
	}

	/**
	 * Registers product taxonomy for avaiable countries
	 */
	public static function register_product_countries_taxonomy() {

		$labels = array(
			'name'              => _x( 'Country', 'taxonomy general name', 'wiaas' ),
			'singular_name'     => _x( 'Country', 'taxonomy singular name', 'wiaas' ),
			'menu_name'         => _x( 'Country', 'Admin menu name', 'wiaas' ),
			'search_items'      => __( 'Search Countries', 'wiaas' ),
			'all_items'         => __( 'All Countries', 'wiaas' ),
			'parent_item'       => __( 'Parent Country', 'wiaas' ),
			'parent_item_colon' => __( 'Parent Country:', 'wiaas' ),
			'edit_item'         => __( 'Edit Country', 'wiaas' ),
			'update_item'       => __( 'Update Country', 'wiaas' ),
			'add_new_item'      => __( 'Add New Country', 'wiaas' ),
			'new_item_name'     => __( 'New Country Name', 'wiaas' ),
		);

		$args = array(
			'hierarchical'      => false,
			'label'                 => __( 'Countries', 'wiaas' ),
			'labels'            => $labels,
			'show_ui'           => true,
			'show_admin_column' => true,
			'query_var'         => true,
			'rewrite'           => array( 'slug' => 'product_country' ),
		);

		register_taxonomy( 'product_country', array( 'product' ), $args );

		$choices = self::get_country_choices();

		foreach (self::$default_countries as $code => $info) {

			$name = $choices[$code];

			if (has_term($name)) {
				// bail out
				return;
			}

			$name = $choices[$code];
			$result = wp_insert_term($name, 'product_country');

			if (is_wp_error($result)) {
				continue;
			}

			update_term_meta($result['term_id'], '_wiaas_country_code', $code);
			update_term_meta($result['term_id'], '_wiaas_country_currency', $info['currency']);
			update_term_meta($result['term_id'], '_wiaas_country_vat', $info['vat']);
		}
	}

	/**
	 * Retrieves country for provided package
	 * @param $package
	 *
	 * @return array|null
	 */
	public static function get_package_country($package) {
		return self::get_product_country($package);
	}

	/**
	 * Retrieves country for provided product
	 * @param $product
	 *
	 * @return array|null
	 */
	public static function   get_product_country($product) {
		$country_terms = get_the_terms($product->get_id(), 'product_country');

		if (is_wp_error($country_terms) || empty($country_terms) || empty($country_terms[0])) {
			return null;
		}

		$country_term = $country_terms[0];

		$code = get_term_meta($country_term->term_id, '_wiaas_country_code', true);
		$currency  = get_term_meta($country_term->term_id, '_wiaas_country_currency', true);
		$vat = get_term_meta($country_term->term_id, '_wiaas_country_vat', true);

		return  array(
			'id' => $country_term->term_id,
			'name' => $country_term->name,
			'code' => $code,
			'currency' => $currency,
			'vat' => $vat
		);
	}

    /**
     * Retrieves country term id from db for provided product
     * @param $product
     *
     * @return int|null
     */
    public static function get_product_country_term_id($product) {
        $product_country = get_the_terms($product->get_id(), 'product_country');
        return  is_array($product_country) && isset($product_country[0]) ?
            $product_country[0]->term_id :
            null;
    }
}

Wiaas_Countries::init();
