<?php
/**
 * The class handling the custom meta boxes.
 *
 * @package    Woocommerce_Product_Tabs
 */

namespace Barn2\Plugin\WC_Product_Tabs_Pro\Admin;

use Barn2\Plugin\WC_Product_Tabs_Pro\Plugin;
use Barn2\Plugin\WC_Product_Tabs_Pro\Dependencies\Lib\Admin\Settings_API_Helper;

/**
 * The class handling the custom meta boxes.
 *
 * @package    Woocommerce_Product_Tabs
 */
class Meta_Boxes {

	/**
	 * 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 $license_setting;

	/**
	 * 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->license_setting   = $plugin->get_license_setting();
		$this->version           = $plugin->get_version();

		$this->load();
	}

		/**
	 * Register all of the hooks related to the dashboard functionality
	 * of the plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	public function load() {
		// Metabox in Tab
		add_action( 'add_meta_boxes', [ $this, 'add_tab_meta_boxes' ] );
		add_action( 'save_post', [ $this, 'save_tab_meta_box_content' ] );
		add_action( 'save_post', [ $this, 'save_tab_meta_box_category' ] );
		add_action( 'save_post', [ $this, 'save_tab_meta_box_product' ] );
		add_action( 'save_post', [ $this, 'save_tab_meta_box_icon' ] );
		add_action( 'save_post', [ $this, 'woo_product_tabs_override_tab_slug' ], 20, 3 );
	}

	/**
	 * Add meta box in product tabs.
	 *
	 * @since    1.0.0
	 */
	public function add_tab_meta_boxes() {

		$screens = [ WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB ];

		foreach ( $screens as $screen ) {

			// Settings Metabox
			add_meta_box(
				WOOCOMMERCE_PRODUCT_TABS_SLUG . '_tab_section',
				__( 'Tab: Settings', 'woocommerce-product-tabs' ),
				[ $this, 'tab_meta_box_callback' ],
				$screen,
				'side',
				'high'
			);

			// Category Metabox
			add_meta_box(
				WOOCOMMERCE_PRODUCT_TABS_SLUG . '_tab_condition_section',
				__( 'Product categories', 'woocommerce-product-tabs' ),
				[ $this, 'tab_categories_meta_box_callback' ],
				$screen,
				'side'
			);

			// Product Metabox
			add_meta_box(
				WOOCOMMERCE_PRODUCT_TABS_SLUG . '_tab_product_section',
				__( 'Products', 'woocommerce-product-tabs' ),
				[ $this, 'tab_products_meta_box_callback' ],
				$screen,
				'side'
			);

			// Icon Metabox
			add_meta_box(
				WOOCOMMERCE_PRODUCT_TABS_SLUG . '_tab_icon_section',
				__( 'Icons', 'woocommerce-product-tabs' ),
				[ $this, 'tab_icons_meta_box_callback' ],
				$screen,
				'normal'
			);

		}

	}

	public function tab_meta_box_callback( $post ) {

		$post_id = $post->ID;

			// Add an nonce field so we can check for it later.
		wp_nonce_field( 'wpt_tab_meta_box', 'wpt_meta_box_tab_nonce' );

		$use_default_for_all = get_post_meta( $post->ID, '_wpt_option_use_default_for_all', true );
		echo '<p><label for="_wpt_option_use_default_for_all"><strong>' . __( 'Use Default for All', 'woocommerce-product-tabs' ) . '</strong>';
		echo '</label>';
		echo '</p>';
		echo '<input type="checkbox" name="_wpt_option_use_default_for_all" id="_wpt_option_use_default_for_all" value="yes" ';
		checked( 'yes', $use_default_for_all, true );
		echo ' />';
		echo '<span>' . __( 'Check to display default content in all products', 'woocommerce-product-tabs' ) . '</span>';

	}

	public function tab_categories_meta_box_callback( $post ) {

		$post_id = $post->ID;

		wp_nonce_field( 'wpt_tab_meta_box', 'wpt_meta_box_tab_category_nonce' );

		$wpt_conditions_category = [];
		$wpt_conditions_category = get_post_meta( $post_id, '_wpt_conditions_category', true );

		// echo '<h4>'.__( 'Product Categories', 'woocommerce-product-tabs' ).'</h4>';
		// echo '<p>'.__( 'Select categories if you want to show tab in selected category only. If nothing is selected it will be shown for all categories. ', 'woocommerce-product-tabs' ).'</p>';

		$args = [
			'walker'     => new Product_Category_Walker(),
			'taxonomy'   => 'product_cat',
			'hide_empty' => 0,
			'title_li'   => '',
			'checked'    => $wpt_conditions_category,
		];

		echo '<ul class="condition-category-list">';
		wp_list_categories( $args );
		echo '</ul><!-- .condition-category-list -->';

	}


