<?php
/**
 * Handle major update notifications for Event Monster plugin.
 * 
 * Shows a dismissible admin notice banner when users upgrade to a new major version,
 * and provides a "What's New" admin page.
 *
 * @package Event_Monster
 * @since 4.0.0
 */

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

class Event_Monster_Free_Update_Notice
{
    /**
     * The current plugin version.
     * @var string
     */
    private $current_version;

    /**
     * Option name for storing dismissed state.
     * @var string
     */
    private $dismiss_option = 'em_update_notice_dismissed';

    /**
     * Option name for storing the version when notice was dismissed.
     * @var string
     */
    private $dismiss_version_option = 'em_update_notice_dismissed_version';

    /**
     * Option name for storing previous version before update.
     * @var string
     */
    private $previous_version_option = 'em_previous_version';

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->current_version = defined('EM_FREE_VERSION') ? EM_FREE_VERSION : '4.0.0';
        
        // Track version changes
        $this->track_version();
        
        // Add admin notice
        add_action('admin_notices', array($this, 'display_update_notice'));
        
        // Add What's New page
        add_action('admin_menu', array($this, 'add_whats_new_page'), 99);
        
        // AJAX handler for dismissing notice
        add_action('wp_ajax_em_dismiss_update_notice', array($this, 'ajax_dismiss_notice'));
        
        // Enqueue admin scripts for dismiss functionality
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
    }

    /**
     * Track version changes to detect upgrades.
     */
    private function track_version()
    {
        $stored_version = get_option($this->previous_version_option, '');
        
        // If this is a new install (no previous version), store current version
        // and mark notice as dismissed (don't show to new users)
        if (empty($stored_version)) {
            update_option($this->previous_version_option, $this->current_version);
            update_option($this->dismiss_option, true);
            update_option($this->dismiss_version_option, $this->current_version);
            return;
        }
        
        // If version changed, update stored version and reset dismiss state
        if (version_compare($stored_version, $this->current_version, '<')) {
            update_option($this->previous_version_option, $this->current_version);
            // Reset dismiss state for new version
            delete_option($this->dismiss_option);
            delete_option($this->dismiss_version_option);
        }
    }

    /**
     * Check if the update notice should be shown.
     * @return bool
     */
    private function should_show_notice()
    {
        // Don't show if already dismissed for this version
        $dismissed = get_option($this->dismiss_option, false);
        $dismissed_version = get_option($this->dismiss_version_option, '');
        
        if ($dismissed && $dismissed_version === $this->current_version) {
            return false;
        }
        
        // Only show on Event Monster admin pages or main dashboard
        $screen = get_current_screen();
        if (!$screen) {
            return false;
        }
        
        // Show on all admin pages for better visibility
        return true;
    }

    /**
     * Display the update notice banner.
     */
    public function display_update_notice()
    {
        if (!$this->should_show_notice()) {
            return;
        }
        
        $whats_new_url = admin_url('admin.php?page=em-whats-new');
        ?>
        <div class="notice notice-info is-dismissible em-update-notice" id="em-update-notice">
            <div style="display: flex; align-items: center; padding: 10px 0;">
                <div style="flex-shrink: 0; margin-right: 15px;">
                    <span style="display: inline-flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); border-radius: 8px;">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M2 17L12 22L22 17" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M2 12L12 17L22 12" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </span>
                </div>
                <div style="flex: 1;">
                    <h3 style="margin: 0 0 5px 0; font-size: 14px; font-weight: 600; color: #1e293b;">
                        🎉 <?php printf(__('Event Monster %s - Major Update!', 'event-monster'), $this->current_version); ?>
                    </h3>
                    <p style="margin: 0; color: #64748b; font-size: 13px;">
                        <?php _e('This version includes a completely redesigned interface, new event list layouts, and improved performance.', 'event-monster'); ?>
                        <strong><?php _e('Your existing events and data are preserved.', 'event-monster'); ?></strong>
                    </p>
                </div>
                <div style="flex-shrink: 0; margin-left: 15px;">
                    <a href="<?php echo esc_url($whats_new_url); ?>" class="button button-primary" style="margin-right: 8px;">
                        <?php _e('See What\'s New', 'event-monster'); ?>
                    </a>
                    <button type="button" class="button em-dismiss-notice" id="em-dismiss-update-notice">
                        <?php _e('Dismiss', 'event-monster'); ?>
                    </button>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Add What's New admin page.
     */
    public function add_whats_new_page()
    {
        add_submenu_page(
            'edit.php?post_type=awl_event_monster',
            __('What\'s New', 'event-monster'),
            __('What\'s New', 'event-monster'),
            'manage_options',
            'em-whats-new',
            array($this, 'render_whats_new_page')
        );
    }

    /**
     * Render the What's New admin page.
     */
    public function render_whats_new_page()
    {
        include EM_FREE_PLUGIN_DIR . 'templates/admin/whats-new.php';
    }

    /**
     * Enqueue admin scripts for notice functionality.
     */
    public function enqueue_admin_scripts()
    {
        if (!$this->should_show_notice()) {
            return;
        }
        
        wp_add_inline_script('jquery', '
            jQuery(document).ready(function($) {
                // Handle custom dismiss button click
                $("#em-dismiss-update-notice").on("click", function(e) {
                    e.preventDefault();
                    $.ajax({
                        url: ajaxurl,
                        type: "POST",
                        data: {
                            action: "em_dismiss_update_notice",
                            nonce: "' . wp_create_nonce('em_dismiss_notice') . '"
                        },
                        success: function() {
                            $("#em-update-notice").fadeOut();
                        }
                    });
                });
                
                // Also handle WordPress default dismiss button
                $(document).on("click", "#em-update-notice .notice-dismiss", function() {
                    $.ajax({
                        url: ajaxurl,
                        type: "POST",
                        data: {
                            action: "em_dismiss_update_notice",
                            nonce: "' . wp_create_nonce('em_dismiss_notice') . '"
                        }
                    });
                });
            });
        ');
    }

    /**
     * AJAX handler for dismissing the notice.
     */
    public function ajax_dismiss_notice()
    {
        check_ajax_referer('em_dismiss_notice', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }
        
        update_option($this->dismiss_option, true);
        update_option($this->dismiss_version_option, $this->current_version);
        
        wp_send_json_success();
    }
}
