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


/**
 * Class to handle the duplicate SEO button in the left sidebar (under title)
 * This creates a secondary "Generate SEO Suggestions" button outside the metabox
 * for easier access on all entity types (posts, pages, categories, products)
 */
class Aysa_Sidebar_Seo_Button {

    public function __construct() {
        $this->init_hooks();
    }

    /**
     * Initialize WordPress hooks
     */
    private function init_hooks() {
        // Hook for posts and products only (pages use floating button)
        add_action('edit_form_after_title', array($this, 'add_seo_button_after_title'), 20);
        
        // Add floating button specifically for pages
        add_action('admin_print_footer_scripts', array($this, 'add_floating_button_for_pages'));
        
        // Hook for product categories and normal WordPress categories - add button in edit form
        add_action('product_cat_edit_form_fields', array($this, 'add_seo_button_category_edit'), 5);
        add_action('product_cat_add_form_fields', array($this, 'add_seo_button_category_add'), 5);
        add_action('category_edit_form_fields', array($this, 'add_seo_button_category_edit'), 5);
        add_action('category_add_form_fields', array($this, 'add_seo_button_category_add'), 5);
        
        // Enqueue styles and scripts
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts_styles'));
    }

    /**
     * Add SEO button after title for posts and pages
     */
    public function add_seo_button_after_title($post) {
        // Check if we already rendered a button for this post
        static $rendered_posts = array();
        if (in_array($post->ID, $rendered_posts)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA Sidebar Button: Button already rendered for post ID ' . $post->ID);
            }
            return;
        }

