<?php



/**
 * Dashboard page - V2 WordPress Native
 * This redirects to our new V2 dashboard
 */
function seedprod_pro_dashboard_page() {
	// Load the V2 dashboard directly
	require_once SEEDPROD_PRO_PLUGIN_PATH . 'admin/partials/seedprod-admin-dashboard.php';
}

/**
 * Builder page.
 */
function seedprod_pro_builder_page() {
	require_once SEEDPROD_PRO_PLUGIN_PATH . 'resources/views/builder.php';
}



/* Short circuit new request */

add_action( 'admin_init', 'seedprod_pro_new_lpage', 1 );



/**
 * Preview Shortcode
 */
function seedprod_pro_render_shortcode() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}
		if ( ! empty( $_POST['shortcode'] ) ) {
			$shortcode = sanitize_text_field( wp_unslash( $_POST['shortcode'] ) );

			do_action( 'wp_print_footer_scripts' );
			do_action( 'wp_footer' );
			$content = do_shortcode( $shortcode );
			// $content = do_shortcode( $content );
			echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}

		exit();
	}
	exit;
}


/**
 * Preview Template tag
 */
function seedprod_pro_render_templatetag() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		$content = '';

		// Get input data.
		$render_scripts = sanitize_text_field( wp_unslash( $_POST['renderscripts'] ) );

		if ( ! isset( $render_scripts ) || empty( $render_scripts ) ) {
			$render_scripts = 'true';
		}

		if ( ! empty( $_POST['templatetag'] ) ) {
			$templatetag = sanitize_text_field( wp_unslash( $_POST['templatetag'] ) );

			$args      = array(
				'posts_per_page' => 1,
				'post_type'      => 'post',
			);
			$the_query = new WP_Query( $args );

			// The Loop
			if ( $the_query->have_posts() ) {
				while ( $the_query->have_posts() ) {
					$the_query->the_post();
					$content = do_shortcode( $templatetag );
				}
			}

			/* Restore original Post Data */
			wp_reset_postdata();

			if ( ! empty( $content ) && 'true' === $render_scripts ) {
				do_action( 'wp_print_footer_scripts' );
				do_action( 'wp_footer' );
			}
		}

		echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

		exit();
	}
	exit;
}

/**
 * Preview WC Template Tags.
 */
function seedprod_pro_render_wc_template_tags() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			return;
		}

		// Check if the WC Instance exists.
		if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
			return;
		}

		$content = '';
		if ( ! empty( $_POST['wc_template_tag'] ) ) {
			$wc_template_tag = sanitize_text_field( wp_unslash( $_POST['wc_template_tag'] ) );

			$args = array(
				'posts_per_page' => 1,
				'post_type'      => 'product',
			);

			// Updating current query.
			$the_query = new WP_Query( $args );

			// The Loop
			if ( $the_query->have_posts() ) {
				while ( $the_query->have_posts() ) {
					$the_query->the_post();

					$id      = get_the_ID();
					$product = wc_get_product( $id );

					if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
						return '';
					}

					$content = do_shortcode( $wc_template_tag );
				}
			}

			/* Restore original Post Data */
			wp_reset_postdata();

			if ( ! empty( $content ) ) {
				do_action( 'wp_print_footer_scripts' );
				do_action( 'wp_footer' );
			}
		}

		echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

		exit();
	}
	exit;
}

/**
 * Preview EDD Template Tags.
 */
function seedprod_pro_render_edd_template_tags() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			return;
		}

		// Check if the EDD Instance exists.
		if ( ! in_array( 'easy-digital-downloads/easy-digital-downloads.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) && ! in_array( 'easy-digital-downloads-pro/easy-digital-downloads.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
			return;
		}

		$content = '';
		if ( ! empty( $_POST['edd_template_tag'] ) ) {
			$edd_template_tag = sanitize_text_field( wp_unslash( $_POST['edd_template_tag'] ) );

			$args = array(
				'posts_per_page' => 1,
				'post_type'      => 'download',
			);

			// Updating current query.
			$the_query = new WP_Query( $args );

			// The Loop
			if ( $the_query->have_posts() ) {
				while ( $the_query->have_posts() ) {
					$the_query->the_post();

					$id       = get_the_ID();
					$download = edd_get_download( $id );

					if ( ! $download || ! is_a( $download, 'EDD_Download' ) ) {
						return '';
					}

					$content = do_shortcode( $edd_template_tag );
				}
			}

			/* Restore original Post Data */
			wp_reset_postdata();

			if ( ! empty( $content ) ) {
				do_action( 'wp_print_footer_scripts' );
				do_action( 'wp_footer' );
			}
		}

		echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

		exit();
	}
	exit;
}


