<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
/**
 * Class YITH_YWGC_Admin_Extended
 *
 * @package YITH\GiftCards\Includes\Admin
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

if ( ! class_exists( 'YITH_YWGC_Admin_Extended' ) ) {

	/**
	 *
	 * @class   YITH_YWGC_Admin_Extended
	 *
	 * @since   1.0.0
	 * @author  YITH <plugins@yithemes.com>
	 */
	class YITH_YWGC_Admin_Extended extends YITH_YWGC_Admin {

		/**
		 * Single instance of the class
		 *
		 * @since 1.0.0
		 */
		protected static $instance;

		/**
		 * Returns single instance of the class
		 *
		 * @since 1.0.0
		 */
		public static function get_instance() {
			if ( is_null( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Constructor
		 *
		 * Initialize plugin and registers actions and filters to be used
		 *
		 * @param  array $args the arguments
		 *
		 * @since  1.0
		 */
		public function __construct() {

			parent::__construct();

			add_filter( 'plugin_action_links_' . plugin_basename( YITH_YWGC_DIR . 'init.php' ), array( $this, 'action_links' ) );
			add_filter( 'yith_show_plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 5 );

			add_action( 'init', array( $this, 'create_gift_card_product_in_draft' ) );
			add_filter( 'removable_query_args', array( __CLASS__, 'removable_query_args' ), 10, 2 );

			add_action( 'woocommerce_admin_field_update-cron', array( $this, 'show_update_cron_field' ) );
		}

		/**
		 * show the custom woocommerce field
		 *
		 * @since 3.1.12
		 *
		 * @param array $option
		 */
		public function show_update_cron_field( $option ) {

			$option['option'] = $option;

			wc_get_template( '/admin/update-cron.php', $option, '', YITH_YWGC_TEMPLATES_DIR );
		}

		/**
		 * Retrieve the documentation URL.
		 *
		 * @return string
		 */
		protected function get_doc_url(): string {
			return 'https://www.bluehost.com/help/article/yith-woocommerce-gift-cards';
		}

		/**
		 * Add a panel under YITH Plugins tab
		 *
		 * @return   void
		 * @since    1.0
		 * @use      /Yit_Plugin_Panel class
		 * @see      plugin-fw/lib/yit-plugin-panel.php
		 */
		public function register_panel() {

			if ( ! empty( $this->panel ) ) {
				return;
			}

			$admin_tabs = $this->get_admin_panel_tabs();

			/**
			 * APPLY_FILTERS: yith_wcgc_plugin_settings_capability
			 *
			 * Filter the plugin settings capability.
			 *
			 * @param string the capability name. Default: manage_options
			 *
			 * @return string
			 */
			$capability = apply_filters( 'yith_wcgc_plugin_settings_capability', 'manage_options' );

			$premium_tab = array(
				'landing_page_url' => $this->get_premium_landing_uri(),
				'premium_features' => array(
					// Put here all the premium Features.
					__( 'Manage stock of each gift card product', 'yith-woocommerce-gift-cards' ),
					__( 'Enable an optional <strong>QR code</strong> in gift cards', 'yith-woocommerce-gift-cards' ),
					__( 'Import and export gift cards into a <strong>CSV file</strong>', 'yith-woocommerce-gift-cards' ),
					__( 'Allow users to <strong>enter a custom amount</strong> (and set the minimum and/or maximum amount)', 'yith-woocommerce-gift-cards' ),
					__( 'Allow users to <strong>upload a custom image or photo</strong> to customize the gift card', 'yith-woocommerce-gift-cards' ),
					__( 'Option to attach a PDF to gift card email', 'yith-woocommerce-gift-cards' ),
					__( 'Notify the sender via email when the gift card is delivered to recipient', 'yith-woocommerce-gift-cards' ),
					__( 'Enable the “Gift this product” option in product pages to sell gift cards linked to specific products', 'yith-woocommerce-gift-cards' ),
					'<b>' . __( 'Regular updates, Translations and Premium Support', 'yith-woocommerce-gift-cards' ) . '</b>',
				),
				'main_image_url'   => YITH_YWGC_ASSETS_URL . '/images/gift-cards-get-premium.jpeg', // Plugin main image should be in your plugin assets folder.
			);

			$args = array(
				'ui_version'       => 2,
				'create_menu_page' => true,
				'parent_slug'      => '',
				'page_title'       => 'YITH WooCommerce Gift Cards',
				'menu_title'       => 'Gift Cards',
				'capability'       => $capability,
				'parent'           => '',
				'class'            => yith_set_wrapper_class(),
				'parent_page'      => 'yit_plugin_panel',
				'page'             => $this->panel_page,
				'admin-tabs'       => $admin_tabs,
				'options-path'     => YITH_YWGC_DIR . 'plugin-options',
				'premium_tab'      => $premium_tab,
				'plugin_slug'      => YITH_YWGC_SLUG,
				'plugin_version'   => YITH_YWGC_VERSION,
				'plugin_icon'      => YITH_YWGC_ASSETS_URL . '/images/gift-card.svg',
				'is_free'          => defined( 'YITH_YWGC_FREE' ),
				'is_premium'       => defined( 'YITH_YWGC_PREMIUM' ),
				'is_extended'      => defined( 'YITH_YWGC_EXTENDED' ),
				'help_tab'         => array(
					'doc_url' => $this->get_doc_url(),
				),
				'welcome_modals'   => array(
					'show_in'  => 'panel',
					'on_close' => function () {
						update_option( 'yith-ywgc-welcome-modal', 'no' );
					},
					'modals'   => array(
						'welcome' => array(
							'type'        => 'welcome',
							'description' => __( 'With this plugin you can create different gift card products and allow your customers to send it to a friend or a loved one.', 'yith-woocommerce-gift-cards' ),
							'show'        => get_option( 'yith-ywgc-welcome-modal', 'welcome' ) === 'welcome',
							'items'       => array(
								'documentation'  => array(
									'url' => $this->get_doc_url(),
								),
								'create-product' => array(
									'title'       => __( 'Are you ready? Create your first <mark>gift card product</mark>', 'yith-woocommerce-gift-cards' ),
									'description' => __( '...and start the adventure!', 'yith-woocommerce-gift-cards' ),
									'url'         => add_query_arg(
										array(
											'yith-ywgc-new-gift-card-product' => 1,
										)
									),
								),
							),
						),
					),
				),
			);

			if ( ! class_exists( 'YIT_Plugin_Panel_WooCommerce' ) ) {
				require_once YITH_YWGC_DIR . 'plugin-fw/lib/yit-plugin-panel-wc.php';
			}

			$this->panel = new YIT_Plugin_Panel_WooCommerce( $args );

		}

		/**
		 * Action links
		 *
		 * @param mixed $links links.
		 *
		 * @return array|mixed
		 */
		public function action_links( $links ) {

			$links = yith_add_action_links( $links, $this->panel_page, defined( 'YITH_YWGC_PREMIUM' ), YITH_YWGC_SLUG );

			return $links;

		}

		/**
		 * Plugin Row Meta
		 *
		 * @param  mixed $new_row_meta_args new_row_meta_args.
		 * @param  mixed $plugin_meta plugin_meta.
		 * @param  mixed $plugin_file plugin_file.
		 * @param  mixed $plugin_data plugin_data.
		 * @param  mixed $status status.
		 * @param  mixed $init_file init_file.
		 *
		 * @return mixed
		 */
		public function plugin_row_meta( $new_row_meta_args, $plugin_meta, $plugin_file, $plugin_data, $status, $init_file = 'YITH_YWGC_INIT' ) {

			if ( defined( $init_file ) && constant( $init_file ) === $plugin_file ) {
				$new_row_meta_args['slug'] = YITH_YWGC_SLUG;
			}

			if ( defined( 'YITH_YWGC_FREE' ) ) {
				$new_row_meta_args['is_free'] = true;
			}

			if ( defined( 'YITH_YWGC_PREMIUM' ) ) {
				$new_row_meta_args['is_premium'] = true;
			}

			if ( defined( 'YITH_YWGC_EXTENDED' ) ) {
				$new_row_meta_args['is_extended'] = true;
			}

			return $new_row_meta_args;
		}

		/**
		 * Generate a Draft Gift Card product and redirect the customer to the edit page
		 *
		 * @return void
		 */
		public static function create_gift_card_product_in_draft() {

			if ( isset( $_GET['yith-ywgc-new-gift-card-product'] ) ) {//phpcs:ignore WordPress.Security.NonceVerification

				if ( class_exists( 'WC_Product_Gift_Card' ) ) {

					$args = array(
						'post_title'     => esc_html__( 'Gift Card', 'yith-woocommerce-gift-cards' ),
						'post_name'      => 'gift_card',
						'post_content'   => esc_html__( 'This product has been automatically created by the plugin YITH Gift Cards. It is in draft mode, so you can just edit this text, upload a custom image (if you have one) and then publish the product to start to sell your gift card.', 'yith-woocommerce-gift-cards' ),
						'post_status'    => 'draft',
						'post_date'      => date( 'Y-m-d H:i:s' ),
						'post_author'    => 0,
						'post_type'      => 'product',
						'comment_status' => 'closed',
					);

					$draft_gift_card_id = wp_insert_post( $args );

					$product = new WC_Product_Gift_Card( $draft_gift_card_id );

					if ( $product ) {
						$product->set_tax_status( 'none' );
						$product->set_virtual( true );
						$product->save_amounts( array( 10, 25, 50 ) );

						// upload the default gift card image to the Media Library and use it as the product image
						$file     = YITH_YWGC_ASSETS_IMAGES_URL . 'default-giftcard-main-image.jpg';
						$filename = basename( $file );

						$upload_file = wp_upload_bits( $filename, null, file_get_contents( $file ) );
						if ( ! $upload_file['error'] ) {
							$wp_filetype   = wp_check_filetype( $filename, null );
							$attachment    = array(
								'post_mime_type' => $wp_filetype['type'],
								'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
								'post_content'   => '',
								'post_status'    => 'inherit',
							);
							$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'] );
							if ( ! is_wp_error( $attachment_id ) ) {
								require_once ABSPATH . 'wp-admin' . '/includes/image.php';
								$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
								wp_update_attachment_metadata( $attachment_id, $attachment_data );

								set_post_thumbnail( $product->get_id(), $attachment_id );
							}
						}

						$product->save();

						wp_redirect( get_edit_post_link( $product->get_id(), 'edit' ) );

					}
				}
			}
		}

		/**
		 * Handle removable query args.
		 *
		 * @param array $args Query args to be removed.
		 *
		 * @return array
		 * @since 4.0.0
		 */
		public static function removable_query_args( $args ) {
			$args[] = 'yith-ywgc-new-gift-card-product';

			return $args;
		}

	}
}
