init_hooks();
}
/**
* Initialize hooks
*/
private function init_hooks() {
// Add coupon to $_GET when checkout is called
add_action( 'admin_init', array( $this, 'add_coupon_to_request' ), 1 );
// Use output buffering to modify pricing config in inline script
add_action( 'admin_init', array( $this, 'start_output_buffering' ), 999 );
// Add JavaScript to handle upgrade links
add_action( 'admin_footer', array( $this, 'add_discount_js' ) );
add_action( 'wp_footer', array( $this, 'add_discount_js' ) );
// Display discount notice on pricing page
add_action( 'admin_notices', array( $this, 'show_discount_notice' ) );
// Use Freemius filters to add discount code
// Must be called after 'init' hook to ensure aiautotool_premium() returns an object
add_action( 'init', array( $this, 'register_freemius_filters' ), 20 );
// Hook into pricing template to ensure coupon is passed (high priority to run early)
add_action( 'admin_init', array( $this, 'ensure_coupon_in_pricing' ), 1 );
// Hook into pricing config to ensure coupon is included
// Note: This filter may not exist in all Freemius versions, so we also use direct $_GET manipulation
add_filter( 'fs_pricing_query_params', array( $this, 'add_coupon_to_pricing_params' ), 10, 1 );
// Filter pricing config directly (if available)
// Since pricing.php merges $_GET into query_params, ensuring coupon is in $_GET should work
// But we also add a filter to modify the config if needed
add_filter( 'fs_pricing_config', array( $this, 'add_coupon_to_pricing_config' ), 10, 1 );
// Inject coupon into pricing config via inline script as fallback
add_action( 'admin_footer', array( $this, 'inject_coupon_into_pricing_config' ), 999 );
}
/**
* Register Freemius filters
* Called after 'init' hook to ensure aiautotool_premium() returns an object
*/
public function register_freemius_filters() {
// Use Freemius filters to add discount code
if ( function_exists( 'aiautotool_premium' ) ) {
$premium = aiautotool_premium();
if ( $premium && is_object( $premium ) && method_exists( $premium, 'add_filter' ) ) {
// Hook into checkout_url to add discount code
$premium->add_filter( 'checkout_url', array( $this, 'add_discount_to_checkout_url' ), 10, 1 );
// Hook into pricing_url to add discount code
$premium->add_filter( 'pricing_url', array( $this, 'add_discount_to_pricing_url' ), 10, 1 );
}
}
}
/**
* Add coupon to pricing config
* This is called if the filter exists
*
* @param array $config Pricing config array
* @return array Modified config with coupon
*/
public function add_coupon_to_pricing_config( $config ) {
// Only apply if new user
if ( ! $this->is_new_user() ) {
return $config;
}
// Get coupon from $_GET or use default
$coupon = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : '';
if ( empty( $coupon ) ) {
$coupon = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
}
// Ensure coupon is in config
if ( ! empty( $coupon ) && ! isset( $config['coupon'] ) ) {
$config['coupon'] = $coupon;
}
return $config;
}
/**
* Inject coupon into pricing config via JavaScript
*/
public function inject_coupon_into_pricing_config() {
// Only on pricing page
$page = isset( $_GET['page'] ) ? $_GET['page'] : '';
if ( strpos( $page, 'pricing' ) === false ) {
return;
}
// Only if new user
if ( ! $this->is_new_user() ) {
return;
}
// Get coupon
$coupon = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : '';
if ( empty( $coupon ) ) {
$coupon = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
}
if ( empty( $coupon ) ) {
return;
}
?>
is_new_user() ) {
return $params;
}
// Get coupon from $_GET or use default
$coupon = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : '';
if ( empty( $coupon ) ) {
$coupon = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
}
// Ensure coupon is in params
if ( ! empty( $coupon ) ) {
$params['coupon'] = $coupon;
}
return $params;
}
/**
* Ensure coupon is passed to pricing config
* This runs early (priority 1) to ensure coupon is in $_GET before pricing.php template loads
*/
public function ensure_coupon_in_pricing() {
// Only apply on pricing page
$page = isset( $_GET['page'] ) ? $_GET['page'] : '';
if ( strpos( $page, 'pricing' ) === false ) {
return;
}
// Only add if new user
if ( ! $this->is_new_user() ) {
return;
}
// Ensure coupon is in $_GET
// This is critical because pricing.php merges $_GET into $query_params at line 58
// which then gets merged into $pricing_config at line 105
if ( ! isset( $_GET['coupon'] ) || empty( $_GET['coupon'] ) ) {
$discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
$_GET['coupon'] = $discount_code;
// Debug log
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
}
} else {
// Debug log
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
}
}
}
/**
* Display discount notice on pricing page
*/
public function show_discount_notice() {
// Only display on pricing page
$screen = get_current_screen();
if ( ! $screen || strpos( $screen->id, 'ai_auto_tool' ) === false ) {
return;
}
// Check if it's pricing page
$page = isset( $_GET['page'] ) ? $_GET['page'] : '';
if ( strpos( $page, 'pricing' ) === false && strpos( $page, 'checkout' ) === false ) {
return;
}
// Only display if new user
if ( ! $this->is_new_user() ) {
return;
}
$discount_code = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
if ( empty( $discount_code ) ) {
return;
}
?>
is_new_user() ) {
return;
}
// Check if on checkout or pricing page
$page = isset( $_GET['page'] ) ? $_GET['page'] : '';
$fs_action = isset( $_GET['fs_action'] ) ? $_GET['fs_action'] : '';
// If on Freemius checkout/pricing page
if ( strpos( $page, 'ai_auto_tool' ) !== false &&
( strpos( $page, 'pricing' ) !== false || strpos( $page, 'checkout' ) !== false ) ) {
// Only add if coupon doesn't exist
if ( ! isset( $_GET['coupon'] ) || empty( $_GET['coupon'] ) ) {
$discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
$_GET['coupon'] = $discount_code;
// Debug
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
}
}
}
// Also add if fs_action exists
if ( strpos( $fs_action, 'checkout' ) !== false || strpos( $fs_action, 'pricing' ) !== false ) {
if ( ! isset( $_GET['coupon'] ) || empty( $_GET['coupon'] ) ) {
$discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
$_GET['coupon'] = $discount_code;
}
}
}
/**
* Start output buffering to modify HTML
*/
public function start_output_buffering() {
// Only apply in admin and if new user
if ( ! is_admin() || ! $this->is_new_user() ) {
return;
}
ob_start( array( $this, 'modify_html_output' ) );
}
/**
* Modify HTML output to add coupon to pricing config
*/
public function modify_html_output( $buffer ) {
if ( empty( $buffer ) ) {
return $buffer;
}
// Only modify if we have a coupon
$coupon = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : '';
if ( empty( $coupon ) ) {
$coupon = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
}
if ( empty( $coupon ) ) {
return $buffer;
}
// Find and modify Freemius.pricing.new() call
// Pattern: Freemius.pricing.new( {...config...} )
$pattern = '/(Freemius\.pricing\.new\s*\(\s*)(\{[^}]*(?:\{[^}]*\}[^}]*)*\})(\s*\))/s';
$buffer = preg_replace_callback( $pattern, function( $matches ) use ( $coupon ) {
$before = $matches[1];
$config_json = $matches[2];
$after = $matches[3];
try {
// Parse JSON config
$config = json_decode( $config_json, true );
if ( is_array( $config ) && ! isset( $config['coupon'] ) ) {
// Add coupon to config
$config['coupon'] = $coupon;
// Re-encode JSON
$new_config_json = json_encode( $config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
}
return $before . $new_config_json . $after;
} elseif ( is_array( $config ) && isset( $config['coupon'] ) ) {
// Coupon already exists, ensure it's correct
if ( $config['coupon'] !== $coupon ) {
$config['coupon'] = $coupon;
$new_config_json = json_encode( $config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
return $before . $new_config_json . $after;
}
}
} catch ( Exception $e ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
}
}
return $matches[0];
}, $buffer );
// Also modify Freemius links (keep original functionality)
$discount_code = $coupon;
$patterns = array(
// Links containing freemius.com
'/(href=["\'])([^"\']*freemius\.com[^"\']*)(["\'])/i' => function( $matches ) use ( $discount_code ) {
$url = $matches[2];
// Check if coupon already exists
if ( strpos( $url, 'coupon=' ) === false ) {
$separator = strpos( $url, '?' ) !== false ? '&' : '?';
$url = $url . $separator . 'coupon=' . urlencode( $discount_code );
}
return $matches[1] . $url . $matches[3];
},
);
foreach ( $patterns as $pattern => $callback ) {
$buffer = preg_replace_callback( $pattern, $callback, $buffer );
}
return $buffer;
}
/**
* Check if user is a new user
*
* @return bool True if new user, False otherwise
*/
public function is_new_user() {
if ( ! function_exists( 'aiautotool_premium' ) ) {
return false;
}
$fs = aiautotool_premium();
// New user is someone who:
// 1. Has not registered with Freemius OR
// 2. Does not have a valid license OR
// 3. Has never purchased a license before
// Check if registered with Freemius
if ( ! $fs->is_registered() ) {
return true; // Not registered = new user
}
// Check if has valid license
if ( ! $fs->has_active_valid_license() ) {
// Check if there's any expired or cancelled license
$license = $fs->_get_license();
// If no license = new user
if ( ! is_object( $license ) ) {
return true;
}
// If has license but expired and never renewed = could be new user
// (Optional: you can skip this case if you want to apply only to those who never purchased)
// return false; // If had license before then not a new user
}
// Check if discount code has been used before
$discount_used = get_option( 'aiautotool_new_user_discount_used', false );
if ( $discount_used ) {
return false; // Already used discount
}
// Default: if no valid license = new user
return ! $fs->has_active_valid_license();
}
/**
* Check if URL is a Freemius checkout/pricing URL
*
* @param string $url URL to check
* @return bool True if Freemius URL, False otherwise
*/
private function is_freemius_url( $url ) {
if ( empty( $url ) ) {
return false;
}
// Parse URL to get host and query
$parsed_url = parse_url( $url );
// Check if it's plugin admin pricing URL
if ( isset( $parsed_url['query'] ) ) {
parse_str( $parsed_url['query'], $query_params );
// If it's plugin pricing page
if ( isset( $query_params['page'] ) && strpos( $query_params['page'], 'ai_auto_tool' ) !== false &&
( strpos( $query_params['page'], 'pricing' ) !== false || strpos( $query_params['page'], 'checkout' ) !== false ) ) {
return true;
}
}
// Check if URL contains page=ai_auto_tool-pricing
if ( strpos( $url, 'page=ai_auto_tool-pricing' ) !== false ||
strpos( $url, 'page=ai_auto_tool-checkout' ) !== false ) {
return true;
}
if ( ! isset( $parsed_url['host'] ) ) {
return false;
}
$host = strtolower( $parsed_url['host'] );
// Check if it's Freemius domain
$freemius_domains = array(
'freemius.com',
'checkout.freemius.com',
'api.freemius.com',
'dashboard.freemius.com'
);
foreach ( $freemius_domains as $domain ) {
if ( strpos( $host, $domain ) !== false ) {
return true;
}
}
// Check if URL contains checkout or pricing path
$path = isset( $parsed_url['path'] ) ? strtolower( $parsed_url['path'] ) : '';
if ( strpos( $path, '/checkout' ) !== false || strpos( $path, '/pricing' ) !== false ) {
return true;
}
return false;
}
/**
* Add discount code to checkout URL
*
* @param string $url Original checkout URL
* @return string Checkout URL with discount code (if new user)
*/
public function add_discount_to_checkout_url( $url ) {
// Only apply to this plugin
if ( ! function_exists( 'aiautotool_premium' ) ) {
return $url;
}
// Check if new user
if ( ! $this->is_new_user() ) {
return $url;
}
// Only add coupon to Freemius URLs, not internal admin URLs
if ( ! $this->is_freemius_url( $url ) ) {
return $url;
}
// Check if URL already has coupon (avoid duplicates)
$parsed_url = parse_url( $url );
if ( isset( $parsed_url['query'] ) ) {
parse_str( $parsed_url['query'], $query_params );
if ( isset( $query_params['coupon'] ) && ! empty( $query_params['coupon'] ) ) {
return $url; // Already has coupon, don't add again
}
}
// Add discount code to URL
$discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
// Use WordPress function to add query parameter (safer and simpler)
$new_url = add_query_arg( 'coupon', $discount_code, $url );
// Debug (can be removed later)
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
}
return $new_url;
}
/**
* Add discount code to pricing URL
*
* @param string $url Original pricing URL
* @return string Pricing URL with discount code (if new user)
*/
public function add_discount_to_pricing_url( $url ) {
return $this->add_discount_to_checkout_url( $url );
}
/**
* Mark discount code as used
* (Call when user completes payment)
*/
public function mark_discount_as_used() {
update_option( 'aiautotool_new_user_discount_used', true );
}
/**
* Reset discount status (for testing or to allow reuse)
*/
public function reset_discount_status() {
delete_option( 'aiautotool_new_user_discount_used' );
}
/**
* Add JavaScript to handle upgrade links and add coupon
*/
public function add_discount_js() {
// Only add script if new user
if ( ! $this->is_new_user() ) {
return;
}
$discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
?>
apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE ),
'percentage' => 50,
'is_available' => $this->is_new_user(),
'message' => $this->is_new_user()
? sprintf(
__( 'You are a new user! Use code %s to get 50%% off', 'ai-auto-tool' ),
apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE )
)
: __( 'Discount code only applies to new users', 'ai-auto-tool' )
);
}
}
// Khởi tạo class
if ( class_exists( 'AIAutoTool_NewUserDiscount' ) ) {
new AIAutoTool_NewUserDiscount();
}