	public function tab_products_meta_box_callback( $post ) {

		$post_id = $post->ID;

		wp_nonce_field( 'wpt_tab_meta_box', 'wpt_meta_box_tab_product_nonce' );

		// Select Products Section
		$wpt_conditions_product = [];
		$wpt_conditions_product = get_post_meta( $post_id, '_wpt_conditions_product', true );

		$args = [
			'post_type'        => 'product',
			'post_status'      => 'publish',
			'order'            => 'DESC',
			'orderby'          => 'date',
			'posts_per_page'   => -1,
			'suppress_filters' => 0,
		];

		$products = get_posts( $args );

		if ( ! empty( $products ) ) {
			echo '<input type="text" id="wpt_search_product" placeholder="Search product..">';
			echo '<ul class="condition-product-list icon-list-wrap" id="wpt_product_ul">';
			foreach ( $products as $product ) {

				$checked_product = '';
				if ( is_array( $wpt_conditions_product ) ) {
					$checked_product = checked( in_array( $product->ID, $wpt_conditions_product ), true, false );
				}
				?>
				<li class="select-product">
				<input type="checkbox" <?php echo esc_attr( $checked_product ); ?> id="product-<?php echo esc_attr( $product->ID ); ?>" name="wpt_product_list[]" value="<?php echo esc_attr( $product->ID ); ?>" />
				<label for="product-<?php echo esc_attr( $product->ID ); ?>">
					<?php echo esc_html( $product->post_title ); ?>
				</label>
				</li>
				<?php
			}
			echo '</ul><!-- .condition-product-list -->';
		} else {
			echo '<p>' . __( 'Products not found.', 'woocommerce-product-tabs' ) . '</p>';
		}

	}

	public function tab_icons_meta_box_callback( $post ) {
		$post_id = $post->ID;
		wp_nonce_field( 'wpt_tab_meta_box', 'wpt_meta_box_tab_icon_nonce' );

		$tab_icon = get_post_meta( $post->ID, '_wpt_tab_icon', true );
		?>
		<div class="icon-wrap">
		<a href="#" class="tab_icon button button-secondary"><?php esc_html_e( 'Add Icon', 'woocommerce-product-tabs' ); ?></a>
		<input type="hidden" name="wpt_tab_icon" id="product_tab_icon" class="input-icon" value="<?php echo esc_attr( $tab_icon ); ?>">
		<div class="icon-output">
			<?php if ( ! empty( $tab_icon ) ) : ?>
			<i class="<?php echo esc_attr( $tab_icon ); ?>"></i>
			<a href="#" class="icon-remove"><?php esc_html_e( 'Remove', 'woocommerce-product-tabs' ); ?></a>
			<?php endif ?>
		</div>
		</div>
		<?php require WOOCOMMERCE_PRODUCT_TABS_DIR . '/templates/admin/icons.php'; ?>
		<?php
	}

	/**
	 *  Save post product tab icon.
	 *
	 * @since 1.0.0
	 */
	public function save_tab_meta_box_icon( $post_id ) {

		// Check if our nonce is set.
		if ( ! isset( $_POST['wpt_meta_box_tab_icon_nonce'] ) ) {
			return;
		}
		// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( $_POST['wpt_meta_box_tab_icon_nonce'], 'wpt_tab_meta_box' ) ) {
			return;
		}

