<?php

namespace Flyerimage\Core\Init;

/**
 * Onboarding Notice Class
 * Displays welcome notice on first plugin activation
 * 
 * @author Pritom Kumar Mondal <pritomkucse@gmail.com>
 */
class OnboardingNotice
{
    /**
     * Option key for tracking notice display
     */
    const NOTICE_KEY = 'flyerimage_onboarding_notice_shown';

    /**
     * Initialize the class
     */
    public function __construct()
    {
        add_action('admin_notices', [$this, 'display_notice']);
        add_action('wp_ajax_flyerimage_dismiss_notice', [$this, 'dismiss_notice']);
    }

    /**
     * Display the onboarding notice
     * 
     * @return void
     */
    public function display_notice()
    {
        // Only show to users who can manage options
        if (!current_user_can('manage_options')) {
            return;
        }

        // Check if notice has already been dismissed
        if (get_option(self::NOTICE_KEY)) {
            return;
        }

        // Check if at least one campaign exists
        $campaign_count = $this->get_campaign_count();
        if ($campaign_count > 0) {
            // Mark notice as shown if campaigns exist
            update_option(self::NOTICE_KEY, 1);
            return;
        }

        // Only show on dashboard and plugins page
        $screen = get_current_screen();
        if ($screen && in_array($screen->id, ['dashboard', 'plugins'])) {
            $this->render_notice();
        }
    }

    /**
     * Render the notice HTML
     * 
     * @return void
     */
    private function render_notice()
    {
        $nonce = wp_create_nonce('flyerimage_dismiss_notice_nonce');
        $admin_url = admin_url('admin.php?page=flyer-image&action=new');
        ?>
        <div class="notice notice-success is-dismissible flyerimage-onboarding-notice" data-nonce="<?php echo esc_attr($nonce); ?>">
            <p>
                <strong><?php esc_html_e('Welcome to Flyer Image! 🎉', 'flyerimage'); ?></strong>
            </p>
            <p>
                <?php esc_html_e('Get started by creating your first campaign and reach your audience with amazing visual content.', 'flyerimage'); ?>
            </p>
            <p>
                <a href="<?php echo esc_url($admin_url); ?>" class="button button-primary">
                    <?php esc_html_e('Create Your First Campaign', 'flyerimage'); ?>
                </a>
                <button type="button" class="button button-secondary flyerimage-dismiss-notice">
                    <?php esc_html_e('Dismiss', 'flyerimage'); ?>
                </button>
            </p>
        </div>

        <style>
            .flyerimage-onboarding-notice {
                border-left: 4px solid #0073aa;
                padding: 12px;
            }
            .flyerimage-onboarding-notice p {
                margin: 8px 0;
            }
            .flyerimage-onboarding-notice .button {
                margin-right: 10px;
            }
        </style>

        <script>
            jQuery(document).ready(function($) {
                $(document).on('click', '.flyerimage-dismiss-notice', function(e) {
                    e.preventDefault();
                    var nonce = $('.flyerimage-onboarding-notice').data('nonce');
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'flyerimage_dismiss_notice',
                            nonce: nonce
                        },
                        success: function() {
                            $('.flyerimage-onboarding-notice').fadeOut('fast', function() {
                                $(this).remove();
                            });
                        }
                    });
                });
            });
        </script>
        <?php
    }

    /**
     * Handle notice dismissal via AJAX
     * 
     * @return void
     */
    public function dismiss_notice()
    {
        // Check nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'flyerimage_dismiss_notice_nonce')) {
            wp_send_json_error(['message' => 'Invalid nonce'], 403);
            return;
        }

        // Check capability
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions'], 403);
            return;
        }

        // Mark notice as dismissed
        update_option(self::NOTICE_KEY, 1);
        wp_send_json_success(['message' => 'Notice dismissed']);
    }

    /**
     * Get count of existing campaigns
     * 
     * @return int
     */
    private function get_campaign_count()
    {
        global $wpdb;
        
        // Get table name with proper prefix
        $table_prefix = "fiV102030858_";
        $table_name = esc_sql($wpdb->prefix . $table_prefix . 'flyer_images');
        
        // Count campaigns
        $count = $wpdb->get_var("SELECT COUNT(*) FROM `{$table_name}`");
        return intval($count);
    }

    /**
     * Reset the notice flag (useful for testing or plugin reset)
     * 
     * @return void
     */
    public static function reset_notice()
    {
        delete_option(self::NOTICE_KEY);
    }

    /**
     * Mark notice as shown
     * 
     * @return void
     */
    public static function mark_notice_shown()
    {
        update_option(self::NOTICE_KEY, 1);
    }
}
