<?php

class Wiaas_Admin_Countries {

	public static function init() {

		// Add countries fields to countries list
		add_filter( 'manage_edit-product_country_columns', array( __CLASS__, 'update_list_headers' ) );
		add_filter( 'manage_product_country_custom_column', array( __CLASS__, 'update_list_column_content' ), 10, 3 );

		// Validate country settings
		add_filter('acf/load_field/name=_wiaas_country_code', array(__CLASS__, 'populate_country_codes'));
		add_filter('acf/load_field/name=_wiaas_country_currency', array(__CLASS__, 'populate_country_currencies'));
	}

	public static function update_list_headers($columns) {
		$columns['wiaas_code'] = __( 'Code', 'wiaas' );

		$columns['wiaas_vat'] = __('VAT', 'wiaas');

		$columns['wiaas_currency'] = __('Currency', 'wiaas');

		return $columns;
	}

	public static function update_list_column_content($columns, $column, $id) {

		if ($column === 'wiaas_code') {

			$code = get_term_meta($id, '_wiaas_country_code', true);
			$columns .= '<span>'. $code . '</span>';
		}

		if ($column === 'wiaas_vat') {

			$vat = get_term_meta($id, '_wiaas_country_vat', true);
			$columns .= '<span>'. $vat . '</span>';
		}

		if ($column === 'wiaas_currency') {

			$currency = get_term_meta($id, '_wiaas_country_currency', true);
			$columns .= '<span>'. $currency . '</span>';
		}

		return $columns;
	}

	public static function populate_country_codes($field) {
		$countries_list = Wiaas_Countries::get_country_choices();

		$countries_choices = array();
		foreach ($countries_list as $code => $name) {

			$countries_choices[$code] = $code . ' - ' . $name;
		}

		$field['choices'] = $countries_choices;

		return $field;
	}

	public static function populate_country_currencies($field) {

		$field['choices'] = Wiaas_Countries::get_currency_choices();

		return $field;
	}
}

Wiaas_Admin_Countries::init();