		// If this is an autosave, our form has not been submitted, so we don't want to do anything.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB != $_POST['post_type'] ) {
			return;
		}

		$wpt_tab_icon = '';
		if ( isset( $_POST['wpt_tab_icon'] ) && ! empty( $_POST['wpt_tab_icon'] ) ) {
			$wpt_tab_icon = $_POST['wpt_tab_icon'];
		}
		if ( empty( $wpt_tab_icon ) ) {
			delete_post_meta( $post_id, '_wpt_tab_icon' );
			// return;
		} else {
			update_post_meta( $post_id, '_wpt_tab_icon', $wpt_tab_icon );
		}

	}

	/**
	 *  Save post product tab.
	 *
	 * @since 1.0.0
	 */
	public function save_tab_meta_box_product( $post_id ) {

			// Check if our nonce is set.
		if ( ! isset( $_POST['wpt_meta_box_tab_product_nonce'] ) ) {
			return;
		}
			// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( $_POST['wpt_meta_box_tab_product_nonce'], 'wpt_tab_meta_box' ) ) {
			return;
		}

		// If this is an autosave, our form has not been submitted, so we don't want to do anything.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB != $_POST['post_type'] ) {
			return;
		}

		$wpt_conditions_product = '';
		if ( isset( $_POST['wpt_product_list'] ) && ! empty( $_POST['wpt_product_list'] ) ) {
			$wpt_conditions_product = $_POST['wpt_product_list'];
		}
		if ( empty( $wpt_conditions_product ) ) {
			delete_post_meta( $post_id, '_wpt_conditions_product' );
			// return;
		} else {
			update_post_meta( $post_id, '_wpt_conditions_product', $wpt_conditions_product );
		}

	}

	/**
	 *  Save post category tab.
	 *
	 * @since 1.0.0
	 */
	public function save_tab_meta_box_category( $post_id ) {

		// Check if our nonce is set.
		if ( ! isset( $_POST['wpt_meta_box_tab_category_nonce'] ) ) {
			return;
		}
		// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( $_POST['wpt_meta_box_tab_category_nonce'], 'wpt_tab_meta_box' ) ) {
			return;
		}
		// If this is an autosave, our form has not been submitted, so we don't want to do anything.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB != $_POST['post_type'] ) {
			return;
		}

		$wpt_conditions_category = '';
		if ( isset( $_POST['wpt_product_category'] ) && ! empty( $_POST['wpt_product_category'] ) ) {
			$wpt_conditions_category = $_POST['wpt_product_category'];
		}
		if ( empty( $wpt_conditions_category ) ) {
			delete_post_meta( $post_id, '_wpt_conditions_category' );
			return;
		}
		update_post_meta( $post_id, '_wpt_conditions_category', $wpt_conditions_category );

	}


	/**
	 *  Save product tabs settings.
	 *
	 * @since 1.0.0
	 */
	public function save_tab_meta_box_content( $post_id ) {

			// Check if our nonce is set.
		if ( ! isset( $_POST['wpt_meta_box_tab_nonce'] ) ) {
			return;
		}
			// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( $_POST['wpt_meta_box_tab_nonce'], 'wpt_tab_meta_box' ) ) {
			return;
		}
			// If this is an autosave, our form has not been submitted, so we don't want to do anything.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB != $_POST['post_type'] ) {
			return;
		}

			// use_default_for_all
		$use_default_for_all = '';
		if ( isset( $_POST['_wpt_option_use_default_for_all'] ) ) {
			$use_default_for_all = $_POST['_wpt_option_use_default_for_all'];
		}
		if ( ! isset( $_POST['_wpt_option_use_default_for_all'] ) ) {
			$use_default_for_all = 'no';
		}
		update_post_meta( $post_id, '_wpt_option_use_default_for_all', $use_default_for_all );

	}

	/**
	 * Customize tab.
	 *
	 * @since 1.0.2
	 *
	 * @param int     $post_id Post ID.
	 * @param WP_Post $post WP_Post object.
	 * @param bool    $update Whether this is update or not.
	 */
	function woo_product_tabs_override_tab_slug( $post_id, $post, $update ) {
		// Only want to set if this is a new post.
		if ( $update ) {
			return;
		}

		// Bail out if this is an autosave.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		// Bail out if this is not an event item.
		if ( WOOCOMMERCE_PRODUCT_TABS_POST_TYPE_TAB !== $post->post_type ) {
			return;
		}

		// Bail out if no permission.
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		remove_action( 'save_post', [ $this, 'woo_product_tabs_override_tab_slug' ], 20 );

		$unique_slug = 'wpt-' . $post_id;

		$new_data = [
			'ID'        => $post_id,
			'post_name' => $unique_slug,
		];

		wp_update_post( $new_data );

		add_action( 'save_post', [ $this, 'woo_product_tabs_override_tab_slug' ], 20, 3 );
	}

}
