<?php

/**
 * Discount Popup for Free Users.
 *
 * Displays a promotional popup for free users after a specified delay.
 * Includes dismiss functionality with re-appearance after set interval.
 *
 * @package    Extra_Product_Options_For_WooCommerce
 * @subpackage Extra_Product_Options_For_WooCommerce/includes
 * @since      4.4.5
 */
// If this file is called directly, abort.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Class EPOFW_Discount_Popup
 *
 * Handles the discount popup display and dismissal for free users.
 *
 * @since 4.4.5
 */
class EPOFW_Discount_Popup {
    /**
     * User meta key for storing dismiss timestamp.
     *
     * @var string
     */
    const DISMISS_META_KEY = 'epofw_discount_popup_dismissed';

    /**
     * Nonce action for popup dismissal.
     *
     * @var string
     */
    const NONCE_ACTION = 'epofw_discount_popup_nonce';

    /**
     * Initialize the class.
     *
     * @since 4.4.5
     */
    public function __construct() {
        // Only run for admin and non-premium users.
        if ( !is_admin() ) {
            return;
        }
        add_action( 'admin_footer', array($this, 'maybe_display_popup') );
        add_action( 'wp_ajax_epofw_dismiss_discount_popup', array($this, 'ajax_dismiss_popup') );
    }

    /**
     * Check if current user is using free version.
     *
     * @since 4.4.5
     *
     * @return bool True if free user, false if premium.
     */
    private function is_free_user() {
        if ( function_exists( 'epofw_fs' ) ) {
        }
        return true;
    }

    /**
     * Check if we're on a plugin admin page.
     *
     * @since 4.4.5
     *
     * @return bool True if on plugin admin page.
     */
    private function is_plugin_admin_page() {
        $screen = get_current_screen();
        if ( !$screen ) {
            return false;
        }
        // Check for plugin's admin pages.
        $plugin_pages = array(
            'toplevel_page_epofw-main',
            'woocommerce_page_epofw-main',
            'product_page_epofw-main',
            'extra-product-addons_page_epofw-main',
            'epofw-main'
        );
        /**
         * Filter the admin pages where discount popup should appear.
         *
         * @since 4.4.5
         *
         * @param array  $plugin_pages Array of screen IDs where popup should show.
         * @param object $screen       Current screen object.
         */
        $plugin_pages = apply_filters( 'epofw_discount_popup_admin_pages', $plugin_pages, $screen );
        // Also check if screen ID contains our plugin slug.
        if ( in_array( $screen->id, $plugin_pages, true ) || strpos( $screen->id, 'epofw' ) !== false ) {
            return true;
        }
        return false;
    }

    /**
     * Get the delay before showing popup (in seconds).
     *
     * @since 4.4.5
     *
     * @return int Delay in seconds.
     */
    private function get_initial_delay() {
        /**
         * Filter the initial delay before showing the discount popup.
         *
         * @since 4.4.5
         *
         * @param int $delay Delay in seconds. Default: 1 week (604800 seconds).
         */
        return apply_filters( 'epofw_discount_popup_initial_delay', WEEK_IN_SECONDS );
    }

    /**
     * Get the re-appearance delay after dismissal (in seconds).
     *
     * @since 4.4.5
     *
     * @return int Delay in seconds.
     */
    private function get_reappear_delay() {
        /**
         * Filter the delay before popup reappears after dismissal.
         *
         * @since 4.4.5
         *
         * @param int $delay Delay in seconds. Default: 2 weeks (1209600 seconds).
         */
        return apply_filters( 'epofw_discount_popup_reappear_delay', 2 * WEEK_IN_SECONDS );
    }

