<?php
/**
 * Forumax Pro Upgrade Offer Notice
 *
 * A premium upgrade notice with improved UI/UX, countdown timer,
 * feature highlights, and conversion-optimized copywriting.
 *
 * @package Forumax
 */

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

/**
 * Get the number of forums created by the user
 *
 * @return int Number of forums
 */
function frmx_get_forums_count() {
	$forums = wp_count_posts( 'forum' );
	return isset( $forums->publish ) ? (int) $forums->publish : 0;
}

/**
 * Get personalized message based on user's usage
 *
 * @return array Message data with headline and subheadline
 */
function frmx_get_personalized_message() {
	$forums_count  = frmx_get_forums_count();
	$install_days  = frmx_get_install_days();

	// Personalized messaging based on usage
	if ( $forums_count >= 10 ) {
		return array(
			'headline'    => sprintf(
				/* translators: %d: number of forums */
				esc_html__( 'You\'ve created %d forums! Ready to supercharge your community?', 'forumax' ),
				$forums_count
			),
			'subheadline' => esc_html__( 'Unlock advanced features like Private Forums, User Badges & Role-based Access', 'forumax' ),
			'cta'         => esc_html__( 'Upgrade & Save 45%', 'forumax' ),
		);
	} elseif ( $install_days >= 30 ) {
		return array(
			'headline'    => esc_html__( 'You\'ve been with us for a month! Here\'s a special thank you.', 'forumax' ),
			'subheadline' => esc_html__( 'Get 45% off Forumax Pro as our way of saying thanks!', 'forumax' ),
			'cta'         => esc_html__( 'Claim Your Reward', 'forumax' ),
		);
	} else {
		return array(
			'headline'    => esc_html__( 'Unlock the Full Power of Forumax', 'forumax' ),
			'subheadline' => esc_html__( 'Join 3,000+ happy customers who upgraded to Pro', 'forumax' ),
			'cta'         => esc_html__( 'Get 45% Off Now', 'forumax' ),
		);
	}
}

/**
 * Get the number of days since plugin installation
 *
 * @return int Number of days
 */
function frmx_get_install_days() {
	$installed_time = get_option( 'bbpc_installed' );
	if ( ! $installed_time ) {
		return 0;
	}
	return (int) floor( ( time() - $installed_time ) / DAY_IN_SECONDS );
}

/**
 * Check if the notice should be shown based on snooze
 *
 * @return bool Whether to show the notice
 */
function frmx_should_show_offer_notice() {
	$user_id      = get_current_user_id();
	$snooze_until = get_user_meta( $user_id, 'bbpc_offer_snooze_until', true );

	if ( $snooze_until && time() < (int) $snooze_until ) {
		return false;
	}

	return true;
}

/**
 * Display the upgrade offer notice
 */
