<?php
defined('ABSPATH') || exit;

class SITSEL_Review_Notice {

    const ACTIVATION_OPTION = 'sitsel_activation_time';
    const DISMISS_OPTION    = 'sitsel_review_dismissed';
    const NONCE             = 'sitsel_review_nonce';

    public static function init() {
        add_action('admin_notices', [__CLASS__, 'show_notice']);
        add_action('wp_ajax_sitsel_dismiss_review_notice', [__CLASS__, 'dismiss_notice']);
    }

    /**
     * Called via activation hook
     */
    public static function activate() {
        if (!get_option(self::ACTIVATION_OPTION)) {
            update_option(self::ACTIVATION_OPTION, time());
        }
    }

    public static function show_notice() {

        if (!current_user_can('manage_options')) {
            return;
        }

        if (get_option(self::DISMISS_OPTION)) {
            return;
        }

        $activation_time = get_option(self::ACTIVATION_OPTION);
        if (!$activation_time) {
            return;
        }

        //  For testing (remove later)
        if ((time() - $activation_time) < 7 * DAY_IN_SECONDS) return;
        ?>
        <div class="notice notice-success is-dismissible sitsel-review-notice">
            <p>
                <strong><?php esc_html_e('Enjoying Softech Addons for Elementor?', 'softech-addons-for-elementor'); ?></strong><br>
                <?php esc_html_e('Please rate the plugin to support development.', 'softech-addons-for-elementor'); ?>
            </p>
            <p>
                <a href="https://wordpress.org/support/plugin/softech-addons-for-elementor/reviews/?rate=5#new-post"
                   target="_blank"
                   rel="noopener noreferrer"
                   class="button button-primary">
                    <?php esc_html_e('Rate the Plugin', 'softech-addons-for-elementor'); ?>
                </a>
            </p>
        </div>

        <script>
        jQuery(document).on('click', '.sitsel-review-notice .notice-dismiss', function () {
            jQuery.post(ajaxurl, {
                action: 'sitsel_dismiss_review_notice',
                _ajax_nonce: '<?php echo esc_js(wp_create_nonce(self::NONCE)); ?>'
            });
        });
        </script>
        <?php
    }

    public static function dismiss_notice() {
        check_ajax_referer(self::NONCE);
        update_option(self::DISMISS_OPTION, 1);
        wp_send_json_success();
    }
}