if ( defined( 'DOING_AJAX' ) ) {
	
	add_action( 'wp_ajax_seedprod_pro_render_shortcode_wc_cart', 'seedprod_pro_render_shortcode_wc_cart' );
	add_action( 'wp_ajax_seedprod_pro_render_shortcode_wc_custom_products_grid', 'seedprod_pro_render_shortcode_wc_custom_products_grid' );
	add_action( 'wp_ajax_seedprod_pro_render_shortcode_wc_checkout', 'seedprod_pro_render_shortcode_wc_checkout' );
	add_action( 'wp_ajax_seedprod_pro_render_shortcode', 'seedprod_pro_render_shortcode' );
	add_action( 'wp_ajax_seedprod_pro_render_templatetag', 'seedprod_pro_render_templatetag' );
	add_action( 'wp_ajax_seedprod_pro_render_wc_template_tags', 'seedprod_pro_render_wc_template_tags' );
	add_action( 'wp_ajax_seedprod_pro_render_edd_template_tags', 'seedprod_pro_render_edd_template_tags' );
	add_action( 'wp_ajax_seedprod_pro_render_shortcode_edd_downloads_grid', 'seedprod_pro_render_shortcode_edd_downloads_grid' );
	add_action( 'wp_ajax_seedprod_pro_render_shortcode_edd_buy_now_button', 'seedprod_pro_render_shortcode_edd_buy_now_button' );
	add_action( 'wp_ajax_seedprod_pro_edd_checkout_purchase_form', 'seedprod_pro_edd_checkout_purchase_form' );
	add_action( 'wp_ajax_seedprod_pro_render_shortcode_edd_cart', 'seedprod_pro_render_shortcode_edd_cart' );
	add_action( 'wp_ajax_seedprod_pro_render_shortcode_edd_checkout', 'seedprod_pro_render_shortcode_edd_checkout' );
	

	add_action( 'wp_ajax_seedprod_pro_dismiss_settings_lite_cta', 'seedprod_pro_dismiss_settings_lite_cta' );

	add_action( 'wp_ajax_seedprod_pro_save_settings', 'seedprod_pro_save_settings' );
	add_action( 'wp_ajax_seedprod_pro_save_api_key', 'seedprod_pro_save_api_key' );

	add_action( 'wp_ajax_seedprod_pro_save_app_settings', 'seedprod_pro_save_app_settings' );

	
	add_action( 'wp_ajax_seedprod_pro_deactivate_api_key', 'seedprod_pro_deactivate_api_key' );
	

	add_action( 'wp_ajax_seedprod_pro_template_subscribe', 'seedprod_pro_template_subscribe' );
	add_action( 'wp_ajax_seedprod_pro_save_template', 'seedprod_pro_save_template' );
	add_action( 'wp_ajax_seedprod_pro_save_lpage', 'seedprod_pro_save_lpage' );
	add_action( 'wp_ajax_seedprod_pro_get_revisions', 'seedprod_pro_get_revisisons' );
	add_action( 'wp_ajax_seedprod_pro_get_utc_offset', 'seedprod_pro_get_utc_offset' );
	add_action( 'wp_ajax_seedprod_pro_get_namespaced_custom_css', 'seedprod_pro_get_namespaced_custom_css' );
	add_action( 'wp_ajax_seedprod_pro_get_stockimages', 'seedprod_pro_get_stockimages' );
	
	add_action( 'wp_ajax_seedprod_pro_backgrounds_sideload', 'seedprod_pro_backgrounds_sideload' );
	add_action( 'wp_ajax_seedprod_pro_backgrounds_download', 'seedprod_pro_backgrounds_download' );
	

	// Landing pages
	add_action( 'wp_ajax_seedprod_pro_slug_exists', 'seedprod_pro_slug_exists' );
	add_action( 'wp_ajax_seedprod_pro_lpage_datatable', 'seedprod_pro_lpage_datatable' );
	add_action( 'wp_ajax_seedprod_pro_duplicate_lpage', 'seedprod_pro_duplicate_lpage' );
	add_action( 'wp_ajax_seedprod_pro_get_lpage_list', 'seedprod_pro_get_lpage_list' );
	add_action( 'wp_ajax_seedprod_pro_archive_selected_lpages', 'seedprod_pro_archive_selected_lpages' );
	add_action( 'wp_ajax_seedprod_pro_unarchive_selected_lpages', 'seedprod_pro_unarchive_selected_lpages' );
	add_action( 'wp_ajax_seedprod_pro_delete_archived_lpages', 'seedprod_pro_delete_archived_lpages' );

	// Theme templates
	
	add_action( 'wp_ajax_seedprod_pro_themetemplate_datatable', 'seedprod_pro_themetemplate_datatable' );
	add_action( 'wp_ajax_seedprod_pro_duplicate_themetemplate', 'seedprod_pro_duplicate_themetemplate' );
	add_action( 'wp_ajax_seedprod_pro_archive_selected_themetemplates', 'seedprod_pro_archive_selected_themetemplates' );
	add_action( 'wp_ajax_seedprod_pro_unarchive_selected_themetemplates', 'seedprod_pro_unarchive_selected_themetemplates' );
	add_action( 'wp_ajax_seedprod_pro_delete_archived_themetemplates', 'seedprod_pro_delete_archived_themetemplates' );
	add_action( 'wp_ajax_seedprod_pro_temp_save_theme_template', 'seedprod_pro_temp_save_theme_template' );
	add_action( 'wp_ajax_seedprod_pro_update_theme_template_conditions', 'seedprod_pro_update_theme_template_conditions' );
	add_action( 'wp_ajax_seedprod_pro_update_theme_template_post_status', 'seedprod_pro_update_theme_template_post_status' );
	add_action( 'wp_ajax_seedprod_pro_update_theme_template_preview_mode', 'seedprod_pro_update_theme_template_preview_mode' );
	add_action( 'wp_ajax_seedprod_pro_update_seedprod_theme_enabled', 'seedprod_pro_update_seedprod_theme_enabled' );

	add_action( 'wp_ajax_seedprod_pro_import_theme_request', 'seedprod_pro_import_theme_request' );
	add_action( 'wp_ajax_seedprod_pro_create_blog_and_home_for_theme', 'seedprod_pro_create_blog_and_home_for_theme' );

	add_action( 'wp_ajax_seedprod_pro_delete_theme_pages', 'seedprod_pro_delete_theme_pages' );

	add_action( 'wp_ajax_seedprod_pro_open_ai_backgrounds_sideload', 'seedprod_pro_open_ai_backgrounds_sideload' );
	add_action( 'wp_ajax_seedprod_pro_generate_image_open_ai', 'seedprod_pro_generate_image_open_ai' );
	add_action( 'wp_ajax_seedprod_pro_generate_image_open_ai_variations', 'seedprod_pro_generate_image_open_ai_variations' );
	add_action( 'wp_ajax_seedprod_pro_generate_image_open_ai_edit_image', 'seedprod_pro_generate_image_open_ai_edit_image' );

	add_action( 'wp_ajax_seedprod_pro_call_open_ai', 'seedprod_pro_call_open_ai' );
	add_action( 'wp_ajax_seedprod_pro_call_open_ai_edit', 'seedprod_pro_call_open_ai_edit' );
	add_action( 'wp_ajax_seedprod_pro_call_ai_credits', 'seedprod_pro_call_ai_credits' );

	

	add_action( 'wp_ajax_seedprod_pro_update_subscriber_count', 'seedprod_pro_update_subscriber_count' );
	add_action( 'wp_ajax_seedprod_pro_subscribers_datatable', 'seedprod_pro_subscribers_datatable' );
	
	add_action( 'wp_ajax_seedprod_pro_delete_subscribers', 'seedprod_pro_delete_subscribers' );
	


	add_action( 'wp_ajax_seedprod_pro_get_plugins_list', 'seedprod_pro_get_plugins_list' );

	add_action( 'wp_ajax_seedprod_pro_install_addon', 'seedprod_pro_install_addon' );
	add_action( 'wp_ajax_seedprod_pro_activate_addon', 'seedprod_pro_activate_addon' );
	add_action( 'wp_ajax_seedprod_pro_deactivate_addon', 'seedprod_pro_deactivate_addon' );

	add_action( 'wp_ajax_seedprod_pro_install_addon', 'seedprod_pro_install_addon' );
	add_action( 'wp_ajax_seedprod_pro_deactivate_addon', 'seedprod_pro_deactivate_addon' );
	add_action( 'wp_ajax_seedprod_pro_activate_addon', 'seedprod_pro_activate_addon' );
	add_action( 'wp_ajax_seedprod_pro_plugin_nonce', 'seedprod_pro_plugin_nonce' );

	add_action( 'wp_ajax_nopriv_seedprod_pro_run_one_click_upgrade', 'seedprod_pro_run_one_click_upgrade' );
	add_action( 'wp_ajax_seedprod_pro_upgrade_license', 'seedprod_pro_upgrade_license' );

	add_action( 'wp_ajax_seedprod_pro_get_wpforms', 'seedprod_pro_get_wpforms' );
	add_action( 'wp_ajax_seedprod_pro_get_wpform', 'seedprod_pro_get_wpform' );
	add_action( 'wp_ajax_seedprod_pro_get_rafflepress', 'seedprod_pro_get_rafflepress' );
	add_action( 'wp_ajax_seedprod_pro_get_rafflepress_code', 'seedprod_pro_get_rafflepress_code' );
	
	add_action( 'wp_ajax_seedprod_pro_get_mypaykit', 'seedprod_pro_get_mypaykit' );
	add_action( 'wp_ajax_seedprod_pro_get_mypaykit_code', 'seedprod_pro_get_mypaykit_code' );

	add_action( 'wp_ajax_seedprod_pro_get_widget_wpforms', 'seedprod_pro_get_widget_wpforms' );
	add_action( 'wp_ajax_seedprod_pro_get_widget_wpresults', 'seedprod_pro_get_widget_wpresults' );

	add_action( 'wp_ajax_seedprod_pro_get_envira_galleries', 'seedprod_pro_get_envira_galleries' );

	add_action( 'wp_ajax_seedprod_pro_dismiss_upsell', 'seedprod_pro_dismiss_upsell' );

	// WooCommerce.
	add_action( 'wp_ajax_seedprod_pro_get_woocommerce_products', 'seedprod_pro_get_woocommerce_products' );
	add_action( 'wp_ajax_seedprod_pro_get_woocommerce_product_taxonomy', 'seedprod_pro_get_woocommerce_product_taxonomy' );
	add_action( 'wp_ajax_seedprod_pro_get_woocommerce_product_attributes', 'seedprod_pro_get_woocommerce_product_attributes' );
	add_action( 'wp_ajax_seedprod_pro_get_woocommerce_product_attribute_terms', 'seedprod_pro_get_woocommerce_product_attribute_terms' );

	// EDD.
	add_action( 'wp_ajax_seedprod_pro_get_edd_downloads', 'seedprod_pro_get_edd_downloads' );
	add_action( 'wp_ajax_seedprod_pro_get_edd_download_taxonomy', 'seedprod_pro_get_edd_download_taxonomy' );

	
	// Subscribe Callback
	add_action( 'wp_ajax_seedprod_pro_subscribe_callback', 'seedprod_pro_subscribe_callback' );
	add_action( 'wp_ajax_nopriv_seedprod_pro_subscribe_callback', 'seedprod_pro_subscribe_callback' );
	

	
	add_action( 'wp_ajax_seedprod_pro_render_gallery_shortcode', 'seedprod_pro_render_gallery_shortcode' );
	add_action( 'wp_ajax_seedprod_pro_render_basic_gallery_shortcode', 'seedprod_pro_render_basic_gallery_shortcode' );
	

	
	add_action( 'wp_ajax_seedprod_pro_render_business_review_shortcode', 'seedprod_pro_render_business_review_shortcode' );
	

	
	add_action( 'wp_ajax_seedprod_pro_get_domain_mapping_domain', 'seedprod_pro_get_domain_mapping_domain' );
	


}







