<?php
/**
 * Contains the class that handles the plugins meta fields for WooCommerce products.
 *
 */

namespace Wetail\Shipping\Engine;



defined( __NAMESPACE__ . '\PATH' ) or die();

if ( class_exists( __NAMESPACE__ . '\Wetail_Shipping_Product_Fields' ) ) {
	return;
}

/**
 * Handles the plugins meta fields for WooCommerce products.
 *
 * @since 3.1.0
 */
final class Wetail_Shipping_Product_Fields {

	const WETAIL_SHIPPING_HS_TARIFF_CODE = '_wetail_shipping_hs_tariff_code';

    /**
     * Registers the fields with WooCommerce.
     *
     * @return void
     * @since 1.1.4
     */
    public static function init() {
		if ( self::is_edit_product_page() ){
			self::add_hs_tariff_code_field();

		}
	    self::add_variations_hs_tariff_code_field();
	    add_action(
		    'woocommerce_admin_process_product_object', function( $wc_product ) {
			    self::process_save( $wc_product );
		    }
	    );

        add_action( 'woocommerce_save_product_variation', function( $post_id, $i ) {
            self::process_save_variation( $post_id, $i );
        }, 10, 2 );
    }

	/**
	 * Adds HS Tariff code field product view
	 * @since 1.1.4
	 */
    private static function add_hs_tariff_code_field() {
        add_action(
            'woocommerce_product_options_shipping', function() {
            global $post;

            if ( 'variable' === wc_get_product( $post->ID )->get_type() ) {
                return;
            }

            echo woocommerce_wp_text_input( // WPCS: XSS ok.
                [
                    'id'          => self::WETAIL_SHIPPING_HS_TARIFF_CODE,
                    'value'       => get_post_meta( $post->ID, self::WETAIL_SHIPPING_HS_TARIFF_CODE, true ),
                    'label'       => __( 'HS Tariff Code', 'wetail-shipping' ),
                    'desc_tip'    => true,
                    'description' => __(
                        'HS Tariff Code for this product.',
                        'wetail-shipping'
                    ),
                ]
            );
        });
    }

	/**
	 * Adds HS Tariff code field product variation view
	 * @since 1.1.4
	 */
    private static function add_variations_hs_tariff_code_field() {
        add_action(
            'woocommerce_product_after_variable_attributes',
            function( $loop, $variation_data, $variation ) {
                echo '<div class="variation-custom-fields">';

                woocommerce_wp_text_input(
                    [
                        'id'            => self::WETAIL_SHIPPING_HS_TARIFF_CODE . '[' . $loop . ']',
                        'label'         => __( 'HS Tariff Code', 'wetail-shipping' ),
                        'wrapper_class' => 'form-row',
                        'value'         => get_post_meta(
                            $variation->ID, self::WETAIL_SHIPPING_HS_TARIFF_CODE, true
                        ),
                    ]
                );

                echo '</div>';
            }, 10, 3
        );
    }

	/**
	 * Saves HS Tariff code to product meta
	 * @since 1.1.4
	 * @param $wc_product
	 */
	private static function process_save( $wc_product ) {
		wetail_shipping_write_log("Saving");
        $nonce_is_valid = wp_verify_nonce(
            $_REQUEST['woocommerce_meta_nonce'],
            'woocommerce_save_data'
        );

        if ( ! $nonce_is_valid ) {
            die( 'Invalid nonce' );
        }

        if ( isset( $_POST[self::WETAIL_SHIPPING_HS_TARIFF_CODE] ) ) {
	        wetail_shipping_write_log(self::WETAIL_SHIPPING_HS_TARIFF_CODE);
	        wetail_shipping_write_log($_POST[self::WETAIL_SHIPPING_HS_TARIFF_CODE]);
            $hs_tariff_code = sanitize_text_field( $_POST[self::WETAIL_SHIPPING_HS_TARIFF_CODE] );
            update_post_meta(
                $wc_product->get_id(),
	            self::WETAIL_SHIPPING_HS_TARIFF_CODE, esc_attr( $hs_tariff_code )
            );
        }
    }

	/**
	 * Saves HS Tariff code to product variation meta
	 * @since 1.1.4
	 * @param $post_id
	 * @param $i
	 */
    private static function process_save_variation( $post_id, $i ) {
	    wetail_shipping_write_log("Saving var");
        if ( isset( $_POST[self::WETAIL_SHIPPING_HS_TARIFF_CODE][ $i ] ) ) {
	        $hs_tariff_code = sanitize_text_field( $_POST[self::WETAIL_SHIPPING_HS_TARIFF_CODE][ $i ] );
            update_post_meta(
                $post_id, self::WETAIL_SHIPPING_HS_TARIFF_CODE, esc_attr( $hs_tariff_code )
            );
        }
    }

	/** Returns true if we are on product page
	 * @since 1.1.4
	 * @return bool
	 */
	public static function is_edit_product_page() {
		return is_admin() &&
		       isset($_GET['post']) &&
		       get_post_type($_GET['post']) === 'product';
	}
}
