<?php // phpcs:ignore WordPress.Files.FileName
/**
 * This file mange the functions
 *
 * @package YITH\AccountFunds\Functions
 */

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

if ( ! function_exists( 'ywf_get_min_fund_rechargeable' ) ) {

	/**
	 * Returns the minimum rechargeable funds
	 *
	 * @return float
	 * @since 1.0.0
	 * @author YITH <plugins@yithemes.com>
	 */
	function ywf_get_min_fund_rechargeable() {

		$min_rech = get_option( 'yith_funds_min_value' );
		$min_rech = empty( $min_rech ) ? 0 : $min_rech;

		return apply_filters( 'yith_min_deposit', $min_rech );
	}
}


if ( ! function_exists( 'ywf_get_max_fund_rechargeable' ) ) {
	/**
	 * Returns the maximum  rechargeable funds
	 *
	 * @return bool|float
	 * @since 1.0.0
	 */
	function ywf_get_max_fund_rechargeable() {

		$max_rech = get_option( 'yith_funds_max_value' );
		$max_rech = empty( $max_rech ) ? '' : $max_rech;

		return apply_filters( 'yith_max_deposit', $max_rech );
	}
}

if ( ! function_exists( 'ywf_enable_discount' ) ) {
	/**
	 * Check if is enable discount
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	function ywf_enable_discount() {

		$enable_discount = get_option( 'yith_discount_enable_discount' );

		return apply_filters( 'ywf_enable_discount', 'yes' === $enable_discount );

	}
}

if ( ! function_exists( 'ywf_get_discount_type' ) ) {
	/**
	 * Get the discount type
	 *
	 * @return string
	 * @since 1.0.0
	 */
	function ywf_get_discount_type() {

		$discount= get_option( 'yith_discount_configuration' );

		return $discount['discount_type'] === 'percentage' ? 'percent' : 'fixed_cart';
	}
}

if ( ! function_exists( 'ywf_get_discount_value' ) ) {

	/**
	 * Get the discount value
	 *
	 * @return string
	 * @since 1.0.0
	 */
	function ywf_get_discount_value() {

		$discount = get_option( 'yith_discount_configuration' );

		return wc_format_decimal( $discount['discount_value'] );
	}
}

if ( ! function_exists( 'ywf_partial_payment_enabled' ) ) {
	/**
	 * Check if partial payment is enabled
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	function ywf_partial_payment_enabled() {

		$partial_payment = get_option( 'yith_enable_partial_payment', 'no' );

		return 'yes' === $partial_payment;
	}
}

if ( ! function_exists( 'ywf_get_fund_endpoint_name' ) ) {
	/**
	 * Get the endpoint title
	 *
	 * @param string $endpoint_id The endpoint id.
	 *
	 * @return string
	 * @since 1.0.0
	 */
	function ywf_get_fund_endpoint_name( $endpoint_id ) {

		return yith_account_funds_get_endpoint_title( $endpoint_id );
	}
}


if ( ! function_exists( 'ywf_order_has_deposit' ) ) {
	/**
	 * Check if order is a deposit
	 *
	 * @param WC_Order $order The order.
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	function ywf_order_has_deposit( $order ) {
		$has_deposit = 'yes' === $order->get_meta( '_order_has_deposit' );

		return apply_filters( 'ywf_order_has_deposit', $has_deposit, $order );

	}
}

if ( ! function_exists( 'ywf_get_endpoint_url' ) ) {

	/**
	 * Return the endpoint url
	 *
	 * @param string $type The endpoint type.
	 * @param array  $args The args.
	 *
	 * @return string
	 * @since 1.0.0
	 */
	function ywf_get_endpoint_url( $type, $args = array() ) {

		$endpoint = yith_account_funds_get_endpoint_slug( $type );

		if ( count( $args ) > 0 ) {
			$url = esc_url( add_query_arg( $args, wc_get_page_permalink( 'myaccount' ) . $endpoint ) );
		} else {
			$url = esc_url( wc_get_page_permalink( 'myaccount' ) . $endpoint );
		}

		return apply_filters( 'ywf_get_endpoint_url', $url, $type, $args );
	}
}