        // Debug logging (only if WP_DEBUG is enabled)
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA Sidebar Button: add_seo_button_after_title called for post type: ' . $post->post_type . ', ID: ' . $post->ID);
        }
        
        // Only show on supported post types (excluding pages which use floating button)
        $supported_types = array('post', 'product');
        if (!in_array($post->post_type, $supported_types)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA Sidebar Button: Post type ' . $post->post_type . ' not supported (pages use floating button)');
            }
            return;
        }

        // Don't show if the main metabox is not loaded
        if (!$this->should_show_button()) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA Sidebar Button: should_show_button returned false');
            }
            return;
        }

        $entity_type = $this->get_entity_type_from_post($post);
        $entity_id = $post->ID;
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA Sidebar Button: Rendering button for ' . $entity_type . ' with ID ' . $entity_id);
        }
        $this->render_seo_button($entity_type, $entity_id, 'post');
        $rendered_posts[] = $post->ID;
    }

    /**
     * Alternative method to add SEO button at form top
     */
    public function add_seo_button_form_top($post) {
        // Only show for pages if the after_title hook didn't work
        if ($post->post_type !== 'page') {
            return;
        }

        // Check if we already rendered a button for this post
        static $rendered_posts = array();
        if (in_array($post->ID, $rendered_posts)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA Sidebar Button: Button already rendered for post ID ' . $post->ID);
            }
            return;
        }

        if (!$this->should_show_button()) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA Sidebar Button: should_show_button returned false for form_top');
            }
            return;
        }

        $entity_type = 'Page';
        $entity_id = $post->ID;
        
        $this->render_seo_button($entity_type, $entity_id, 'form_top');
        $rendered_posts[] = $post->ID;
    }

    /**
     * Alternative method for page form hook
     */
    public function add_seo_button_page_form() {
        global $post, $pagenow, $typenow;
        
        if ($typenow !== 'page' || !in_array($pagenow, array('post.php', 'post-new.php'))) {
            return;
        }
        
        if (!$post || !$this->should_show_button()) {
            return;
        }
        
        // Check if we already rendered a button for this post
        static $rendered_posts = array();
        if (in_array($post->ID, $rendered_posts)) {
            return;
        }

        $this->render_seo_button('Page', $post->ID, 'page_form');
        $rendered_posts[] = $post->ID;
    }

    /**
     * Alternative method for advanced form hook
     */
    public function add_seo_button_advanced() {
        global $post, $pagenow, $typenow;
        
        if ($typenow !== 'page' || !in_array($pagenow, array('post.php', 'post-new.php'))) {
            return;
        }
        
        if (!$post || !$this->should_show_button()) {
            return;
        }
        
        // Check if we already rendered a button for this post
        static $rendered_posts = array();
        if (in_array($post->ID, $rendered_posts)) {
            return;
        }

        $this->render_seo_button('Page', $post->ID, 'advanced');
        $rendered_posts[] = $post->ID;
    }

    /**
     * Last resort: inject button via JavaScript
     */
    public function add_seo_button_via_js() {
        global $pagenow, $typenow, $post;
        
        // Only on page edit screens
        if (!in_array($pagenow, array('post.php', 'post-new.php')) || $typenow !== 'page') {
            return;
        }
        
        if (!$post || !$this->should_show_button()) {
            return;
        }
        
        ?>
        <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            // Try to find a good place to inject the button
            var titleWrap = document.getElementById('titlewrap');
            var postBody = document.getElementById('post-body-content');
            var target = titleWrap || postBody;
            
            if (target) {
                // Create button container
                var buttonContainer = document.createElement('div');
                buttonContainer.className = 'aysa-sidebar-seo-button-container';
                buttonContainer.style.margin = '15px 0';
                buttonContainer.style.padding = '15px';
                buttonContainer.style.background = '#f9f9f9';
                buttonContainer.style.border = '1px solid #ddd';
                buttonContainer.style.borderRadius = '5px';
                
                // Create button
                var button = document.createElement('button');
                button.type = 'button';
                button.className = 'button button-primary aysa-sidebar-generate-btn';
                button.setAttribute('data-entity-type', 'Page');
                button.setAttribute('data-entity-id', '<?php echo $post->ID; ?>');
                button.style.padding = '8px 16px';
                button.style.fontSize = '14px';
                button.style.minHeight = '36px';
                button.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>Generate SEO Suggestions';
                
                // Create info text
                var infoText = document.createElement('div');
                infoText.style.fontSize = '12px';
                infoText.style.color = '#666';
                infoText.style.marginTop = '5px';
                infoText.textContent = 'Quick access to AYSA SEO automation';
                
                buttonContainer.appendChild(button);
                buttonContainer.appendChild(infoText);
                
                // Insert after title or at top of content
                if (titleWrap && titleWrap.nextSibling) {
                    titleWrap.parentNode.insertBefore(buttonContainer, titleWrap.nextSibling);
                } else if (titleWrap) {
                    titleWrap.parentNode.appendChild(buttonContainer);
                } else if (postBody) {
                    postBody.insertBefore(buttonContainer, postBody.firstChild);
                }
                
            }
        });
        </script>
        <?php
    }

    /**
     * Add floating button specifically for pages
     */
    public function add_floating_button_for_pages() {
        global $pagenow, $typenow, $post;
        
        // Only on page edit screens
        if (!in_array($pagenow, array('post.php', 'post-new.php')) || $typenow !== 'page') {
            return;
        }
        
        if (!$post || !$this->should_show_button()) {
            return;
        }
        
        ?>
        <style>
        /* Floating button styles for pages */
        #aysa-floating-seo-button {
            position: fixed;
            top: 50%;
            left: 20px;
            transform: translateY(-50%);
            z-index: 999999;
            background: #2ea043;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 12px 20px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
            max-width: 200px;
            white-space: nowrap;
            overflow: hidden;
        }
        
        #aysa-floating-seo-button:hover {
            background: #238636;
            transform: translateY(-50%) scale(1.05);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
        }
        
        #aysa-floating-seo-button:active {
            transform: translateY(-50%) scale(0.98);
        }
        
        #aysa-floating-seo-button .aysa-icon {
            width: 18px;
            height: 18px;
            flex-shrink: 0;
        }
        
        #aysa-floating-seo-button .aysa-text {
            font-size: 13px;
        }
        
        /* Hide on mobile screens */
        @media (max-width: 768px) {
            #aysa-floating-seo-button {
                display: none;
            }
        }
        
        /* Adjust position if WordPress admin bar is present */
        .wp-toolbar #aysa-floating-seo-button {
            top: calc(50% + 16px);
        }
        
        /* Animation for button appearance */
        @keyframes aysa-slide-in {
            from {
                left: -200px;
                opacity: 0;
            }
            to {
                left: 20px;
                opacity: 1;
            }
        }
        
        #aysa-floating-seo-button.aysa-animate-in {
            animation: aysa-slide-in 0.5s ease-out;
        }
        </style>
        
        <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            // Remove any existing floating button
            var existingButton = document.getElementById('aysa-floating-seo-button');
            if (existingButton) {
                existingButton.remove();
            }
            
            // Create floating button
            var floatingButton = document.createElement('button');
            floatingButton.id = 'aysa-floating-seo-button';
            floatingButton.type = 'button';
            floatingButton.className = 'aysa-sidebar-generate-btn aysa-animate-in';
            floatingButton.setAttribute('data-entity-type', 'Page');
            floatingButton.setAttribute('data-entity-id', '<?php echo $post->ID; ?>');
            
            // Button content
            floatingButton.innerHTML = `
                <svg class="aysa-icon" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                </svg>
                <span class="aysa-text">Generate SEO</span>
            `;
            
            // Add to body
            document.body.appendChild(floatingButton);
            
            // Re-check and re-add button periodically in case the page content changes
            var checkInterval = setInterval(function() {
                var existingBtn = document.getElementById('aysa-floating-seo-button');
                if (!existingBtn && document.body) {
                    var newBtn = floatingButton.cloneNode(true);
                    document.body.appendChild(newBtn);
                }
            }, 3000);
            
            // Clean up interval after 30 seconds
            setTimeout(function() {
                clearInterval(checkInterval);
            }, 30000);
            
            // Handle Gutenberg editor changes
            if (typeof wp !== 'undefined' && wp.data && wp.data.subscribe) {
                wp.data.subscribe(function() {
                    var btn = document.getElementById('aysa-floating-seo-button');
                    if (!btn && document.body) {
                        var newBtn = floatingButton.cloneNode(true);
                        document.body.appendChild(newBtn);
                    }
                });
            }
        });
        
        // Handle page visibility changes
        document.addEventListener('visibilitychange', function() {
            if (!document.hidden) {
                setTimeout(function() {
                    var btn = document.getElementById('aysa-floating-seo-button');
                    if (!btn && document.body) {
                        var floatingButton = document.createElement('button');
                        floatingButton.id = 'aysa-floating-seo-button';
                        floatingButton.type = 'button';
                        floatingButton.className = 'aysa-sidebar-generate-btn';
                        floatingButton.setAttribute('data-entity-type', 'Page');
                        floatingButton.setAttribute('data-entity-id', '<?php echo $post->ID; ?>');
                        floatingButton.innerHTML = `
                            <svg class="aysa-icon" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                            </svg>
                            <span class="aysa-text">Generate SEO</span>
                        `;
                        document.body.appendChild(floatingButton);
                    }
                }, 500);
            }
        });
        </script>
        <?php
    }

    /**
     * Add SEO button for category edit form
     */
    public function add_seo_button_category_edit($term) {
        // Check if we already rendered a button for this term
        static $rendered_terms = array();
        if (in_array($term->term_id, $rendered_terms)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA Sidebar Button: Button already rendered for term ID ' . $term->term_id);
            }
            return;
        }

        if (!$this->should_show_button()) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA Sidebar Button: should_show_button returned false for category');
            }
            return;
        }

        $entity_type = 'Category';
        $entity_id = $term->term_id;
        
        $this->render_seo_button($entity_type, $entity_id, 'category_edit');
        $rendered_terms[] = $term->term_id;
    }

    /**
     * Add SEO button for category add form
     */
    public function add_seo_button_category_add() {
        if (!$this->should_show_button()) {
            return;
        }

        $entity_type = 'Category';
        $entity_id = 0; // New category
        
        $this->render_seo_button($entity_type, $entity_id, 'category_add');
    }

    /**
     * Render the SEO button HTML
     */
    private function render_seo_button($entity_type, $entity_id, $context) {
        ?>
        <div class="aysa-sidebar-seo-button-container" data-entity-type="<?php echo esc_attr($entity_type); ?>" data-entity-id="<?php echo esc_attr($entity_id); ?>" data-context="<?php echo esc_attr($context); ?>">
            <?php if ($context === 'category_edit' || $context === 'category_add'): ?>
                <tr class="form-field">
                    <th scope="row">
                        <label>AYSA SEO</label>
                    </th>
                    <td>
            <?php endif; ?>
            
            <div class="aysa-sidebar-seo-wrapper">
                <button type="button" 
                        class="button button-primary aysa-sidebar-generate-btn" 
                        id="aysa-sidebar-generate-<?php echo esc_attr($context); ?>-<?php echo esc_attr($entity_id); ?>"
                        data-entity-type="<?php echo esc_attr($entity_type); ?>" 
                        data-entity-id="<?php echo esc_attr($entity_id); ?>"
                        style="margin: 10px 0; padding: 8px 16px; font-size: 14px; min-height: 36px;">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;">
                        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                    </svg>
                    Generate SEO Suggestions
                </button>
                <div class="aysa-sidebar-button-info" style="font-size: 12px; color: #666; margin-top: 5px;">
                    Quick access to AYSA SEO automation
                </div>
            </div>
            

            <?php if ($context === 'category_edit' || $context === 'category_add'): ?>
                    </td>
                </tr>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Determine if the button should be shown
     */
    private function should_show_button() {
        // Check if AYSA is properly configured
        $project_id = get_option('aysa_project_id', 0);
        if (empty($project_id)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA Sidebar Button: No project ID found');
            }
            return false;
        }

        // Check if user has the capability
        if (!current_user_can('edit_posts')) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA Sidebar Button: User does not have edit_posts capability');
            }
            return false;
        }

        return true;
    }

    /**
     * Get entity type from post object
     */
    private function get_entity_type_from_post($post) {
        switch ($post->post_type) {
            case 'product':
                return 'Product';
            case 'page':
                return 'Page';
            case 'post':
                return 'Post';
            default:
                return 'Page';
        }
    }

    /**
     * Enqueue styles and scripts
     */
    public function enqueue_scripts_styles($hook) {
        // Only load on edit screens
        if (!in_array($hook, array('post.php', 'post-new.php', 'edit-tags.php', 'term.php'))) {
            return;
        }

        // Enqueue the main AYSA scripts that contain the handleGenerateSuggestions function
        wp_enqueue_script('aysa-actions');
        
        // Try to enqueue aysa-metabox if it exists
        $metabox_script_path = AYSA_PLUGIN_URL . 'admin/js/aysa-metabox.js';
        if (file_exists(AYSA_PLUGIN_DIR . 'admin/js/aysa-metabox.js')) {
            wp_enqueue_script(
                'aysa-metabox-sidebar',
                $metabox_script_path,
                array('jquery', 'aysa-actions'),
                AYSA_VERSION . '.' . time(),
                true
            );
        }
        
        // Add our custom script for the sidebar button
        wp_add_inline_script('aysa-actions', $this->get_sidebar_button_script(), 'after');
        
        // Add custom styles - use the main plugin CSS handle
        wp_add_inline_style('aysa-automation', $this->get_sidebar_button_styles());
    }

    /**
     * Get the JavaScript for the sidebar button
     */
    private function get_sidebar_button_script() {
        return "
        document.addEventListener('DOMContentLoaded', function() {
            // Wait for main AYSA scripts to load
            function initSidebarButtons() {
                const sidebarButtons = document.querySelectorAll('.aysa-sidebar-generate-btn');
                
                sidebarButtons.forEach(function(button) {
                    if (button._aysaSidebarListener) {
                        return; // Already has listener
                    }
                    
                    button.addEventListener('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        // Try multiple ways to call the handleGenerateSuggestions function
                        let functionCalled = false;
                        
                        // Method 1: Check window.handleGenerateSuggestions
                        if (typeof window.handleGenerateSuggestions === 'function') {
                            window.handleGenerateSuggestions(e);
                            functionCalled = true;
                        }
                        // Method 2: Check global handleGenerateSuggestions
                        else if (typeof handleGenerateSuggestions === 'function') {
                            handleGenerateSuggestions(e);
                            functionCalled = true;
                        }
                        // Method 3: Try to find it in the global scope
                        else if (window.handleGenerateSuggestions) {
                            window.handleGenerateSuggestions(e);
                            functionCalled = true;
                        }
                        
                        // Fallback: trigger the main button if function not found
                        if (!functionCalled) {
                            const mainButton = document.getElementById('generate-suggestions-btn');
                            if (mainButton) {
                                mainButton.click();
                                functionCalled = true;
                            }
                        }
                        
                        // Last resort: show error message
                        if (!functionCalled) {
                            alert('AYSA SEO functionality is not loaded. Please refresh the page and try again.');
                        }
                    });
                    
                    button._aysaSidebarListener = true;
                });
            }
            
            // Try to initialize immediately
            initSidebarButtons();
            
            // Also try after a delay to catch dynamically loaded content
            setTimeout(initSidebarButtons, 1000);
            setTimeout(initSidebarButtons, 3000);
            
            // Watch for DOM changes (in case buttons are added dynamically)
            const observer = new MutationObserver(function(mutations) {
                let shouldReinit = false;
                mutations.forEach(function(mutation) {
                    if (mutation.addedNodes.length > 0) {
                        mutation.addedNodes.forEach(function(node) {
                            if (node.nodeType === 1 && 
                                (node.classList.contains('aysa-sidebar-generate-btn') || 
                                 node.querySelector('.aysa-sidebar-generate-btn'))) {
                                shouldReinit = true;
                            }
                        });
                    }
                });
                
                if (shouldReinit) {
                    setTimeout(initSidebarButtons, 100);
                }
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        });
        ";
    }

    /**
     * Get the CSS styles for the sidebar button
     */
    private function get_sidebar_button_styles() {
        return "
        .aysa-sidebar-seo-button-container {
            margin: 15px 0;
            padding: 15px;
            background: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .aysa-sidebar-seo-wrapper {
            text-align: center;
        }
        
        .aysa-sidebar-generate-btn {
            background: #2271b1 !important;
            border-color: #2271b1 !important;
            color: #fff !important;
            transition: all 0.3s ease;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        
        .aysa-sidebar-generate-btn:hover {
            background: #135e96 !important;
            border-color: #135e96 !important;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .aysa-sidebar-generate-btn:focus {
            box-shadow: 0 0 0 2px #2271b1;
        }
        
        .aysa-sidebar-generate-btn svg {
            flex-shrink: 0;
        }
        
        .aysa-sidebar-button-info {
            font-style: italic;
        }
        
        /* Category form specific styles */
        .form-field .aysa-sidebar-seo-wrapper {
            text-align: left;
        }
        
        /* Post/Page specific styles */
        .post-php .aysa-sidebar-seo-button-container,
        .post-new-php .aysa-sidebar-seo-button-container {
            margin: 20px 0;
            max-width: 600px;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .aysa-sidebar-seo-button-container {
                margin: 10px 0;
                padding: 10px;
            }
            
            .aysa-sidebar-generate-btn {
                width: 100%;
                justify-content: center;
            }
        }
        ";
    }
}

// Initialize the class
new Aysa_Sidebar_Seo_Button();
