<?php
/**
 * Class for WooCommerce Buy Now Settings
 *
 * @package     smart-offers/modules/buy-now/php/admin/
 * @since       4.0.0
 * @version     1.1.1
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'SA_WC_Buy_Now_Settings' ) ) {

	/**
	 * Class for WooCommerce Buy Now Settings
	 */
	class SA_WC_Buy_Now_Settings {

		/**
		 * Variable to hold instance of Buy Now Settings
		 *
		 * @var $instance
		 */
		private static $instance = null;

		/**
		 * Constructor
		 */
		private function __construct() {
			add_action( 'woocommerce_admin_field_sa_bn_full_row_text', array( $this, 'sa_bn_full_row_text' ) );
		}

		/**
		 * Get single instance of Buy Now Settings.
		 *
		 * @return SA_WC_Buy_Now_Settings Singleton object of SA_WC_Buy_Now_Settings
		 */
		public static function get_instance() {

			// Check if instance is already exists.
			if ( is_null( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Function to show Buy Now settings with save button.
		 */
		public function show_bn_settings() {
			$this->bn_save_storewide_settings();
			?>
			<form method="post" action="" id="wc_bn_storewide_settings">
				<?php woocommerce_admin_fields( $this->get_bn_storewide_settings() ); ?>
				<p class="submit">
					<button name="save" class="button-primary woocommerce-save-button" type="submit" value="<?php esc_attr_e( 'Save changes', 'smart-offers' ); ?>"><?php esc_html_e( 'Save changes', 'smart-offers' ); ?></button>
				</p>
				<?php wp_nonce_field( 'sa_wc_bn_storewide_settings', 'bn_security', false ); ?>
			</form>
			<?php
		}

		/**
		 * Function to get settting for storewide settings tab
		 */
		public function get_bn_storewide_settings() {

			// Header styles & scripts.
			do_action( 'sa_wc_buy_now_enhanced_select_script_start' );

			$buy_now_settings = array();

			$term_id_to_name = get_terms(
				array(
					'taxonomy'   => 'product_cat',
					'hide_empty' => false,
					'fields'     => 'id=>name',
				)
			);

			$product_category_terms = get_terms(
				array(
					'taxonomy'   => 'product_cat',
					'hide_empty' => false,
					'fields'     => 'all',
				)
			);

			$categories = array();

			if ( ! empty( $product_category_terms ) ) {
				foreach ( $product_category_terms as $product_category_term ) {
					$categories[ $product_category_term->term_id ] = $product_category_term->name;
					if ( ! empty( $product_category_term->parent ) ) {
						$categories[ $product_category_term->term_id ] .= '&nbsp;&mdash;&nbsp;' . $term_id_to_name[ $product_category_term->parent ];
					}
				}
			}

			$all_discount_types = wc_get_coupon_types();

			$coupons = get_option( 'wc_buy_now_storewide_coupons', array() );
			foreach ( $coupons as $index => $code ) {
				$coupon        = new WC_Coupon( $code );
				$discount_type = $coupon->get_discount_type();
				if ( ! empty( $discount_type ) ) {
					/* translators: 1. Text 'Type', 2. Coupons discount type */
					$discount_type = sprintf( __( ' ( %1$s: %2$s )', 'smart-offers' ), __( 'Type', 'smart-offers' ), $all_discount_types[ $discount_type ] );
				}
				$coupons[ $code ] = $code . $discount_type;
				unset( $coupons[ $index ] );
			}

			$shipping_methods = (array) WC()->shipping->load_shipping_methods();
			$shipping_methods = wp_list_pluck( $shipping_methods, 'method_title', 'id' );
			$shipping_methods = array( '' => '' ) + $shipping_methods;

			$buy_now_settings = array(
				array(
					'type' => 'title',
					'id'   => 'wc_buy_now_option',
					'desc' => __( 'Use these options to configure the way Buy Now should work.', 'smart-offers' ),
				),
				array(
					'name'        => __( 'Label for "Buy Now" buttons', 'smart-offers' ),
					'desc'        => __( 'What should the "Buy Now" buttons be called. This option is only for "Buy Now" button.', 'smart-offers' ),
					'desc_tip'    => true,
					'id'          => 'wc_buy_now_button_text',
					'type'        => 'text',
					'placeholder' => __( 'Buy Now', 'smart-offers' ),
				),
				array(
					'name'  => __( 'Add to Cart and Checkout setup', 'smart-offers' ),
					'type'  => 'sa_bn_full_row_text',
					'class' => 'sa_bn_storewide_action_label',
					'css'   => 'padding-left: 0; padding-bottom: 0.5em;',
					'desc'  => __( 'Select one of these options', 'smart-offers' ),
				),
				array(
					'id'      => 'wc_buy_now_set_for',
					'class'   => 'wc_buy_now_set_for',
					'default' => 'standard',
					'type'    => 'radio',
					'options' => array(
						'standard' => __( 'Use "Buy Now" settings configured in the product', 'smart-offers' ),
					),
				),
				array(
					'name'    => ' ',
					'id'      => 'wc_buy_now_set_for',
					'class'   => 'wc_buy_now_set_for',
					'default' => 'standard',
					'type'    => 'radio',
					'options' => array(
						'buy-now' => __( 'Convert all "Add to cart" actions to "Buy Now"', 'smart-offers' ),
					),
				),
				array(
					'id'      => 'wc_buy_now_set_for',
					'class'   => 'wc_buy_now_set_for',
					'default' => 'standard',
					'type'    => 'radio',
					'options' => array(
						'and-buy-now' => __( 'Add "Buy Now" button in addition to "Add to cart" button', 'smart-offers' ),
					),
				),
				array(
					'name'              => __( 'Product categories', 'smart-offers' ),
					'desc'              => __( '"Buy Now" button will be displayed on products from these categories. Keep it empty to display on all products. This option is only for "Buy Now" button.', 'smart-offers' ),
					'desc_tip'          => true,
					'id'                => 'wc_buy_now_product_categories',
					'type'              => 'multiselect',
					'class'             => 'wc-enhanced-select',
					'css'               => 'width: 400px;',
					'default'           => '',
					'options'           => $categories,
					'custom_attributes' => array(
						'data-placeholder' => __( 'All product categories', 'smart-offers' ),
					),
				),
				array(
					'name'  => __( 'Additional settings for these "Buy Now" buttons', 'smart-offers' ),
					'type'  => 'sa_bn_full_row_text',
					'class' => 'sa_bn_additional_button_action_label',
					'css'   => 'padding-left: 5em; padding-bottom: 0.5em; padding-top:0.5em; font-weight: bold; border-left: 1px solid #cccccc; border-right: 1px solid #cccccc;',
					'desc'  => __( 'These settings will be applied to the "Buy Now" buttons for product categories selected above.', 'smart-offers' ),
				),
				array(
					'name'              => __( 'Apply coupons', 'smart-offers' ),
					'desc'              => __( '"Buy Now" button will apply selected coupons to cart. This option is only for "Buy Now" button.', 'smart-offers' ),
					'desc_tip'          => true,
					'id'                => 'wc_buy_now_storewide_coupons',
					'type'              => 'multiselect',
					'class'             => 'select2_search_products_coupons',
					'css'               => 'width: 400px;',
					'default'           => '',
					'options'           => $coupons,
					'custom_attributes' => array(
						'data-placeholder' => __( 'Search a coupon...', 'smart-offers' ),
						'data-action'      => 'woocommerce_json_search_coupons',
						'data-security'    => wp_create_nonce( 'search-coupons' ),
					),
				),
				array(
					'name'              => __( 'Shipping method', 'smart-offers' ),
					'desc'              => __( '"Buy Now" button will apply this shipping method to order. This option is only for "Buy Now" button.', 'smart-offers' ),
					'id'                => 'wc_buy_now_storewide_shipping_method',
					'default'           => '',
					'type'              => 'select',
					'class'             => 'wc-enhanced-select-nostd',
					'css'               => 'min-width: 350px;',
					'desc_tip'          => true,
					'options'           => $shipping_methods,
					'custom_attributes' => array(
						'data-placeholder' => __( 'Select a shipping method...', 'smart-offers' ),
					),
				),
				array(
					'name'     => __( 'Redirect to page', 'smart-offers' ),
					'desc'     => __( 'Users will be redirected to this page when "Buy Now" button is clicked. Leaving it blank, will complete checkout for logged in users whose previous payment details are found and for guest users, they will be taken to the checkout page. This option is only for "Buy Now" button.', 'smart-offers' ),
					'id'       => 'wc_buy_now_storewide_redirect_to_page',
					'type'     => 'single_select_page',
					'default'  => '',
					'class'    => 'wc-enhanced-select-nostd',
					'css'      => 'min-width:300px;',
					'desc_tip' => true,
				),
				array(
					'id'      => 'wc_buy_now_set_for',
					'class'   => 'wc_buy_now_set_for',
					'default' => 'standard',
					'type'    => 'radio',
					'options' => array(
						'express-checkout' => __( 'Add "Express Checkout" button on the cart page', 'smart-offers' ),
					),
				),
				array(
					'name'        => __( 'Label for "Express Checkout" button', 'smart-offers' ),
					'desc'        => __( 'What should the "Express Checkout" buttons be called when display on cart page for logged in user', 'smart-offers' ),
					'desc_tip'    => true,
					'id'          => 'wc_buy_now_express_checkout_button_text',
					'type'        => 'text',
					'placeholder' => __( 'Express Checkout', 'smart-offers' ),
				),
				array(
					'name'     => __( 'Preserve user\'s cart?', 'smart-offers' ),
					'desc'     => __( 'Exclude existing products and checkout only with the product whose Buy Now link is clicked', 'smart-offers' ),
					'id'       => 'wc_buy_now_is_preserve_cart',
					'type'     => 'checkbox',
					'default'  => 'yes',
					'desc_tip' => __( 'When checked, products from user\'s current cart (if available) will not be combined with products of Buy now link. After completing buy now process, previous cart contents will be restored. When disabled, all the products in cart will be combined with products from buy now link.', 'smart-offers' ),
				),
				array(
					'name'     => __( 'Enable quick checkout?', 'smart-offers' ),
					'desc'     => __( 'Show checkout page in a popup', 'smart-offers' ),
					'id'       => 'wc_buy_now_is_quick_checkout',
					'type'     => 'checkbox',
					'default'  => 'yes',
					'desc_tip' => __( 'For guest users and for those users whose checkout details are not available the checkout page will be shown as a popup on click of Buy Now button.', 'smart-offers' ),
				),
				array(
					'name'     => __( '1-step or 2-step?', 'smart-offers' ),
					'desc'     => __( 'Respect Amazon\'s 1-Click patent', 'smart-offers' ),
					'id'       => 'wc_buy_now_is_two_click',
					'type'     => 'checkbox',
					'default'  => 'no',
					'desc_tip' => __( 'Enable this option to use 2-Click instead of 1-Click purchase. This option is only for "Buy Now" button.', 'smart-offers' ),
				),
				array(
					'type' => 'sectionend',
					'id'   => 'wc_buy_now_option',
				),
			);

			// Footer styles & scripts.
			do_action( 'sa_wc_buy_now_enhanced_select_script_end' );

			return apply_filters( 'sa_wc_buy_now_settings', $buy_now_settings, $this );
		}

		/**
		 * Function to display heading for Buy Now storewide actions
		 *
		 * @param array $value The values to create element.
		 */
		public function sa_bn_full_row_text( $value = array() ) {
			?>
			<tr valign="top">
				<td colspan="2" style="<?php echo ( ! empty( $value['css'] ) ) ? esc_attr( $value['css'] ) : ''; ?>" class="<?php echo ( ! empty( $value['class'] ) ) ? esc_attr( $value['class'] ) : ''; ?>">
					<label><?php echo ( ! empty( $value['name'] ) ) ? esc_html( $value['name'] ) : ''; ?> <?php echo wc_help_tip( esc_html( $value['desc'] ) ); // phpcs:ignore ?></label>
				</td>
			</tr>
			<?php
		}

		/**
		 * Function to save changes made in storewide settings
		 */
		public function bn_save_storewide_settings() {
			$get_post_type = ( ! empty( $_GET['post_type'] ) ) ? wc_clean( wp_unslash( $_GET['post_type'] ) ) : ''; // phpcs:ignore
			$get_tab       = ( ! empty( $_GET['tab'] ) ) ? wc_clean( wp_unslash( $_GET['tab'] ) ) : ''; // phpcs:ignore

			if ( 'smart_offers' === $get_post_type && 'bn_storewide_settings' === $get_tab && ( empty( $_POST['bn_security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['bn_security'] ) ), 'sa_wc_bn_storewide_settings' ) ) ) { // phpcs:ignore
				return;
			}

			$updated = WC_Admin_Settings::save_fields( $this->get_bn_storewide_settings() );

			if ( $updated ) {
				$this->bn_add_message( 'success', __( 'Your settings have been saved.', 'smart-offers' ) );
			} else {
				$this->bn_add_message( 'error', __( 'Oops, unable to update.', 'smart-offers' ) );
			}
		}

		/**
		 * Function show message on saving changes
		 *
		 * @param  string $type  Message type ( error, info, warning, succcess ).
		 * @param  array  $message Message to show.
		 */
		public function bn_add_message( $type = '', $message = '' ) {
			if ( ! empty( $type ) && ! empty( $message ) ) {
				?>
				<div class="notice notice-<?php echo esc_attr( $type ); ?> is-dismissible">
					<p>
						<strong> <?php echo esc_html( $message ); ?> </strong>
					</p>
				</div>
				<?php
			}
		}

	}
}