if ( ! function_exists( 'ywf_get_customize_my_account_menu' ) ) {
	/**
	 * Integration with customize my account page
	 *
	 * @return string
	 * @since 1.0.0
	 */
	function ywf_get_customize_my_account_menu() {

		$position = get_option( 'yith-wcmap-menu-position', 'left' );
		$tab      = 'tab' === get_option( 'yith-wcmap-menu-style', 'sidebar' ) ? '-tab' : '';
		$menu     = '<div id="my-account-menu' . esc_attr( $tab ) . '" class="yith-wcmap position-' . esc_attr( $position ) . '">' . YITH_WCMAP_Frontend()->my_account_menu() . '</div>';

		return $menu;
	}
}


if ( ! function_exists( 'ywf_get_gateway' ) ) {

	/**
	 * Get all gateways
	 *
	 * @return array
	 * @since 1.0.0
	 */
	function ywf_get_gateway() {
		$payment  = WC()->payment_gateways->payment_gateways();
		$gateways = array();
		foreach ( $payment as $gateway ) {
			if ( 'yes' === $gateway->enabled && 'yith_funds' !== $gateway->id ) {
				$gateways[ $gateway->id ] = $gateway->title;
			}
		}

		return $gateways;
	}
}

if ( ! function_exists( 'ywf_get_user_currency' ) ) {
	/**
	 * Get user currency
	 *
	 * @param int $user_id The user id.
	 *
	 * @return int|WP_Post
	 * @since 1.0.0
	 */
	function ywf_get_user_currency( $user_id ) {

		$args = array(
			'numberposts' => 1,
			'suppress_filters' => true,
			'meta_query'  => array( // phpcs:ignore WordPress.DB.SlowDBQuery
				array(
					'key'     => '_customer_user',
					'value'   => $user_id,
					'compare' => '=',
					'type'    => 'numeric',
				),
				array(
					'key'     => '_order_has_deposit',
					'value'   => 'yes',
					'compare' => 'LIKE',
				),

			),
			'post_type'   => 'shop_order',
			'post_status' => 'wc-completed',
			'fields'      => 'ids',
		);

		$order_id = get_posts( $args );

		return isset( $order_id[0] ) ? $order_id[0] : - 1;
	}
}

if ( ! function_exists( 'ywf_get_date_created_order' ) ) {
	/**
	 * Get the order date
	 *
	 * @param WC_Order $order The order.
	 * @param string   $context The context.
	 *
	 * @return WC_DateTime
	 */
	function ywf_get_date_created_order( $order, $context = 'view' ) {

		global $YITH_FUNDS; // phpcs:ignore WordPress.NamingConventions.ValidVariableName

		$order_date = '';
		if ( $YITH_FUNDS->is_wc_2_7 ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName
			$order_date = $order->get_date_created( $context );

		} else {

			$order_date = $order->post->post_date;
		}

		return $order_date;
	}
}

if ( ! function_exists( 'ywf_get_operation_type' ) ) {

	/**
	 * Return the operation type
	 *
	 * @return array
	 * @since 1.0.0
	 */
	function ywf_get_operation_type() {

		$operation_types = array(

			'deposit'  => __( 'Deposit', 'yith-woocommerce-account-funds' ),
			'pay'      => __( 'Payment', 'yith-woocommerce-account-funds' ),
			'admin_op' => __( 'Admin activity', 'yith-woocommerce-account-funds' ),
			'restore'  => __( 'Funds restored', 'yith-woocommerce-account-funds' ),
			'remove'   => __( 'Funds refunded', 'yith-woocommerce-account-funds' ),
		);

		return apply_filters( 'ywf_operation_type', $operation_types );
	}
}