function forumax_offer_notice() {
	$is_dev_mode = defined( 'DEVELOPER_MODE' ) && DEVELOPER_MODE;

	if ( is_user_logged_in() && ! $is_dev_mode ) {
		$user_id   = get_current_user_id();
		$dismissed = get_user_meta( $user_id, 'bbpc_offer_dismissed', true );

		if ( '1' === $dismissed ) {
			return;
		}

		if ( ! frmx_should_show_offer_notice() ) {
			return;
		}
	}

	$message     = frmx_get_personalized_message();
	$coupon_code = 'DASH45';
	$pricing_url = 'https://forumax.spider-themes.net/pricing/';

	// Pro features to highlight
	$pro_features = array(
		array(
			'icon'  => 'dashicons-chart-bar',
			'title' => esc_html__( 'Advanced Analytics', 'forumax' ),
			'desc'  => esc_html__( 'Track forum activity, user engagement & content performance in real-time', 'forumax' ),
		),
		array(
			'icon'  => 'dashicons-lock',
			'title' => esc_html__( 'Access Control', 'forumax' ),
			'desc'  => esc_html__( 'Restrict forum access by user roles & membership levels', 'forumax' ),
		),
		array(
			'icon'  => 'dashicons-groups',
			'title' => esc_html__( 'Private Forums', 'forumax' ),
			'desc'  => esc_html__( 'Create exclusive private forums for specific user groups & teams', 'forumax' ),
		),
		array(
			'icon'  => 'dashicons-awards',
			'title' => esc_html__( 'User Badges', 'forumax' ),
			'desc'  => esc_html__( 'Reward active members with custom badges & reputation points', 'forumax' ),
		),
	);
	?>
	<div class="frmx-offer-notice" id="frmx-offer-notice">
		<!-- Decorative Background Elements -->
		<div class="frmx-offer-bg-pattern"></div>
		<div class="frmx-offer-glow"></div>

		<!-- Close & Snooze Buttons -->
		<div class="frmx-offer-actions">
			<button type="button" class="frmx-offer-snooze" data-action="snooze" title="<?php esc_attr_e( 'Remind me in 3 days', 'forumax' ); ?>">
				<span class="dashicons dashicons-clock"></span>
				<span class="frmx-offer-snooze-text"><?php esc_html_e( 'Later', 'forumax' ); ?></span>
			</button>
			<button type="button" class="frmx-offer-dismiss" data-action="dismiss" title="<?php esc_attr_e( 'Dismiss forever', 'forumax' ); ?>">
				<span class="dashicons dashicons-no-alt"></span>
			</button>
		</div>

		<div class="frmx-offer-container">
			<!-- Left: Badge & Headline -->
			<div class="frmx-offer-header">
				<div class="frmx-offer-badge">
					<span class="frmx-offer-badge-icon">🎉</span>
					<span class="frmx-offer-badge-text"><?php esc_html_e( 'Limited Time Offer', 'forumax' ); ?></span>
				</div>
				<h3 class="frmx-offer-headline"><?php echo esc_html( $message['headline'] ); ?></h3>
				<p class="frmx-offer-subheadline"><?php echo esc_html( $message['subheadline'] ); ?></p>
			</div>

			<!-- Center: Pro Features -->
			<div class="frmx-offer-features">
				<?php foreach ( $pro_features as $feature ) : ?>
					<div class="frmx-offer-feature">
						<span class="dashicons <?php echo esc_attr( $feature['icon'] ); ?>"></span>
						<div class="frmx-offer-feature-text">
							<strong><?php echo esc_html( $feature['title'] ); ?></strong>
							<span><?php echo esc_html( $feature['desc'] ); ?></span>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

			<!-- Right: Discount & CTA -->
			<div class="frmx-offer-cta-section">
				<div class="frmx-offer-discount">
					<span class="frmx-offer-discount-value">45%</span>
					<span class="frmx-offer-discount-label"><?php esc_html_e( 'OFF', 'forumax' ); ?></span>
				</div>

				<div class="frmx-offer-coupon">
					<span class="frmx-offer-coupon-label"><?php esc_html_e( 'Use code:', 'forumax' ); ?></span>
					<div class="frmx-offer-coupon-box">
						<code class="frmx-offer-coupon-code" id="frmx-coupon-code"><?php echo esc_html( $coupon_code ); ?></code>
						<button type="button" class="frmx-offer-copy-btn" id="frmx-copy-btn" title="<?php esc_attr_e( 'Copy coupon code', 'forumax' ); ?>">
							<span class="dashicons dashicons-admin-page"></span>
						</button>
						<span class="frmx-offer-copy-success" id="frmx-copy-success">
							<span class="dashicons dashicons-yes-alt"></span>
							<?php esc_html_e( 'Copied!', 'forumax' ); ?>
						</span>
					</div>
				</div>

				<a href="<?php echo esc_url( add_query_arg( 'coupon', $coupon_code, $pricing_url ) ); ?>" 
				   class="frmx-offer-cta-btn" 
				   target="_blank"
				   rel="noopener noreferrer">
					<?php echo esc_html( $message['cta'] ); ?>
					<span class="dashicons dashicons-arrow-right-alt"></span>
				</a>

				<p class="frmx-offer-guarantee">
					<span class="dashicons dashicons-shield"></span>
					<?php esc_html_e( '30-day money-back guarantee', 'forumax' ); ?>
				</p>
			</div>
		</div>
	</div>

	<script>
	document.addEventListener('DOMContentLoaded', function() {
		const notice = document.getElementById('frmx-offer-notice');
		const copyBtn = document.getElementById('frmx-copy-btn');
		const couponCode = document.getElementById('frmx-coupon-code');
		const copySuccess = document.getElementById('frmx-copy-success');
		const snoozeBtn = notice.querySelector('.frmx-offer-snooze');
		const dismissBtn = notice.querySelector('.frmx-offer-dismiss');

		// Copy coupon code
		if (copyBtn && couponCode) {
			copyBtn.addEventListener('click', function() {
				/**
				 * Copy text to clipboard with fallback
				 *
				 * navigator.clipboard API requires HTTPS (secure context).
				 * On HTTP local sites it is undefined, so we must check
				 * before calling and use execCommand fallback otherwise.
				 */
				function copyToClipboard(text) {
					var textArea = document.createElement('textarea');
					textArea.value = text;
					textArea.style.position = 'fixed';
					textArea.style.left = '-9999px';
					document.body.appendChild(textArea);
					textArea.select();
					document.execCommand('copy');
					document.body.removeChild(textArea);
				}

				function showCopyFeedback() {
					copySuccess.classList.add('show');
					copyBtn.classList.add('copied');
					setTimeout(function() {
						copySuccess.classList.remove('show');
						copyBtn.classList.remove('copied');
					}, 2000);
				}

				if (navigator.clipboard && window.isSecureContext) {
					navigator.clipboard.writeText(couponCode.textContent).then(function() {
						showCopyFeedback();
					}).catch(function() {
						copyToClipboard(couponCode.textContent);
						showCopyFeedback();
					});
				} else {
					copyToClipboard(couponCode.textContent);
					showCopyFeedback();
				}
			});
		}

		// Handle dismiss/snooze actions
		function handleAction(action) {
			notice.style.opacity = '0';
			notice.style.transform = 'translateY(-20px)';
			
			setTimeout(function() {
				notice.style.display = 'none';
			}, 300);

			fetch('<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>', {
				method: 'POST',
				credentials: 'same-origin',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				body: 'action=bbpc_handle_offer_notice&notice_action=' + action + '&nonce=<?php echo esc_js( wp_create_nonce( 'bbpc-offer-notice' ) ); ?>'
			});
		}

		if (snoozeBtn) {
			snoozeBtn.addEventListener('click', function() {
				handleAction('snooze');
			});
		}

		if (dismissBtn) {
			dismissBtn.addEventListener('click', function() {
				handleAction('dismiss');
			});
		}

		// Animate in on load
		setTimeout(function() {
			notice.classList.add('frmx-offer-visible');
		}, 100);
	});
	</script>
	<?php
}