/*
 * Force License Recheck
 */
add_action( 'init', 'seedprod_pro_force_license_recheck' );

add_action( 'init', 'seedprod_pro_deactivate_license' );





/**
 * Return Widget Previews
 */
function seedprod_pro_get_widget_wpforms() {
	// Verify the nonce without echoing the return value
	if ( ! check_ajax_referer( 'seedprod_nonce', false, false ) ) {
		exit;
	}

	if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
		exit;
	}

	$block_type  = filter_input( INPUT_GET, 'block_type' );
	$base_id     = filter_input( INPUT_GET, 'base_id' );
	$widget_name = str_replace( 'wpwidgetblock-', '', $block_type );

	global $wp_widget_factory;
	$inst = $wp_widget_factory->widgets[ $widget_name ];

	// Get and decode the JSON input
	$component_json = file_get_contents( 'php://input' );
	$component      = json_decode( $component_json, true );
	$options        = isset( $component['options'] ) ? $component['options'] : array();

	// Sanitize options
	$instance = array();
	if ( is_array( $options ) ) {
		foreach ( $options as $key => $value ) {
			// Check if the value is an array
			if ( is_array( $value ) ) {
				$array_values     = array_map( 'sanitize_text_field', $value );
				$instance[ $key ] = implode( ',', $array_values );
			} else {
				$instance[ $key ] = sanitize_text_field( $value );
			}
		}
	}

	// Start output buffering to capture the widget form output
	ob_start();

	?>
	<div class="widget-inside media-widget-control">
		<div class="form wp-core-ui">
			<input type="hidden" class="id_base" value="<?php echo esc_attr( $base_id ); ?>">
			<?php $random_data = wp_rand( 1000, 9999 ); ?>
			<input type="hidden" class="widget-id" value="widget-c<?php echo esc_attr( $random_data ); ?>" />
			<div class="widget-content">
				<?php
				// Update the widget instance and output the form
				$updated_instance = $inst->update( $instance, array() );
				$inst->form( $updated_instance );
				?>
			</div>
		</div>
	</div>
	<?php

	// Get the buffered content and clean the buffer
	$output = ob_get_clean();

	// Output the content
	echo $output;
	exit;
}