if ( ! function_exists( 'ywf_check_if_can_send_email' ) ) {

	/**
	 * Check if is possible send the email
	 *
	 * @param bool $send_email Can send email.
	 * @param int  $user_id The user id.
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	function ywf_check_if_can_send_email( $send_email, $user_id ) {

		$show_checkbox = get_option( 'ywf_user_privacy', 'no' );

		if ( 'yes' === $show_checkbox ) {

			$user_meta = get_user_meta( $user_id, '_ywf_agree_to_send_email', true );

			if ( ! $user_meta ) {
				$send_email = false;
			}
		}

		return $send_email;
	}

	add_filter( 'ywf_send_email', 'ywf_check_if_can_send_email', 10, 2 );
}

if ( ! function_exists( 'ywf_update_db_1_0_1' ) ) {
	/**
	 * Update the db to version 1.0.1
	 *
	 * @since 1.0.1
	 */
	function ywf_update_db_1_0_1() {

		$fund_db_option = get_option( 'ywf_dbversion', '1.0.0' );

		if ( $fund_db_option && version_compare( $fund_db_option, '1.0.1', '<' ) ) {

			global $wpdb;

			$sql = "ALTER TABLE {$wpdb->prefix}ywf_user_fund_log ADD `editor_id` INT NOT NULL AFTER `user_id`";
			$wpdb->query( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared

			update_option( 'ywf_dbversion', '1.0.1' );
		}
	}

	add_action( 'admin_init', 'ywf_update_db_1_0_1' );
}

add_action( 'woocommerce_pre_payment_complete', 'yith_account_funds_clear_session' );
add_action( 'woocommerce_cart_emptied', 'yith_account_funds_clear_session' );
if ( ! function_exists( 'yith_account_funds_clear_session' ) ) {
	/**
	 * Clear sessions
	 *
	 * @since 1.0.0
	 */
	function yith_account_funds_clear_session() {

		if ( ! is_null( WC()->session ) ) {

			WC()->session->set( 'ywf_fund_used', false );
			WC()->session->set( 'ywf_partial_payment', 'no' );
			WC()->session->set( 'deposit_amount', false );
			WC()->session->set( 'ywf_order_awaiting_partial_payment', false );
			WC()->session->set( 'yith_remain_funds', 0 );
			delete_transient( 'ywf_partial_payment' );
			delete_transient( 'ywf_fund_used' );
			if ( function_exists( 'wc_clear_notices' ) ) {
				wc_clear_notices();
			}
		}
	}
}

if ( ! function_exists( 'yith_account_funds_get_partial_coupon_code' ) ) {
	/**
	 * Get the coupon code
	 *
	 * @return string
	 */
	function yith_account_funds_get_partial_coupon_code() {
		$user_id = get_current_user_id();

		return apply_filters( 'yith_partial_coupon_code', 'yith_partial_coupon_' . $user_id, $user_id );
	}
}


if ( ! function_exists( 'yith_account_funds_get_endpoint_slug' ) ) {
	/**
	 * Get the endpoint slug
	 *
	 * @param string $endpoint The endpoint.
	 *
	 * @return string the right endpoint slug
	 */
	function yith_account_funds_get_endpoint_slug( $endpoint ) {

		$is_customize_active = defined( 'YITH_WCMAP_PREMIUM' ) && YITH_WCMAP_PREMIUM;

		$account_funds_endpoint = array( 'funds' );
		$slug                   = '';
		if ( in_array( $endpoint, $account_funds_endpoint, true ) ) {

			if ( 'funds' === $endpoint ) {
				$option_slug_name = 'funds_endpoint';
			} else {
				$option_slug_name = str_replace( '-', '_', $endpoint );
			}
			$slug = get_option( 'ywf_' . $option_slug_name . '_slug', $endpoint );

			if ( $is_customize_active ) {
				$option_slug_name = str_replace( '-', '_', $endpoint );
				$slug             = get_option( 'woocommerce_myaccount_' . $option_slug_name . '_endpoint', $endpoint );
			}
		}

		return $slug;
	}
}

if ( ! function_exists( 'yith_account_funds_get_endpoint_title' ) ) {
	/**
	 * Get the endpoint title
	 *
	 * @param string $endpoint The endpoint.
	 *
	 * @return string
	 * @since 1.0.0
	 */
	function yith_account_funds_get_endpoint_title( $endpoint ) {

		$account_funds_endpoint = array( 'funds' );

		$title = '';
		if ( in_array( $endpoint, $account_funds_endpoint, true ) ) {
			if ( 'funds' === $endpoint ) {
				$option_slug_name = 'funds_endpoint';
			} else {
				$option_slug_name = str_replace( '-', '_', $endpoint );
			}

			$default_title = _x( 'Funds', 'Endpoint title visible on My Account page', 'yith-woocommerce-account-funds' );

			$title = get_option( 'ywf_' . $option_slug_name, $default_title );
		}

		return $title;
	}
}


if ( ! function_exists( 'ywf_update_db_1_0_2' ) ) {
	/**
	 * Update the db to version 1.0.2
	 *
	 * @since 2.0.0
	 */
	function ywf_update_db_1_0_2() {

		$fund_db_option = get_option( 'ywf_dbversion', '1.0.1' );

		if ( $fund_db_option && version_compare( $fund_db_option, '1.0.2', '<' ) ) {

			$can_make_deposit = get_option( 'ywf_vendor_can_charge', 'no' );
			$can_use_funds    = get_option( 'ywf_vendor_can_use', 'no' );
			$can_redeem       = get_option( 'ywf_vendor_can_redeem', 'no' );

			$old_endpoints = get_option( 'ywf_make_a_deposit_slug', false );
			if ( 'yes' === $can_redeem || 'yes' === $can_use_funds || 'yes' === $can_make_deposit ) {
				$modules = array(
					'multi-vendor'
				);
				update_option( 'yith_funds_modules_active', $modules );
			}

			if ( $old_endpoints ) {
				$new_opt = array(
					'balance',
					'add_funds',
					'history'
				);
				update_option( 'yith_funds_dashboard_content', $new_opt );
			}

			// emails
			$old_email_enabled        = get_option( 'ywf_mail_enabled', false );
			$old_edit_email_enabled   = get_option( 'ywf_mail_admin_change_fund_enabled', false );
			$old_redeem_email_enabled = get_option( 'ywf_redeem_email_enabled', false );
			if ( $old_email_enabled ) {
				$limit    = get_option( 'ywf_email_limit' );
				$subject  = get_option( 'ywf_mail_subject' );
				$heading  = get_option( 'ywf_user_heading' );
				$message  = get_option( 'ywf_mail_content' );
				$type     = get_option( 'ywf_mail_type' );
				$new_args = array(
					'enabled'           => $old_email_enabled,
					'mail_amount_limit' => $limit,
					'subject'           => $subject,
					'heading'           => $heading,
					'custom_message'    => $message,
					'email_type'        => $type

				);
				update_option( 'woocommerce_yith_user_funds_email_settings', $new_args );
			}
			if ( $old_edit_email_enabled ) {
				$subject  = get_option( 'ywf_mail_admin_change_fund_subject' );
				$heading  = get_option( 'ywf_user_change_fund_heading' );
				$message  = get_option( 'ywf_mail_change_fund_content' );
				$type     = get_option( 'ywf_mail_admin_change_fund_type' );
				$new_args = array(
					'enabled'        => $old_edit_email_enabled,
					'subject'        => $subject,
					'heading'        => $heading,
					'custom_message' => $message,
					'email_type'     => $type

				);
				update_option( 'woocommerce_yith_advise_user_funds_email_settings', $new_args );
			}
			if ( $old_redeem_email_enabled ) {
				$subject   = get_option( 'ywf_redeem_email_subject' );
				$recipient = get_option( 'ywf_redeem_email_recipient' );
				$heading   = get_option( 'ywf_redeem_email_heading' );
				$type      = get_option( 'ywf_redeem_email_type' );
				$new_args  = array(
					'enabled'                => $old_edit_email_enabled,
					'subject'                => $subject,
					'heading'                => $heading,
					'custom_message'         => '',
					'email_type'             => $type,
					'redeem_email_recipient' => $recipient

				);
				update_option( 'woocommerce_ywf_vendor_redeem_email_settings', $new_args );
			}

			//old price discount

			$old_discount_type = get_option( 'yith_discount_type_discount' );
			if( $old_discount_type ){
				$old_discount_value = get_option( 'yith_discount_value' );
				$discount_args = array(
					'discount_type' => $old_discount_type,
					'discount_value' => $old_discount_value
				);

				update_option( 'yith_discount_configuration', $discount_args );
			}
			update_option( 'ywf_dbversion', '1.0.2' );
		}
	}

	add_action( 'admin_init', 'ywf_update_db_1_0_2' );
}

if ( ! function_exists( 'yith_funds_upload_product_image' ) ) {
	function yith_funds_upload_product_image() {

		$image_url = YITH_FUNDS_ASSETS_URL . '/images/deposit.png';

		$tmp_image = download_url( $image_url );
		if ( is_wp_error( $tmp_image ) ) {
			return false;
		}

		$file     = array(
			'name'     => basename( $image_url ),
			'type'     => mime_content_type( $tmp_image ),
			'tmp_name' => $tmp_image,
			'size'     => filesize( $tmp_image ),
		);
		$sideload = wp_handle_sideload(
			$file,
			array(
				'test_form' => false // no needs to check 'action' parameter
			)
		);

		if ( ! empty( $sideload['error'] ) ) {
			// you may return error message if you want
			return false;
		}

		// it is time to add our uploaded image into WordPress media library
		$attachment_id = wp_insert_attachment(
			array(
				'guid'           => $sideload['url'],
				'post_mime_type' => $sideload['type'],
				'post_title'     => basename( $sideload['file'] ),
				'post_content'   => '',
				'post_status'    => 'inherit',
			),
			$sideload['file']
		);

		if ( is_wp_error( $attachment_id ) || ! $attachment_id ) {
			return false;
		}

		// update medatata, regenerate image sizes

		wp_update_attachment_metadata(
			$attachment_id,
			wp_generate_attachment_metadata( $attachment_id, $sideload['file'] )
		);

		return $attachment_id;

	}
}

/**
 * Get fictitious data for preview and test emails
 *
 * @param string $email_id The email ID.
 * @param string $email The email address to use.
 *
 * @return array
 * @since  2.0.0
 */
function yith_ywf_get_test_values( string $email_id, string $email = '' ): array {

	global $sitepress;

	$lang = $sitepress ? $sitepress->get_current_language() : '';

	$shared = array(
		'user'     => array(
			'customer_name'      => wp_get_current_user()->get( 'billing_first_name' ),
			'customer_last_name' => wp_get_current_user()->get( 'billing_last_name' ),
			'customer_email'     => $email ? $email : wp_get_current_user()->get( 'billing_email' ),
			'user_id'            => wp_get_current_user()->ID,
		),
		'language' => $lang,
	);

	switch ( $email_id ) {
		case 'yith_user_funds_email':
			$data = array(
				'user_funds' => array(
					'funds_formatted' => wc_price( wp_get_current_user()->get( '_customer_fund' ) ),
					'funds'           => wp_get_current_user()->get( '_customer_fund' )
				)
			);
			break;
		case  'yith_advise_user_funds_email':
			$data = array(
				'user_funds' => array(
					'before_funds_formatted' => wc_price( 5 ),
					'after_funds_formatted'  => wc_price( 10 ),
					'change_reason'          => _x( 'An extra for you!', '[ADMIN Test email]', 'yith-woocommerce-account-funds' ),
					'log_date'               => date_i18n( wc_date_format(), gmdate( wc_date_format() ) ),
				)
			);
			break;
		default:
			$data = apply_filters( 'ywf_test_email_args', array(), $email_id );
			break;
	}

	return $shared + $data;
}


/**
 * Prune preview email content from unnecessary tags
 *
 * @param string $content The email content.
 *
 * @return string
 * @since  2.0.0
 */
function yith_ywf_prune_preview_email_content( string $content ): string {
	$content       = preg_replace( '/<title>(.*)<\/title>/i', '', $content );
	$content       = preg_replace( '/<yith-wccet-style type\=\"text\/css\">(\n.*)*<\/yith-wccet-style>\n/im', '', $content );
	$content       = preg_replace( '/<!--\[if gte mso 9\]>(.*)<!\[endif\]-->/im', '', $content );
	$content       = preg_replace( '/<!--\[if !gte mso 9\]>-->\n(.*)\n<!--<!\[endif\]-->/im', '', $content );
	$tags_to_strip = array( 'body', 'html', 'head', 'meta', '!DOCTYPE' );
	foreach ( $tags_to_strip as $html_tag ) {
		$content = preg_replace( "/<\\/?$html_tag(.|\\s)*?>/", '', $content );
	}

	return $content;
}