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


/**
 * Class responsible for displaying meta title, description and keywords on the front-end
 * based on the data entered in the AYSA metabox
 */
class Aysa_Meta_Tags {
    
    private $debug;
    private $audit_logger;
    private $confidence_scorer;

    private function get_project_id_for_wallet() {
        if (function_exists('get_option')) {
            return max(0, intval(get_option('aysa_project_id', 0)));
        }

        return 0;
    }

    private function track_wallet_usage($action_key, $reference, $fallback_cost_cents, $meta = array(), $endpoint = '') {
        if (!function_exists('aysa_get_wallet_manager')) {
            return;
        }

        $project_id = $this->get_project_id_for_wallet();
        if ($project_id <= 0) {
            return;
        }

        $wallet_manager = aysa_get_wallet_manager();
        if (!$wallet_manager || !method_exists($wallet_manager, 'track_action_usage')) {
            return;
        }

        $wallet_manager->track_action_usage($project_id, $action_key, $reference, array(
            'meta' => is_array($meta) ? $meta : array(),
            'fallback_cost_cents' => max(0, intval($fallback_cost_cents)),
            'endpoint' => $endpoint,
            'billing_authority' => 'plugin_wallet',
        ));
    }
    
    /**
     * Initialize the class and set up hooks
     */
    public function __construct() {
        // Debug flag - set to true to see debug info
        $this->debug = true; // Force debug mode on to help troubleshoot
        
        if ($this->debug) {
            aysa_debug_log("AYSA SEO: Meta Tags class initialized");
        }
        
        // Add meta tags directly to the head with highest priority
        add_action('wp_head', array($this, 'output_meta_tags'), 0);
        
        // Add direct output for the title tag
        add_action('wp_head', array($this, 'output_title_tag'), 0);
        
        // ✅ HTML <title> tag filters (for browser title bar / tab title)
        add_filter('pre_get_document_title', array($this, 'override_document_title'), 9999);
        add_filter('wp_title', array($this, 'modify_wp_title'), 9999, 3);
        add_filter('document_title_parts', array($this, 'modify_document_title_parts'), 9999);
        
        // ✅ FIXED: H1 title filter (now excludes individual products/posts/pages to preserve original titles)
        add_filter('the_title', array($this, 'filter_the_title'), 9999, 2);
        
        // ✅ WooCommerce specific hooks (for shop pages, categories, but NOT individual products)
        add_filter('woocommerce_page_title', array($this, 'modify_woocommerce_title'), 9999);
        add_filter('woocommerce_product_taxonomy_title', array($this, 'modify_woocommerce_category_title'), 9999);
        
        // Add debug output to footer
        add_action('wp_footer', array($this, 'output_debug_info'));
        
        $this->audit_logger = class_exists('Aysa_Audit_Logger') ? new Aysa_Audit_Logger() : null;
        $this->confidence_scorer = class_exists('Aysa_Confidence_Scorer') ? new Aysa_Confidence_Scorer() : null;
        
        add_action('wp_ajax_aysa_generate_meta_tags', array($this, 'ajax_generate_meta_tags'));
    }
    
