<?php

class Wiaas_Admin_Product_Additional_Info {

    public static function init() {

        add_action('woocommerce_product_options_general_product_data', array(__CLASS__, 'display_additional_fields'));
        add_action('woocommerce_process_product_meta', array(__CLASS__, 'save_additional_fields'));
        add_filter('woocommerce_json_search_found_products', array(__CLASS__, 'filter_product_by_country'));
    }


    /**
     * Add Manufacturer product and Supplier product number fields to
     * Simple product general tab
     *
     */
    public static function display_additional_fields() {

        global $post;
        $product  = wc_get_product( $post->ID );

        if ($product->get_type() === 'simple') {

            echo '<div class=" product_custom_field ">';

            woocommerce_wp_text_input(
                array(
                    'id' => '_manufacturer_product_no',
                    'label' => __('Manufacturer product number', 'woocommerce'),
                    'type' => 'text'
                )
            );

            woocommerce_wp_text_input(
                array(
                    'id' => '_supplier_product_no',
                    'label' => __('Supplier product number', 'woocommerce'),
                    'type' => 'text'
                )
            );

            echo '</div>';
        }
    }

    public static function filter_product_by_country($search_results) {

        $url = wp_get_referer();

        if (strpos($url, 'post') === false) {
            return $search_results;
        }

        $post_param = explode("&", parse_url($url, PHP_URL_QUERY))[0];
        $post_id = explode("=", $post_param)[1];
        $country_id = wp_get_post_terms($post_id, 'product_country', array('fields' => 'ids'))[0];

        if (!empty($search_results)) {
            $search_result_objects = array_map('wc_get_product', array_keys($search_results));

            foreach ($search_result_objects as $result_id => $producta) {
                if (Wiaas_Countries::get_product_country_term_id($producta) !== $country_id) {
                    unset($search_results[$producta->get_id()]);
                }
            }
        }

        return $search_results;
    }


    /**
     * Save Manufacturer product and Supplier product number fields to
     * Simple product meta data
     *
     */
    public static function save_additional_fields($post_id) {

        $manufacturer_product_no = $_POST['_manufacturer_product_no'];
        if (!empty($manufacturer_product_no))
            update_post_meta($post_id, '_manufacturer_product_no', esc_attr($manufacturer_product_no));

        $supplier_product_no = $_POST['_supplier_product_no'];
        if (!empty($supplier_product_no))
            update_post_meta($post_id, '_supplier_product_no', esc_attr($supplier_product_no));

    }
}

Wiaas_Admin_Product_Additional_Info::init();