<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Sifency_Frontend_Popup {

    public function __construct() {
        if ( is_admin() ) return;

        // Render popup at footer
        add_action( 'wp_footer', [ $this, 'render_popup' ], 5 );

        // Enqueue JS for popup functionality
        add_action( 'wp_footer', [ $this, 'popup_js' ], 20 );
    }

    /**
     * Render Elementor Popup template
     */
    public function render_popup() {
        $popup_id = Sifency_Frontend_Helper::find_matching_template( 'popup' );
        if ( ! $popup_id ) return;

        echo '<!-- Sifency Custom Popup Start -->';
        echo '<div class="sifency-custom-popup">';
        echo wp_kses_post ( Sifency_Frontend_Helper::render_elementor_content( $popup_id, true ) );
        echo '<button class="sifency-popup-close">×</button>'; // Close button
        echo '</div>';
        echo '<!-- Sifency Custom Popup End -->';
    }

    /**
     * JS for popup open/close
     */
    public function popup_js() {
        ?>
        <script>
        (function(){
            const popup = document.querySelector('.sifency-custom-popup');
            const closeBtn = document.querySelector('.sifency-popup-close');

            if(!popup || !closeBtn) return;

            // Example: Show popup after 2 seconds
            setTimeout(() => {
                popup.style.display = 'block';
            }, 2000);

            // Close popup
            closeBtn.addEventListener('click', () => {
                popup.style.display = 'none';
            });

            window.addEventListener('click', (e) => {
                if(e.target === popup) popup.style.display = 'none';
            });

        })();
        </script>
        <?php
    }
}