    /**
     * Check if popup should be displayed.
     *
     * @since 4.4.5
     *
     * @return bool True if popup should be shown.
     */
    private function should_display_popup() {
        /**
         * Filter to enable/disable the discount popup completely.
         *
         * @since 4.4.5
         *
         * @param bool $enabled Whether popup is enabled. Default true.
         */
        if ( !apply_filters( 'epofw_discount_popup_enabled', true ) ) {
            return false;
        }
        // Only for free users.
        if ( !$this->is_free_user() ) {
            return false;
        }
        // Only on plugin admin pages.
        if ( !$this->is_plugin_admin_page() ) {
            return false;
        }
        $current_user_id = get_current_user_id();
        if ( !$current_user_id ) {
            return false;
        }
        // Get install date.
        $install_date = get_option( 'epofw_install_date' );
        if ( !$install_date ) {
            // Set install date if not exists (for existing installations).
            $install_date = time();
            add_option( 'epofw_install_date', $install_date );
        }
        $now = time();
        // Check if initial delay has passed.
        $initial_delay = $this->get_initial_delay();
        $show_after_time = $install_date + $initial_delay;
        if ( $now < $show_after_time ) {
            return false;
        }
        // Check if user has dismissed the popup.
        $dismissed_time = get_user_meta( $current_user_id, self::DISMISS_META_KEY, true );
        if ( $dismissed_time ) {
            // Check if re-appearance delay has passed.
            $reappear_delay = $this->get_reappear_delay();
            $reappear_time = intval( $dismissed_time ) + $reappear_delay;
            if ( $now < $reappear_time ) {
                return false;
            }
        }
        /**
         * Filter the final decision on whether to display the discount popup.
         *
         * @since 4.4.5
         *
         * @param bool $should_display Whether popup should display. Default true.
         * @param int  $current_user_id Current user ID.
         * @param int  $install_date Plugin install timestamp.
         */
        return apply_filters(
            'epofw_discount_popup_should_display',
            true,
            $current_user_id,
            $install_date
        );
    }

    /**
     * Get the upgrade URL with UTM parameters.
     *
     * @since 4.4.5
     *
     * @return string Upgrade URL.
     */
    private function get_upgrade_url() {
        $upgrade_url = '';
        if ( function_exists( 'epofw_fs' ) ) {
            $upgrade_url = epofw_fs()->get_upgrade_url();
        }
        /**
         * Filter the discount popup upgrade URL.
         *
         * @since 4.4.5
         *
         * @param string $upgrade_url The upgrade URL.
         */
        return apply_filters( 'epofw_discount_popup_upgrade_url', $upgrade_url );
    }

    /**
     * Maybe display the discount popup.
     *
     * @since 4.4.5
     */
    public function maybe_display_popup() {
        if ( !$this->should_display_popup() ) {
            return;
        }
        $this->render_popup();
    }

    /**
     * Get popup content strings.
     *
     * @since 4.4.5
     *
     * @return array Popup content strings.
     */
    private function get_popup_content() {
        $content = array(
            'subtitle'    => __( 'Special Pro Upgrade Offer', 'extra-product-options-for-woocommerce' ),
            'title'       => __( 'Save 50%', 'extra-product-options-for-woocommerce' ),
            'plan'        => __( 'on Pro License Today!', 'extra-product-options-for-woocommerce' ),
            'urgency'     => __( 'Limited time offer - Upgrade now and unlock all premium features!', 'extra-product-options-for-woocommerce' ),
            'description' => __( 'Unlock 22+ advanced field types, nested conditional logic, formula-based pricing, file uploads, image swatches, and quantity-based addons. Take your product customization to the next level!', 'extra-product-options-for-woocommerce' ),
            'cta_text'    => __( 'Get Pro Now', 'extra-product-options-for-woocommerce' ),
        );
        /**
         * Filter the discount popup content strings.
         *
         * @since 4.4.5
         *
         * @param array $content Array of content strings with keys: subtitle, title, plan, urgency, description, cta_text.
         */
        return apply_filters( 'epofw_discount_popup_content', $content );
    }