/**
 * Return Widget
 */
function seedprod_pro_get_widget_wpresults() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}
		// print_r($_REQUEST);
		$block_type = filter_input( INPUT_GET, 'block_type' );
		// print_r($block_type);

		$widget_name = str_replace( 'wpwidgetblock-', '', $block_type );

		global $wp_widget_factory;
		$inst = $wp_widget_factory->widgets[ $widget_name ];

		$component_json = file_get_contents( 'php://input' );
		$component      = json_decode( $component_json, true );
		$options        = $component['options'];

		$instance = array();
		if ( is_array( $options ) ) {
			$wp_options = array();
			foreach ( $options as $t => $value ) {
				if ( 'WP_Widget_Custom_HTML' === $widget_name && 'content' === $t ) {
					$wp_options[ $t ] = $value;
				} else {
					// Check if the value is an array
					if ( is_array( $value ) ) {
						$array_values     = array_map( 'sanitize_text_field', $value );
						$wp_options[ $t ] = implode( ',', $array_values );
					} else {
						$wp_options[ $t ] = sanitize_text_field( $value );
					}
				}
			}
			$instance = $wp_options;
		}
		$updated_instance = $inst->update( $instance, array() );
		the_widget( $widget_name, $instance );

		die( '' );
		// return $widget_name;
	}
}