/**
 * Handle offer notice AJAX actions (dismiss/snooze)
 */
add_action( 'wp_ajax_bbpc_handle_offer_notice', 'forumax_handle_offer_notice_ajax' );

/**
 * Process the dismiss or snooze action
 */
function forumax_handle_offer_notice_ajax() {
	check_ajax_referer( 'bbpc-offer-notice', 'nonce' );

	if ( ! is_user_logged_in() ) {
		wp_send_json_error( array( 'message' => 'User not logged in.' ) );
	}

	$user_id = get_current_user_id();
	$action  = isset( $_POST['notice_action'] ) ? sanitize_text_field( wp_unslash( $_POST['notice_action'] ) ) : '';

	if ( 'dismiss' === $action ) {
		update_user_meta( $user_id, 'bbpc_offer_dismissed', '1' );
		wp_send_json_success( array( 'message' => 'Notice dismissed permanently.' ) );
	} elseif ( 'snooze' === $action ) {
		// Snooze for 3 days
		$snooze_until = time() + ( 3 * DAY_IN_SECONDS );
		update_user_meta( $user_id, 'bbpc_offer_snooze_until', $snooze_until );
		wp_send_json_success( array( 'message' => 'Notice snoozed for 3 days.' ) );
	} else {
		wp_send_json_error( array( 'message' => 'Invalid action.' ) );
	}

	wp_die();
}

// Keep backward compatibility - remove old action if it exists
remove_action( 'wp_ajax_bbpc_dismiss_offer_notice', 'forumax_dismiss_offer_notice' );