    /**
     * Render the popup HTML.
     *
     * @since 4.4.5
     */
    private function render_popup() {
        $upgrade_url = $this->get_upgrade_url();
        $nonce = wp_create_nonce( self::NONCE_ACTION );
        $content = $this->get_popup_content();
        /**
         * Fires before the discount popup is rendered.
         *
         * @since 4.4.5
         *
         * @param string $upgrade_url The upgrade URL.
         * @param array  $content     Popup content strings.
         */
        do_action( 'epofw_before_discount_popup', $upgrade_url, $content );
        ?>
		<div id="epofw-discount-popup-overlay" class="epofw-discount-popup-overlay">
			<div id="epofw-discount-popup" class="epofw-discount-popup">
				<button type="button" class="epofw-discount-popup-close" id="epofw-discount-popup-close" data-nonce="<?php 
        echo esc_attr( $nonce );
        ?>">
					<span class="dashicons dashicons-no-alt"></span>
				</button>

				<div class="epofw-discount-popup-header">
					<div class="epofw-discount-confetti epofw-discount-confetti-left">
						<span></span><span></span><span></span><span></span><span></span>
					</div>
					<p class="epofw-discount-popup-subtitle"><?php 
        echo esc_html( $content['subtitle'] );
        ?></p>
					<h2 class="epofw-discount-popup-title"><?php 
        echo esc_html( $content['title'] );
        ?></h2>
					<p class="epofw-discount-popup-plan"><?php 
        echo esc_html( $content['plan'] );
        ?></p>
					<div class="epofw-discount-confetti epofw-discount-confetti-right">
						<span></span><span></span><span></span><span></span><span></span>
					</div>
				</div>

				<div class="epofw-discount-popup-urgency">
					<span class="dashicons dashicons-awards"></span>
					<?php 
        echo esc_html( $content['urgency'] );
        ?>
				</div>

				<div class="epofw-discount-popup-body">
					<p class="epofw-discount-popup-description">
						<?php 
        echo esc_html( $content['description'] );
        ?>
					</p>

					<a href="<?php 
        echo esc_url( $upgrade_url );
        ?>"
						class="epofw-discount-popup-cta"
						id="epofw-discount-popup-cta"
						target="_blank"
						rel="noopener noreferrer"
						data-nonce="<?php 
        echo esc_attr( $nonce );
        ?>">
						<?php 
        echo esc_html( $content['cta_text'] );
        ?>
					</a>
				</div>
			</div>
		</div>
		<?php 
        /**
         * Fires after the discount popup HTML is rendered.
         *
         * @since 4.4.5
         *
         * @param string $upgrade_url The upgrade URL.
         * @param array  $content     Popup content strings.
         */
        do_action( 'epofw_after_discount_popup', $upgrade_url, $content );
        ?>

		<style>
			.epofw-discount-popup-overlay {
				position: fixed;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: rgba(0, 0, 0, 0.6);
				z-index: 999999;
				display: flex;
				align-items: center;
				justify-content: center;
				opacity: 0;
				animation: epofwFadeIn 0.3s ease forwards;
			}

			@keyframes epofwFadeIn {
				to { opacity: 1; }
			}

			.epofw-discount-popup {
				background: #fff;
				border-radius: 12px;
				box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
				max-width: 480px;
				width: 90%;
				position: relative;
				overflow: hidden;
				transform: scale(0.9);
				animation: epofwScaleIn 0.3s ease forwards;
			}

			@keyframes epofwScaleIn {
				to { transform: scale(1); }
			}

			.epofw-discount-popup-close {
				position: absolute;
				top: 10px;
				right: 10px;
				background: rgba(255, 255, 255, 0.9);
				border: none;
				border-radius: 50%;
				width: 32px;
				height: 32px;
				cursor: pointer;
				display: flex;
				align-items: center;
				justify-content: center;
				z-index: 10;
				transition: all 0.2s ease;
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
			}

			.epofw-discount-popup-close:hover {
				background: #fff;
				transform: rotate(90deg);
			}

			.epofw-discount-popup-close .dashicons {
				font-size: 20px;
				width: 20px;
				height: 20px;
				color: #666;
			}

			.epofw-discount-popup-header {
				background: linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%);
				padding: 65px 25px;
				text-align: center;
				position: relative;
				overflow: hidden;
			}

			.epofw-discount-popup-subtitle {
				color: rgba(255, 255, 255, 0.9);
				font-size: 14px;
				margin: 0 0 18px 0;
				font-weight: 500;
			}

			.epofw-discount-popup-title {
				color: #fff;
				font-size: 42px;
				font-weight: 700;
				margin: 0;
				text-transform: uppercase;
				letter-spacing: 1px;
				text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
			}

			.epofw-discount-popup-plan {
				color: rgba(255, 255, 255, 0.9);
				font-size: 16px;
				margin: 18px 0 0 0;
				font-weight: 500;
			}

			/* Confetti decoration */
			.epofw-discount-confetti {
				position: absolute;
				top: 50%;
				transform: translateY(-50%);
			}

			.epofw-discount-confetti-left {
				left: 15px;
			}

			.epofw-discount-confetti-right {
				right: 15px;
			}

			.epofw-discount-confetti span {
				display: block;
				width: 8px;
				height: 8px;
				margin: 6px 0;
				border-radius: 2px;
				animation: epofwConfetti 1.5s ease-in-out infinite;
			}