// login redirect
add_action( 'login_head', 'seedprod_pro_redirect_login_page' );



// Make RafflePress Discoverable
if ( 'pro' === SEEDPROD_PRO_BUILD ) {
	add_filter( 'install_plugins_table_api_args_featured', 'seedprod_pro_featured_plugins_tab' );
}
/**
 * Helper function for adding plugins to featured list
 *
 * @return array
 */
function seedprod_pro_featured_plugins_tab( $args ) {
	add_filter( 'plugins_api_result', 'seedprod_pro_plugins_api_result', 10, 3 );

	return $args;
} // featured_plugins_tab


/**
 * Add plugins to featured plugins list
 *
 * @return object
 */
function seedprod_pro_plugins_api_result( $res, $action, $args ) {
	remove_filter( 'plugins_api_result', 'seedprod_pro_plugins_api_result', 10, 3 );

	$res = seedprod_pro_add_plugin_featured( 'rafflepress', $res );

	return $res;
} // plugins_api_result

/**
 * Add single plugin to featured list
 *
 * @return object
 */
function seedprod_pro_add_plugin_featured( $plugin_slug, $res ) {
	// check if plugin is already on the list
	if ( ! empty( $res->plugins ) && is_array( $res->plugins ) ) {
		foreach ( $res->plugins as $plugin ) {
			if ( is_object( $plugin ) && ! empty( $plugin->slug ) && $plugin->slug == $plugin_slug ) {
				return $res;
			}
		} // foreach
	}

	if ( $plugin_info = get_transient( 'seedprod-plugin-info-' . $plugin_slug ) ) {
		array_splice( $res->plugins, 4, 0, array( $plugin_info ) );
		// array_unshift($res->plugins, $plugin_info);
	} else {
		$plugin_info = plugins_api(
			'plugin_information',
			array(
				'slug'   => $plugin_slug,
				'is_ssl' => is_ssl(),
				'fields' => array(
					'banners'           => true,
					'reviews'           => true,
					'downloaded'        => true,
					'active_installs'   => true,
					'icons'             => true,
					'short_description' => true,
				),
			)
		);
		if ( ! is_wp_error( $plugin_info ) ) {
			$res->plugins = array_merge( array( $plugin_info ), $res->plugins );
			set_transient( 'seedprod-plugin-info-' . $plugin_slug, $plugin_info, DAY_IN_SECONDS * 7 );
		}
	}

	return $res;
} // add_plugin_featured



