<?php
/**
 * Pro Conversion Triggers — Free Edition
 *
 * 1. Slim, once-dismissed admin notice with a concrete Pro pitch (no widget counts).
 *
 * 2. In-editor Pro widget placeholder wiring (placeholder widgets are
 *    registered separately in modules/um-pro-widget-placeholders.php
 *    and display the upgrade prompt card inside Elementor's canvas).
 *
 * @package UM_Elementor_Free
 * @since   2.7
 */

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

class UM_Elementor_Pro_Conversion {

    /** Meta key used to permanently suppress the slim admin notice. */
    const NOTICE_META = 'umwfe_widget_count_notice_dismissed';

    /** AJAX action for the slim notice dismiss. */
    const AJAX_ACTION = 'umwfe_dismiss_widget_count_notice';

    /** Pro marketing URL. */
    const PRO_URL = 'https://userelements.com/ultimate-member-elementor/';

    public function __construct() {
        // ── Admin notice (wp-admin only) ──────────────────────────────────
        add_action( 'admin_notices',          [ $this, 'render_widget_count_notice' ] );
        add_action( 'admin_enqueue_scripts',  [ $this, 'enqueue_notice_assets' ] );
        add_action( 'wp_ajax_' . self::AJAX_ACTION, [ $this, 'handle_dismiss' ] );
    }

    // =========================================================================
    // Admin notice
    // =========================================================================

    /**
     * Only show on screens that make sense for a plugin notice.
     */
    private function is_relevant_screen(): bool {
        $screen = get_current_screen();
        if ( ! $screen ) {
            return false;
        }
        $allowed = [ 'plugins', 'dashboard', 'toplevel_page_elementor', 'edit-page', 'edit-post' ];
        return in_array( $screen->id, $allowed, true )
            || str_starts_with( $screen->id, 'elementor' );
    }

    /**
     * Render the slim widget-count notice (once; dismiss = forever).
     */
    public function render_widget_count_notice(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }
        if ( ! $this->is_relevant_screen() ) {
            return;
        }
        if ( get_user_meta( get_current_user_id(), self::NOTICE_META, true ) ) {
            return;
        }

        $nonce   = wp_create_nonce( self::AJAX_ACTION );
        $pro_url = esc_url( self::PRO_URL );

        printf(
            '<div class="notice notice-info umwfe-widget-count-notice" id="umwfe-widget-count-notice" data-nonce="%s">
                <span class="umwfe-wcn-bolt">⚡</span>
                <p class="umwfe-wcn-text">
                    %s
                    <a href="%s" target="_blank" class="umwfe-wcn-link">%s&nbsp;&rarr;</a>
                </p>
                <button type="button" class="umwfe-wcn-dismiss" aria-label="%s">&#10005;</button>
            </div>',
            esc_attr( $nonce ),
            esc_html__(
                'The free edition covers directories and UM form styling. Pro adds carousel, sortable tables with CSV export, standalone advanced filters, multi-column layouts, live search, account page styling, the profile page builder, native directory styling, and per-field visibility rules.',
                'ultimate-member-widgets-for-elementor'
            ),
            $pro_url,
            esc_html__( 'See what\'s in Pro', 'ultimate-member-widgets-for-elementor' ),
            esc_attr__( 'Dismiss this notice', 'ultimate-member-widgets-for-elementor' )
        );
    }

    /**
     * Inline the tiny CSS + JS needed for the slim notice.
     * Kept inline to avoid an extra HTTP request for < 1 KB of code.
     */
    public function enqueue_notice_assets(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }
        if ( get_user_meta( get_current_user_id(), self::NOTICE_META, true ) ) {
            return;
        }
        ?>
        <style id="umwfe-wcn-style">
        /* ── Slim widget-count admin notice ───────────────────────────────── */
        .umwfe-widget-count-notice {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 14px !important;
            border-left-color: #6366f1 !important;
            background: #1e1e38;
            border-radius: 0 4px 4px 0;
        }
        .umwfe-wcn-bolt {
            font-size: 18px;
            flex-shrink: 0;
            line-height: 1;
        }
        .umwfe-wcn-text {
            flex: 1;
            margin: 0 !important;
            font-size: 13px;
            color: #c8cde4;
            line-height: 1.5;
        }
        .umwfe-wcn-link {
            color: #818cf8;
            font-weight: 600;
            text-decoration: none;
            white-space: nowrap;
        }
        .umwfe-wcn-link:hover {
            color: #a5b4fc;
            text-decoration: underline;
        }
        .umwfe-wcn-dismiss {
            flex-shrink: 0;
            background: none;
            border: none;
            color: #6b7280;
            font-size: 14px;
            cursor: pointer;
            padding: 0 4px;
            line-height: 1;
            box-shadow: none;
        }
        .umwfe-wcn-dismiss:hover { color: #c8cde4; }
        </style>
        <script id="umwfe-wcn-script">
        (function(){
            document.addEventListener('DOMContentLoaded', function(){
                var notice = document.getElementById('umwfe-widget-count-notice');
                if ( ! notice ) return;
                notice.querySelector('.umwfe-wcn-dismiss').addEventListener('click', function(){
                    var nonce = notice.dataset.nonce;
                    notice.style.transition = 'opacity 0.2s';
                    notice.style.opacity    = '0';
                    setTimeout(function(){ notice.remove(); }, 250);
                    var fd = new FormData();
                    fd.append('action', '<?php echo esc_js( self::AJAX_ACTION ); ?>');
                    fd.append('_wpnonce', nonce);
                    fetch(<?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>, {
                        method: 'POST', body: fd, credentials: 'same-origin'
                    });
                });
            });
        }());
        </script>
        <?php
    }

    /**
     * AJAX: mark notice dismissed for this user, forever.
     */
    public function handle_dismiss(): void {
        if ( ! check_ajax_referer( self::AJAX_ACTION, '_wpnonce', false ) ) {
            wp_die( esc_html__( 'Security check failed.', 'ultimate-member-widgets-for-elementor' ) );
        }
        update_user_meta( get_current_user_id(), self::NOTICE_META, '1' );
        wp_die();
    }
}
