<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! defined( 'DROP_PRINT_PRO_NOTICE_SNOOZE_DAYS' ) ) {
	define( 'DROP_PRINT_PRO_NOTICE_SNOOZE_DAYS', 14 );
}
if ( ! defined( 'DROP_PRINT_PRO_OFFER_REFRESH_HOURS' ) ) {
	define( 'DROP_PRINT_PRO_OFFER_REFRESH_HOURS', 12 );
}
if ( ! defined( 'DROP_PRINT_PRO_NOTICE_DISMISSED_META' ) ) {
	define( 'DROP_PRINT_PRO_NOTICE_DISMISSED_META', 'drop_print_pro_notice_dismissed_at' );
}
if ( ! function_exists( 'drop_print_show_pro_upsell_notices' ) ) {
	function drop_print_show_pro_upsell_notices(): bool {
		return (bool) apply_filters( 'drop_print_show_pro_upsell_notices', false );
	}
}
if ( ! function_exists( 'drop_print_get_pro_upsell_notice_surface' ) ) {
	function drop_print_get_pro_upsell_notice_surface(): string {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return '';
		}
		$screen = get_current_screen();
		if ( ! $screen ) {
			return '';
		}
		$is_hpos_orders_screen = ( 'woocommerce_page_wc-orders' === $screen->id );
		$hpos_action           = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : '';
		if ( 'edit-product' === $screen->id ) {
			return 'products_list_notice';
		}
		if ( 'product' === $screen->id && 'post' === $screen->base ) {
			return 'product_edit_notice';
		}
		if ( 'edit-shop_order' === $screen->id || ( $is_hpos_orders_screen && 'edit' !== $hpos_action ) ) {
			return 'orders_list_notice';
		}
		if ( ( 'shop_order' === $screen->id && 'post' === $screen->base ) || ( $is_hpos_orders_screen && 'edit' === $hpos_action ) ) {
			return 'order_edit_notice';
		}
		if ( 'toplevel_page_drop-print-settings' === $screen->id ) {
			return 'settings_notice';
		}
		return '';
	}
}
if ( ! function_exists( 'drop_print_current_order_has_drop_print_item' ) ) {
	function drop_print_current_order_has_drop_print_item(): bool {
		if ( ! function_exists( 'wc_get_order' ) ) {
			return false;
		}
		$order_id = 0;
		if ( isset( $_GET['id'] ) ) {
			$order_id = absint( wp_unslash( $_GET['id'] ) );
		} elseif ( isset( $_GET['post'] ) ) {
			$order_id = absint( wp_unslash( $_GET['post'] ) );
		}
		if ( $order_id <= 0 ) {
			return false;
		}
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return false;
		}
		foreach ( $order->get_items() as $item ) {
			if ( ! ( $item instanceof WC_Order_Item_Product ) ) {
				continue;
			}
			$product_id_for_meta = $item->get_product_id();
			$product_obj         = wc_get_product( $product_id_for_meta );
			if ( $product_obj && $product_obj->is_type( 'variation' ) ) {
				$product_id_for_meta = $product_obj->get_parent_id();
			}
			$drop_print_meta = get_post_meta( $product_id_for_meta, '_drop_print_meta', true );
			if ( is_array( $drop_print_meta ) && ! empty( $drop_print_meta['file'] ) ) {
				return true;
			}
		}
		return false;
	}
}
if ( ! function_exists( 'drop_print_get_pro_upsell_offer_snapshot' ) ) {
	function drop_print_get_pro_upsell_offer_snapshot( int $user_id ): array {
		$settings = function_exists( 'drop_print_get_user_settings' ) ? drop_print_get_user_settings( $user_id ) : array();
		$snapshot = isset( $settings['pro_account_state_snapshot'] ) && is_array( $settings['pro_account_state_snapshot'] ) ? $settings['pro_account_state_snapshot'] : array();
		$offer    = isset( $snapshot['upgrade_offer'] ) && is_array( $snapshot['upgrade_offer'] ) ? $snapshot['upgrade_offer'] : array();
		$lock_key = 'drop_print_offer_refresh_' . $user_id;
		if ( get_transient( $lock_key ) ) {
			return $offer;
		}
		set_transient( $lock_key, 1, DROP_PRINT_PRO_OFFER_REFRESH_HOURS * HOUR_IN_SECONDS );
		if ( ! function_exists( 'drop_print_make_server_request_for_ajax' ) || ! function_exists( 'drop_print_extract_pro_upgrade_account_state' ) ) {
			return $offer;
		}
		$api_response = drop_print_make_server_request_for_ajax( 'account-state', array( 'client_wp_user_id' => $user_id ), 'POST', 8 );
		if ( is_wp_error( $api_response ) || ! is_array( $api_response ) ) {
			return $offer;
		}
		$account_state = drop_print_extract_pro_upgrade_account_state( $api_response );
		if ( ! empty( $account_state ) && isset( $account_state['is_pro'] ) && function_exists( 'drop_print_store_pro_upgrade_account_state_snapshot' ) ) {
			drop_print_store_pro_upgrade_account_state_snapshot( $user_id, $account_state );
			if ( isset( $account_state['upgrade_offer'] ) && is_array( $account_state['upgrade_offer'] ) ) {
				return $account_state['upgrade_offer'];
			}
		}
		return $offer;
	}
}
if ( ! function_exists( 'drop_print_has_any_container_file' ) ) {
	function drop_print_has_any_container_file(): bool {
		if ( ! function_exists( 'drop_print_files_get_index' ) ) {
			return true;
		}
		$index = drop_print_files_get_index();
		return isset( $index['files'] ) && is_array( $index['files'] ) && ! empty( $index['files'] );
	}
}
if ( ! function_exists( 'drop_print_render_pro_upsell_notice' ) ) {
	function drop_print_render_pro_upsell_notice(): void {
		if ( ! drop_print_show_pro_upsell_notices() ) {
			return;
		}
		if ( ! function_exists( 'drop_print_user_can_use_pro_upgrade_workflow' ) || ! drop_print_user_can_use_pro_upgrade_workflow() ) {
			return;
		}
		$surface = drop_print_get_pro_upsell_notice_surface();
		if ( '' === $surface ) {
			return;
		}
		$user_id  = get_current_user_id();
		$settings = function_exists( 'drop_print_get_user_settings' ) ? drop_print_get_user_settings( $user_id ) : array();
		if ( empty( $settings['client_user_connection_id'] ) || ! empty( $settings['pro_status'] ) ) {
			return;
		}
		if ( ! drop_print_has_any_container_file() ) {
			return;
		}
		$dismissed_at = absint( get_user_meta( $user_id, DROP_PRINT_PRO_NOTICE_DISMISSED_META, true ) );
		if ( $dismissed_at > 0 && ( time() - $dismissed_at ) < ( DROP_PRINT_PRO_NOTICE_SNOOZE_DAYS * DAY_IN_SECONDS ) ) {
			return;
		}
		if ( 'order_edit_notice' === $surface && ! drop_print_current_order_has_drop_print_item() ) {
			return;
		}
		$offer           = drop_print_get_pro_upsell_offer_snapshot( $user_id );
		$has_spent_money = ! empty( $offer['has_spent_money'] );
		$savings_amount  = isset( $offer['estimated_savings'] ) ? (float) $offer['estimated_savings'] : 0.0;
		$savings_currency = ! empty( $offer['savings_currency'] ) ? strtoupper( (string) $offer['savings_currency'] ) : strtoupper( (string) ( $settings['billing_currency'] ?? '' ) );
		$savings_percent = isset( $offer['savings_percent'] ) ? (float) $offer['savings_percent'] : 25.0;
		$trial_days      = isset( $offer['trial_offer']['days'] ) ? (int) $offer['trial_offer']['days'] : 30;
		$coupon_code     = isset( $offer['coupon_code'] ) ? (string) $offer['coupon_code'] : '';
		$intro_price     = isset( $offer['intro_price'] ) ? (float) $offer['intro_price'] : 0.0;
		$intro_months    = isset( $offer['intro_months'] ) ? (int) $offer['intro_months'] : 3;
		if ( $has_spent_money && $savings_amount > 0 ) {
			$message = sprintf(
				esc_html__( 'You could have saved %1$s %2$s on your recent orders with Drop Print Pro.', 'drop-print' ),
				esc_html( number_format_i18n( $savings_amount, 2 ) ),
				esc_html( $savings_currency )
			);
			$button_label = sprintf(
				esc_html__( 'Try Drop Print Pro free for %d days', 'drop-print' ),
				$trial_days
			);
		} else {
			if ( $intro_price > 0 && '' !== $coupon_code ) {
				$message = sprintf(
					esc_html__( 'Save up to %1$s%% on every order with Drop Print Pro — try %2$d months for only %3$s %4$s/month with coupon %5$s.', 'drop-print' ),
					esc_html( number_format_i18n( $savings_percent ) ),
					$intro_months,
					esc_html( number_format_i18n( $intro_price, 2 ) ),
					esc_html( $savings_currency ),
					'<code>' . esc_html( $coupon_code ) . '</code>'
				);
			} else {
				$message = sprintf(
					esc_html__( 'Save up to %s%% on every order with Drop Print Pro.', 'drop-print' ),
					esc_html( number_format_i18n( $savings_percent ) )
				);
			}
			if ( $intro_price > 0 && '' !== $coupon_code ) {
				$button_label = sprintf(
					esc_html__( 'Try Drop Print Pro discounted for %d months', 'drop-print' ),
					$intro_months
				);
			} else {
				$button_label = sprintf(
					esc_html__( 'Try Drop Print Pro free for %d days', 'drop-print' ),
					$trial_days
				);
			}
		}
		$nonce = wp_create_nonce( 'drop_print_dismiss_pro_upsell_notice' );
		?>
		<div class="notice notice-info drop-print-pro-upsell-notice" data-dismiss-nonce="<?php echo esc_attr( $nonce ); ?>" style="display:flex; align-items:center; gap:14px; flex-wrap:wrap; padding:10px 14px;">
			<p style="margin:0; flex:1 1 320px;"><strong>Drop Print Pro</strong> — <?php echo wp_kses( $message, array( 'code' => array() ) ); ?></p>
			<p style="margin:0; display:flex; gap:10px; align-items:center;">
				<button type="button" class="button button-primary drop-print-pro-upgrade-launcher" data-upgrade-origin="<?php echo esc_attr( $surface ); ?>" data-upgrade-surface="<?php echo esc_attr( ucwords( str_replace( '_', ' ', $surface ) ) ); ?>"><?php echo esc_html( $button_label ); ?> &rarr;</button>
				<button type="button" class="button-link drop-print-pro-upsell-dismiss" style="color:#646970;"><?php esc_html_e( 'Maybe later', 'drop-print' ); ?></button>
			</p>
		</div>
		<script>
		(function($){
			$(function(){
				$(document).on('click', '.drop-print-pro-upsell-notice .drop-print-pro-upsell-dismiss, .drop-print-pro-upsell-notice .notice-dismiss', function(){
					var $notice = $(this).closest('.drop-print-pro-upsell-notice');
					$.post(ajaxurl, {
						action: 'drop_print_dismiss_pro_upsell_notice',
						nonce: $notice.data('dismiss-nonce')
					});
					$notice.slideUp(150);
				});
			});
		})(jQuery);
		</script>
		<?php
	}
}
add_action( 'admin_notices', 'drop_print_render_pro_upsell_notice' );
if ( ! function_exists( 'drop_print_dismiss_pro_upsell_notice_ajax_handler' ) ) {
	function drop_print_dismiss_pro_upsell_notice_ajax_handler() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'drop_print_dismiss_pro_upsell_notice' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'drop-print' ) ), 403 );
			return;
		}
		$user_id = get_current_user_id();
		if ( $user_id <= 0 ) {
			wp_send_json_error( array( 'message' => __( 'Not logged in.', 'drop-print' ) ), 403 );
			return;
		}
		update_user_meta( $user_id, DROP_PRINT_PRO_NOTICE_DISMISSED_META, time() );
		wp_send_json_success();
	}
}
add_action( 'wp_ajax_drop_print_dismiss_pro_upsell_notice', 'drop_print_dismiss_pro_upsell_notice_ajax_handler' );
if ( ! function_exists( 'drop_print_enqueue_pro_upgrade_assets_for_notices' ) ) {
	function drop_print_enqueue_pro_upgrade_assets_for_notices(): void {
		if ( ! drop_print_show_pro_upsell_notices() ) {
			return;
		}
		$surface = drop_print_get_pro_upsell_notice_surface();
		if ( '' === $surface || 'settings_notice' === $surface ) {
			return;
		}
		if ( ! function_exists( 'drop_print_user_can_use_pro_upgrade_workflow' ) || ! drop_print_user_can_use_pro_upgrade_workflow() ) {
			return;
		}
		$user_id  = get_current_user_id();
		$settings = function_exists( 'drop_print_get_user_settings' ) ? drop_print_get_user_settings( $user_id ) : array();
		if ( empty( $settings['client_user_connection_id'] ) ) {
			return;
		}
		if ( ! drop_print_has_any_container_file() ) {
			return;
		}
		if ( wp_script_is( 'drop-print-pro-upgrade-session', 'enqueued' ) ) {
			return;
		}
		$plugin_version = defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3';
		wp_enqueue_script(
			'drop-print-pro-unlock-animation',
			DROP_PRINT_PLUGIN_URL . 'assets/js/shared/drop-print-pro-unlock-animation.js',
			array( 'jquery' ),
			$plugin_version,
			true
		);
		wp_enqueue_script(
			'drop-print-pro-upgrade-session',
			DROP_PRINT_PLUGIN_URL . 'assets/js/shared/drop-print-pro-upgrade.js',
			array( 'jquery', 'drop-print-pro-unlock-animation' ),
			$plugin_version,
			true
		);
		wp_enqueue_style(
			'drop-print-pre-production-styles',
			DROP_PRINT_PLUGIN_URL . 'assets/css/production.css',
			array(),
			$plugin_version
		);
		$surface_labels = array(
			'products_list_notice' => __( 'Products', 'drop-print' ),
			'product_edit_notice'  => __( 'Product', 'drop-print' ),
			'orders_list_notice'   => __( 'Orders', 'drop-print' ),
			'order_edit_notice'    => __( 'Order', 'drop-print' ),
		);
		$surface_label = isset( $surface_labels[ $surface ] ) ? $surface_labels[ $surface ] : __( 'Drop Print', 'drop-print' );
		$config        = function_exists( 'drop_print_get_pro_upgrade_client_config' ) ? drop_print_get_pro_upgrade_client_config( $surface_label, $surface ) : array();
		wp_localize_script( 'drop-print-pro-upgrade-session', 'dropPrintProUpgradeData', $config );
	}
}
add_action( 'admin_enqueue_scripts', 'drop_print_enqueue_pro_upgrade_assets_for_notices', 20 );
