<?php
/**
 * The class handling the product tabs in the product post editor.
 *
 * @package    Woocommerce_Product_Tabs
 */

namespace Barn2\Plugin\WC_Product_Tabs_Pro\Admin;

use Barn2\Plugin\WC_Product_Tabs_Pro\Plugin;

/**
 * The class handling the product tabs in the product post editor.
 *
 * @package    Woocommerce_Product_Tabs
 */
class Product_Editor_Tabs {

	/**
	 * The plugin instance.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      Plugin    $plugin    The plugin instance.
	 */
	private $plugin;

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	private $product_tabs_list;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @var      Plugin
	 */
	public function __construct( $plugin ) {
		$this->plugin            = $plugin;
		$this->plugin_name       = $plugin->get_slug();
		$this->version           = $plugin->get_version();
		$this->product_tabs_list = get_posts(
			[
				'post_type'      => WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB,
				'posts_per_page' => -1,
				'orderby'        => 'menu_order',
				'order'          => 'asc',
			]
		);
		if ( ! empty( $this->product_tabs_list ) ) {
			foreach ( $this->product_tabs_list as $key => $t ) {
				$this->product_tabs_list[ $key ]->post_meta = get_post_meta( $this->product_tabs_list[ $key ]->ID );
			}
		}

		$this->load();
	}

	/**
	 * Register all of the hooks related to the product post editor
	 * of the plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	public function load() {
		// Add Product tab in product data
		add_filter( 'woocommerce_product_data_tabs', [ $this, 'product_data_tab' ], 99, 1 );
		add_action( 'woocommerce_product_data_panels', [ $this, 'product_data_fields' ] );
		add_action( 'save_post', [ $this, 'save_product_tab_data' ] );
		add_filter( 'wp_insert_post_data', [ $this, 'insert_tab_menu_order' ], 99, 2 );
		add_action( 'admin_head', [ $this, 'post_type_menu_active' ] );
	}


	/**
	 * Add Product Tabs in Product Page.
	 *
	 * @since 1.0.0
	 */
	function product_data_tab( $product_data_tabs ) {
		$product_data_tabs['product-tab'] = [
			'label'  => __( 'Product Tabs', 'woocommerce-product-tabs' ),
			'target' => 'product_tabs',
		];
		return $product_data_tabs;
	}

	/**
	 * View product tabs in product page.
	 *
	 * @since 1.0.0
	 */
	function product_data_fields() {

		include WOOCOMMERCE_PRODUCT_TABS_DIR . '/templates/admin/product-tab-html.php';

	}

	/**
	 *  Save product tabs data form product page.
	 *
	 * @since 1.0.0
	 */
	function save_product_tab_data( $post_id ) {

		if ( ! isset( $_POST['_wpt_product_data_nonce'] ) ) {
			return;
		}
		// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( $_POST['_wpt_product_data_nonce'], 'wpt_product_data' ) ) {
			return;
		}

		if ( ( get_post_type( $post_id ) == 'product' ) ) {

			if ( isset( $_POST['_wpt_newtab'] ) && ! empty( $_POST['_wpt_newtab'] ) ) {
				global $wpdb;
				$count      = 0;
				$menu_order = $wpdb->get_var( "SELECT MAX(menu_order)+1 AS menu_order FROM {$wpdb->posts} WHERE post_type='" . WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB . "'" );

				foreach ( $_POST['_wpt_newtab'] as $tab_post ) {
					if ( ! empty( $tab_post['title'] ) ) {
						$product_tab = [
							'post_title'   => sanitize_text_field( $tab_post['title'] ),
							'post_content' => wp_kses_post( $tab_post['content'] ),
							'post_type'    => WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB,
							'menu_order'   => absint( $menu_order + $count ),
							'post_status'  => 'publish',
						];

						$tab_post_id = wp_insert_post( $product_tab );
						if ( ! is_wp_error( $tab_post_id ) ) {
							update_post_meta( $tab_post_id, '_wpt_conditions_product', [ $post_id ] );
							update_post_meta( $tab_post_id, '_wpt_tab_icon', sanitize_text_field( $tab_post['icon'] ) );
						}
					}
					$count++;
				} //endforeach
			}

			$tabs = $this->product_tabs_list;

			if ( ! empty( $tabs ) ) {
				$tab_content = [];
				foreach ( $tabs as $tab ) {
					$tab_content[] = $tab->post_content;
				}

				foreach ( $_POST as $key => $p ) {
					$str = substr( $key, 0, 11 );

					if ( empty( $p ) ) {
						delete_post_meta( $post_id, $key );
					} else {
						if ( ( '_wpt_field_' === $str ) && ! in_array( $p, $tab_content ) ) {
							// Update the meta field in the database.
							update_post_meta( $post_id, $key, wp_kses_post( $p ) );
						}
						if ( in_array( $p, $tab_content ) ) {
							delete_post_meta( $post_id, $key );
						}
					}
				}
			}
		}

	}

	function insert_tab_menu_order( $data, $postarr ) {
		$post_type = WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB;
		if ( $data['post_type'] == $post_type && $data['post_status'] == 'auto-draft' ) {
			global $wpdb;
			if ( $wpdb->get_var( "SELECT menu_order FROM {$wpdb->posts} WHERE post_type='{$post_type}'" ) ) {
				$data['menu_order'] = $wpdb->get_var( "SELECT MAX(menu_order)+1 AS menu_order FROM {$wpdb->posts} WHERE post_type='{$post_type}'" );
			}
		}
		return $data;
	}

	/**
	 * Add active in menu product tabs
	 *
	 * @since 1.0.0
	 */
	function post_type_menu_active() {
		$screen = get_current_screen();
		if ( $screen->post_type === WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB ) {
			?>
		<script type="text/javascript">
			jQuery(document).ready(function(){
			jQuery('ul.wp-submenu li a[href*="edit.php?post_type=woo_product_tab"]').parent().addClass('current');
			});
		</script>
			<?php
		}
	}

}