    /**
     * AJAX handler for generating meta tags
     */
    public function ajax_generate_meta_tags() {
        check_ajax_referer('aysa_nonce', 'nonce');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => 'You do not have permission to generate meta tags.'));
            return;
        }
        
        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        
        if (!$post_id) {
            wp_send_json_error(array('message' => 'Invalid post ID.'));
            return;
        }
        
        $post = get_post($post_id);
        if (!$post) {
            wp_send_json_error(array('message' => 'Post not found.'));
            return;
        }
        
        $meta_title = $post->post_title . ' | ' . get_bloginfo('name');
        $meta_description = wp_trim_words($post->post_content, 20, '...');
        
        $confidence_score = null;
        if ($this->confidence_scorer) {
            $confidence_score = $this->confidence_scorer->calculate_meta_confidence($post_id, $meta_title, $meta_description);
        }
        
        $old_meta_title = get_post_meta($post_id, '_aysa_meta_title', true);
        $old_meta_description = get_post_meta($post_id, '_aysa_meta_description', true);
        
        update_post_meta($post_id, '_aysa_meta_title', $meta_title);
        update_post_meta($post_id, '_aysa_meta_description', $meta_description);
        
        if ($this->audit_logger) {
            $this->audit_logger->log_action(
                'meta_generation',
                $post_id,
                'post',
                array(
                    'meta_title' => $old_meta_title,
                    'meta_description' => $old_meta_description
                ),
                array(
                    'meta_title' => $meta_title,
                    'meta_description' => $meta_description
                ),
                $confidence_score,
                false
            );
        }
        
        do_action('aysa_automation_completed', array(
            'action_type' => 'meta_generation',
            'object_id' => $post_id,
            'object_type' => 'post',
            'confidence_score' => $confidence_score,
            'data' => array(
                'meta_title' => $meta_title,
                'meta_description' => $meta_description
            )
        ));

        $this->track_wallet_usage(
            'aysa_generate_meta_tags',
            'generate_meta_tags:' . $post_id,
            55,
            array(
                'module' => 'on_page_optimization',
                'post_id' => intval($post_id),
                'post_type' => (string) ($post->post_type ?? 'post'),
            ),
            '/wp_ajax/aysa_generate_meta_tags'
        );
        
        wp_send_json_success(array(
            'message' => 'Meta tags generated successfully',
            'meta_title' => $meta_title,
            'meta_description' => $meta_description,
            'confidence_score' => $confidence_score
        ));
    }

    /**
     * Get SEO data for the current page/post/category using multiple fallback methods
     * 
     * @return array SEO data with meta_title, meta_description, and meta_keywords
     */
    private function get_seo_data() {
        $seo_data = array(
            'meta_title' => '',
            'meta_description' => '',
            'meta_keywords' => '',
            'robots_meta' => array()
        );
        
        if ($this->debug) {
            aysa_debug_log("AYSA SEO: get_seo_data called for URL: " . $_SERVER['REQUEST_URI']);
        }
        
        // Try to determine if this is a category/taxonomy page first
        $term = null;
        $is_category_page = false;
        
        if (is_category() || is_tag() || is_tax() || 
            (function_exists('is_product_category') && is_product_category()) || 
            (function_exists('is_product_tag') && is_product_tag())) {
            
            $is_category_page = true;
            $term = get_queried_object();
            
            if ($this->debug) {
                aysa_debug_log("AYSA SEO: Detected category/taxonomy page");
                if ($term && isset($term->term_id)) {
                    aysa_debug_log("AYSA SEO: Term ID: {$term->term_id}, Taxonomy: {$term->taxonomy}");
                } else {
                    aysa_debug_log("AYSA SEO: Term object not available");
                }
            }
        }
        
        // Process category/taxonomy pages
        if ($is_category_page && $term && isset($term->term_id)) {
            $term_id = $term->term_id;
            
            $meta_title = get_term_meta($term_id, '_aysa_seo_title', true);
            $meta_description = get_term_meta($term_id, '_aysa_seo_description', true);
            $meta_keywords = get_term_meta($term_id, '_aysa_seo_keywords', true);
            
            if ($this->debug) {
                aysa_debug_log("AYSA SEO: Term meta data - Title: {$meta_title}, Description: {$meta_description}, Keywords: {$meta_keywords}");
            }
            
            // Set SEO data if available
            if ($meta_title) {
                $seo_data['meta_title'] = $meta_title;
                if ($this->debug) {
                    aysa_debug_log("AYSA SEO: Found meta title for term: {$seo_data['meta_title']}");
                }
            }
            if ($meta_description) {
                $seo_data['meta_description'] = $meta_description;
            }
            if ($meta_keywords) {
                $seo_data['meta_keywords'] = $meta_keywords;
            }
            
            if (empty($seo_data['meta_title']) || empty($seo_data['meta_description']) || empty($seo_data['meta_keywords'])) {
                $keyword_data = get_term_meta($term_id, 'aysa_keyword_data', true);
                if (is_array($keyword_data)) {
                    if (empty($seo_data['meta_title']) && !empty($keyword_data['meta_title'])) {
                        $seo_data['meta_title'] = $keyword_data['meta_title'];
                        if ($this->debug) {
                            aysa_debug_log("AYSA SEO: Using fallback meta title for term: {$seo_data['meta_title']}");
                        }
                    }
                    if (empty($seo_data['meta_description']) && !empty($keyword_data['meta_description'])) {
                        $seo_data['meta_description'] = $keyword_data['meta_description'];
                    }
                    if (empty($seo_data['meta_keywords']) && !empty($keyword_data['meta_keywords'])) {
                        $seo_data['meta_keywords'] = $keyword_data['meta_keywords'];
                    }
                }
            }
            
            // Try to get robots meta
            $robots_meta = get_term_meta($term_id, 'aysa_robots_meta', true);
            if (is_array($robots_meta)) {
                $seo_data['robots_meta'] = $robots_meta;
            }
        } 
        // Process posts, pages, and custom post types
        elseif (is_singular()) {
            $post_id = get_the_ID();
            
            if ($this->debug) {
                aysa_debug_log("AYSA SEO: Getting data for singular post ID: {$post_id}");
            }
            
            $meta_title = get_post_meta($post_id, '_aysa_seo_title', true);
            $meta_description = get_post_meta($post_id, '_aysa_seo_description', true);
            $meta_keywords = get_post_meta($post_id, '_aysa_seo_keywords', true);
            
            if ($this->debug) {
                aysa_debug_log("AYSA SEO: Post meta data - Title: {$meta_title}, Description: {$meta_description}, Keywords: {$meta_keywords}");
            }
            
            // Set SEO data if available
            if ($meta_title) {
                $seo_data['meta_title'] = $meta_title;
            }
            if ($meta_description) {
                $seo_data['meta_description'] = $meta_description;
            }
            if ($meta_keywords) {
                $seo_data['meta_keywords'] = $meta_keywords;
            }
            
            if (empty($seo_data['meta_title']) || empty($seo_data['meta_description']) || empty($seo_data['meta_keywords'])) {
                $keyword_data = get_post_meta($post_id, 'aysa_keyword_data', true);
                if (is_array($keyword_data)) {
                    if (empty($seo_data['meta_title']) && !empty($keyword_data['meta_title'])) {
                        $seo_data['meta_title'] = $keyword_data['meta_title'];
                        if ($this->debug) {
                            aysa_debug_log("AYSA SEO: Using fallback meta title for post: {$seo_data['meta_title']}");
                        }
                    }
                    if (empty($seo_data['meta_description']) && !empty($keyword_data['meta_description'])) {
                        $seo_data['meta_description'] = $keyword_data['meta_description'];
                    }
                    if (empty($seo_data['meta_keywords']) && !empty($keyword_data['meta_keywords'])) {
                        $seo_data['meta_keywords'] = $keyword_data['meta_keywords'];
                    }
                }
            }
            
            // Get robots meta
            $robots_meta = get_post_meta($post_id, 'aysa_robots_meta', true);
            if (is_array($robots_meta)) {
                $seo_data['robots_meta'] = $robots_meta;
            }
        }
        
        if ($this->debug) {
            aysa_debug_log("AYSA SEO: Final SEO data: " . print_r($seo_data, true));
        }
        
        return $seo_data;
    }
    
    /**
     * Override document title completely (highest priority way to set the title)
     * 
     * @param string $title The title to be filtered
     * @return string The modified title
     */
    public function override_document_title($title) {
        $seo_data = $this->get_seo_data();
        
        if (!empty($seo_data['meta_title'])) {
            return $seo_data['meta_title'];
        }
        
        return $title;
    }
    
    /**
     * Filter to modify the title for older WordPress versions
     * 
     * @param string $title The original title
     * @param string $sep The separator
     * @param string $seplocation The separator location
     * @return string The modified title
     */
    public function modify_wp_title($title, $sep, $seplocation) {
        $seo_data = $this->get_seo_data();
        
        if (!empty($seo_data['meta_title'])) {
            return $seo_data['meta_title'];
        }
        
        return $title;
    }
    
    /**
     * Filter to modify document title parts for newer WordPress versions
     * 
     * @param array $title_parts The title parts
     * @return array The modified title parts
     */
    public function modify_document_title_parts($title_parts) {
        $seo_data = $this->get_seo_data();
        
        if (!empty($seo_data['meta_title'])) {
            $title_parts['title'] = $seo_data['meta_title'];
            
            // Remove tagline and site name if they're already included in the custom title
            if (strpos($seo_data['meta_title'], get_bloginfo('name')) !== false) {
                unset($title_parts['site']);
            }
            
            // Remove tagline if set
            unset($title_parts['tagline']);
        }
        
        return $title_parts;
    }
    
    /**
     * Output meta description and keywords tags in the head
     */
    public function output_meta_tags() {
        $seo_data = $this->get_seo_data();
        
        if ($this->debug) {
            aysa_debug_log("AYSA SEO: output_meta_tags called, data: " . print_r($seo_data, true));
            
            // Debug info as HTML comments
            echo "<!-- AYSA SEO Debug Information Start -->\n";
            echo "<!-- Current URL: " . esc_html($_SERVER['REQUEST_URI']) . " -->\n";
            echo "<!-- Page Type: ";
            echo "is_front_page: " . (is_front_page() ? 'true' : 'false') . ", ";
            echo "is_home: " . (is_home() ? 'true' : 'false') . ", ";
            echo "is_singular: " . (is_singular() ? 'true' : 'false') . ", ";
            echo "is_category: " . (is_category() ? 'true' : 'false') . ", ";
            echo "is_tax: " . (is_tax() ? 'true' : 'false') . ", ";
            
            if (function_exists('is_product_category')) {
                echo "is_product_category: " . (is_product_category() ? 'true' : 'false') . ", ";
            }
            echo " -->\n";
            
            if (is_tax() || is_category() || is_tag()) {
                $term = get_queried_object();
                if ($term && isset($term->term_id)) {
                    echo "<!-- Term ID: " . esc_html($term->term_id) . ", Taxonomy: " . esc_html($term->taxonomy) . " -->\n";
                    
                    // Check if term meta data exists
                    $meta_title = get_term_meta($term->term_id, '_aysa_seo_title', true);
                    $meta_description = get_term_meta($term->term_id, '_aysa_seo_description', true);
                    $meta_keywords = get_term_meta($term->term_id, '_aysa_seo_keywords', true);
                    $has_meta = !empty($meta_title) || !empty($meta_description) || !empty($meta_keywords);
                    echo "<!-- Term Meta Data Available: " . ($has_meta ? 'Yes' : 'No') . " -->\n";
                    
                    // Try direct DB query
                    global $wpdb;
                    $meta_key = 'aysa_keyword_data';
                    $query = $wpdb->prepare(
                        "SELECT meta_value FROM {$wpdb->termmeta} WHERE term_id = %d AND meta_key = %s LIMIT 1",
                        $term->term_id,
                        $meta_key
                    );
                    $meta_value = $wpdb->get_var($query);
                    echo "<!-- DB Query for term meta returned: " . (!empty($meta_value) ? 'Data Found' : 'No Data') . " -->\n";
                } else {
                    echo "<!-- No term object available -->\n";
                }
            }
            
            echo "<!-- SEO Data Retrieved: " . json_encode($seo_data) . " -->\n";
            echo "<!-- AYSA SEO Debug Information End -->\n";
        }
        
        // Force meta tags to be output even if empty (for debugging)
        if ($this->debug) {
            echo "<!-- AYSA SEO Debug: Meta tags function running -->\n";
        }
        
        // Output meta description if available
        if (!empty($seo_data['meta_description'])) {
            echo '<meta name="description" content="' . esc_attr($seo_data['meta_description']) . '" />' . "\n";
        } elseif ($this->debug) {
            echo "<!-- AYSA SEO Debug: No meta description available -->\n";
        }
        
        // Output meta keywords if available
        if (!empty($seo_data['meta_keywords'])) {
            echo '<meta name="keywords" content="' . esc_attr($seo_data['meta_keywords']) . '" />' . "\n";
        } elseif ($this->debug) {
            echo "<!-- AYSA SEO Debug: No meta keywords available -->\n";
        }
        
        // Output robots meta tag if any values are set
        $robots_directives = array();
        
        // Check if we have any robots meta settings
        if (!empty($seo_data['robots_meta'])) {
            $meta = $seo_data['robots_meta'];
            
            if (!empty($meta['index']) && $meta['index'] === 'index') {
                $robots_directives[] = 'index';
            } elseif (!empty($meta['noindex']) && $meta['noindex']) {
                $robots_directives[] = 'noindex';
            }
            
            if (!empty($meta['nofollow']) && $meta['nofollow']) {
                $robots_directives[] = 'nofollow';
            } else {
                $robots_directives[] = 'follow';
            }
            
            if (!empty($meta['noarchive']) && $meta['noarchive']) {
                $robots_directives[] = 'noarchive';
            }
            
            if (!empty($meta['noimageindex']) && $meta['noimageindex']) {
                $robots_directives[] = 'noimageindex';
            }
            
            if (!empty($meta['nosnippet']) && $meta['nosnippet']) {
                $robots_directives[] = 'nosnippet';
            }
        }
        
        // Output robots meta tag if we have any directives
        if (!empty($robots_directives)) {
            echo '<meta name="robots" content="' . esc_attr(implode(', ', $robots_directives)) . '" />' . "\n";
        }
        
        // Add a marker tag to confirm the function executed
        echo '<meta name="generator" content="AYSA SEO Plugin" />' . "\n";
    }
    
    /**
     * Output debug information in the footer
     */
    public function output_debug_info() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        global $wp_query;
        
        echo '<!-- AYSA SEO Debug Info -->' . "\n";
        echo '<!-- Current page type: ';
        
        // Get information about the current page
        echo "is_front_page: " . (is_front_page() ? 'true' : 'false') . ", ";
        echo "is_home: " . (is_home() ? 'true' : 'false') . ", ";
        echo "is_singular: " . (is_singular() ? 'true' : 'false') . ", ";
        echo "is_category: " . (is_category() ? 'true' : 'false') . ", ";
        echo "is_tag: " . (is_tag() ? 'true' : 'false') . ", ";
        echo "is_tax: " . (is_tax() ? 'true' : 'false') . ", ";
        echo "is_archive: " . (is_archive() ? 'true' : 'false') . ", ";
        
        if (function_exists('is_product_category')) {
            echo "is_product_category: " . (is_product_category() ? 'true' : 'false') . ", ";
        }
        
        if (function_exists('is_product_tag')) {
            echo "is_product_tag: " . (is_product_tag() ? 'true' : 'false') . ", ";
        }
        
        if (function_exists('is_shop')) {
            echo "is_shop: " . (is_shop() ? 'true' : 'false') . ", ";
        }
        
        echo "-->" . "\n";
        
        echo '<!-- Current object: ';
        
        if (is_singular()) {
            $post_id = get_the_ID();
            echo "Post ID: {$post_id}";
            $meta_title = get_post_meta($post_id, '_aysa_seo_title', true);
            $meta_description = get_post_meta($post_id, '_aysa_seo_description', true);
            $meta_keywords = get_post_meta($post_id, '_aysa_seo_keywords', true);
            $seo_data = array('title' => $meta_title, 'description' => $meta_description, 'keywords' => $meta_keywords);
            echo ', SEO data: ' . json_encode($seo_data);
        } elseif (is_tax() || is_category() || is_tag() || 
            (function_exists('is_product_category') && is_product_category()) || 
            (function_exists('is_product_tag') && is_product_tag())) {
            
            $term = get_queried_object();
            if ($term && isset($term->term_id)) {
                echo "Term ID: {$term->term_id}, Taxonomy: {$term->taxonomy}";
                $meta_title = get_term_meta($term->term_id, '_aysa_seo_title', true);
                $meta_description = get_term_meta($term->term_id, '_aysa_seo_description', true);
                $meta_keywords = get_term_meta($term->term_id, '_aysa_seo_keywords', true);
                $seo_data = array('title' => $meta_title, 'description' => $meta_description, 'keywords' => $meta_keywords);
                echo ', SEO data: ' . json_encode($seo_data);
                
                // Check available meta keys for this term
                $meta_keys = get_metadata('term', $term->term_id);
                echo ', Available meta keys: ' . json_encode(array_keys((array)$meta_keys));
            } else {
                echo "Term object not available";
            }
        } else {
            echo "Other page type";
        }
        
        echo ' -->' . "\n";
    }
    
    /**
     * Modify WooCommerce category title
     * 
     * @param string $title The original title
     * @return string The modified title
     */
    public function modify_woocommerce_title($title) {
        $seo_data = $this->get_seo_data();
        
        if (!empty($seo_data['meta_title'])) {
            // Extract only the title part without site name if it contains a separator
            $separators = array(' | ', ' - ', ' – ', ' » ', ' :: ');
            foreach ($separators as $separator) {
                if (strpos($seo_data['meta_title'], $separator) !== false) {
                    $parts = explode($separator, $seo_data['meta_title']);
                    return $parts[0]; // Return just the first part of the title
                }
            }
            return $seo_data['meta_title'];
        }
        
        return $title;
    }
    
    /**
     * Output the title tag directly
     */
    public function output_title_tag() {
        $seo_data = $this->get_seo_data();
        
        if (!empty($seo_data['meta_title'])) {
            // Remove the default WordPress title function
            remove_action('wp_head', '_wp_render_title_tag', 1);
            
            // Output our custom title tag
            echo '<title>' . esc_html($seo_data['meta_title']) . '</title>' . "\n";
            
            if ($this->debug) {
                echo "<!-- AYSA SEO Direct Title Output: {$seo_data['meta_title']} -->\n";
                aysa_debug_log("AYSA SEO: Direct title output: {$seo_data['meta_title']}");
            }
        }
    }
    
    /**
     * Filter the_title for specific posts or pages
     * ✅ FIXED: Prevent meta title from overriding product H1 titles
     * 
     * @param string $title The post title
     * @param int $post_id The post ID
     * @return string The modified title
     */
    public function filter_the_title($title, $post_id) {
        // Only apply to main title in content, not menu items, widgets, etc.
        if (!in_the_loop() || !is_main_query()) {
            return $title;
        }
        
        // ✅ CRITICAL FIX: Don't modify H1 titles for individual products!
        // Meta title should only affect the <title> tag in HTML head, not the product H1
        if (is_singular('product')) {
            if ($this->debug) {
                aysa_debug_log("AYSA SEO: Skipping the_title filter for product page to preserve H1 = product name");
            }
            return $title; // Keep the original product name for H1
        }
        
        // ✅ ALSO: Don't modify H1 titles for individual posts and pages
        // Let meta title only affect the HTML <title> tag
        if (is_singular(array('post', 'page'))) {
            if ($this->debug) {
                aysa_debug_log("AYSA SEO: Skipping the_title filter for post/page to preserve H1 = post/page title");
            }
            return $title; // Keep the original post/page title for H1
        }
        
        $seo_data = $this->get_seo_data();
        
        if (!empty($seo_data['meta_title'])) {
            if ($this->debug) {
                aysa_debug_log("AYSA SEO: Applying custom title '{$seo_data['meta_title']}' via the_title filter for post ID: {$post_id}");
            }
            return $seo_data['meta_title'];
        }
        
        return $title;
    }
    
    /**
     * Modify WooCommerce category title specifically
     * 
     * @param string $title The original title
     * @return string The modified title
     */
    public function modify_woocommerce_category_title($title) {
        if (!is_tax() && !is_category() && !is_tag() && 
            !(function_exists('is_product_category') && is_product_category()) && 
            !(function_exists('is_product_tag') && is_product_tag())) {
            return $title;
        }
        
        $seo_data = $this->get_seo_data();
        
        if (!empty($seo_data['meta_title'])) {
            if ($this->debug) {
                aysa_debug_log("AYSA SEO: Applying custom title '{$seo_data['meta_title']}' via woocommerce_product_taxonomy_title filter");
            }
            
            // Extract only the title part without site name if it contains a separator
            $separators = array(' | ', ' - ', ' – ', ' » ', ' :: ');
            foreach ($separators as $separator) {
                if (strpos($seo_data['meta_title'], $separator) !== false) {
                    $parts = explode($separator, $seo_data['meta_title']);
                    return $parts[0]; // Return just the first part of the title
                }
            }
            return $seo_data['meta_title'];
        }
        
        return $title;
    }
    
    /**
     * Direct implementation of meta tags that doesn't rely on WordPress hooks
     * This can be called directly from a theme's header.php file
     */
    public static function output_meta_tags_direct() {
        $instance = new self();
        $instance->output_meta_tags();
    }
}                                                