			.epofw-discount-confetti span:nth-child(1) { background: #fbbf24; animation-delay: 0s; }
			.epofw-discount-confetti span:nth-child(2) { background: #34d399; animation-delay: 0.1s; }
			.epofw-discount-confetti span:nth-child(3) { background: #f472b6; animation-delay: 0.2s; }
			.epofw-discount-confetti span:nth-child(4) { background: #60a5fa; animation-delay: 0.3s; }
			.epofw-discount-confetti span:nth-child(5) { background: #fb923c; animation-delay: 0.4s; }

			@keyframes epofwConfetti {
				0%, 100% { transform: translateY(0) rotate(0deg); opacity: 1; }
				50% { transform: translateY(-5px) rotate(10deg); opacity: 0.7; }
			}

			.epofw-discount-popup-urgency {
				background: #fef3c7;
				border: 1px solid #fbbf24;
				color: #92400e;
				padding: 12px 20px;
				text-align: center;
				font-size: 13px;
				font-weight: 600;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 8px;
			}

			.epofw-discount-popup-urgency .dashicons {
				font-size: 16px;
				width: 16px;
				height: 16px;
			}

			.epofw-discount-popup-body {
				padding: 25px;
				text-align: center;
			}

			.epofw-discount-popup-description {
				color: #4b5563;
				font-size: 14px;
				line-height: 1.6;
				margin: 0 0 20px 0;
			}

			.epofw-discount-popup-cta {
				display: inline-block;
				background: linear-gradient(135deg, #036698 0%, #025a85 100%);
				color: #fff !important;
				font-size: 16px;
				font-weight: 600;
				padding: 14px 40px;
				border-radius: 8px;
				text-decoration: none;
				transition: all 0.3s ease;
				box-shadow: 0 4px 15px rgba(3, 102, 152, 0.4);
			}

			.epofw-discount-popup-cta:hover {
				background: linear-gradient(135deg, #025a85 0%, #024d72 100%);
				transform: translateY(-2px);
				box-shadow: 0 6px 20px rgba(3, 102, 152, 0.5);
				color: #fff !important;
				text-decoration: none;
			}

			/* Hide animation when closing */
			.epofw-discount-popup-overlay.epofw-closing {
				animation: epofwFadeOut 0.2s ease forwards;
			}

			.epofw-discount-popup-overlay.epofw-closing .epofw-discount-popup {
				animation: epofwScaleOut 0.2s ease forwards;
			}

			@keyframes epofwFadeOut {
				to { opacity: 0; }
			}

			@keyframes epofwScaleOut {
				to { transform: scale(0.9); opacity: 0; }
			}
		</style>

		<script>
		(function() {
			var overlay = document.getElementById('epofw-discount-popup-overlay');
			var closeBtn = document.getElementById('epofw-discount-popup-close');
			var ctaBtn = document.getElementById('epofw-discount-popup-cta');

			function dismissPopup(markAsDismissed) {
				overlay.classList.add('epofw-closing');

				setTimeout(function() {
					overlay.remove();
				}, 200);

				if (markAsDismissed) {
					var nonce = closeBtn.getAttribute('data-nonce');
					var xhr = new XMLHttpRequest();
					xhr.open('POST', '<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>', true);
					xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					xhr.send('action=epofw_dismiss_discount_popup&nonce=' + nonce);
				}
			}

			// Close button click
			closeBtn.addEventListener('click', function(e) {
				e.preventDefault();
				dismissPopup(true);
			});

			// CTA button click - dismiss but don't prevent default (opens link)
			ctaBtn.addEventListener('click', function() {
				dismissPopup(true);
			});

			// Click outside to close (but mark as dismissed)
			overlay.addEventListener('click', function(e) {
				if (e.target === overlay) {
					dismissPopup(true);
				}
			});

			// ESC key to close
			document.addEventListener('keydown', function(e) {
				if (e.key === 'Escape' && overlay) {
					dismissPopup(true);
				}
			});
		})();
		</script>
		<?php 
    }

    /**
     * AJAX handler for dismissing the popup.
     *
     * @since 4.4.5
     */
    public function ajax_dismiss_popup() {
        // Verify nonce.
        if ( !isset( $_POST['nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), self::NONCE_ACTION ) ) {
            wp_send_json_error( 'Invalid nonce' );
        }
        $current_user_id = get_current_user_id();
        if ( !$current_user_id ) {
            wp_send_json_error( 'Not logged in' );
        }
        // Store dismiss timestamp.
        $dismiss_time = time();
        update_user_meta( $current_user_id, self::DISMISS_META_KEY, $dismiss_time );
        /**
         * Fires after the discount popup has been dismissed by a user.
         *
         * @since 4.4.5
         *
         * @param int $current_user_id User ID who dismissed the popup.
         * @param int $dismiss_time    Timestamp when popup was dismissed.
         */
        do_action( 'epofw_discount_popup_dismissed', $current_user_id, $dismiss_time );
        wp_send_json_success();
    }

}

// Initialize the class.
new EPOFW_Discount_Popup();