<?php

/**
 * Meta Module
 *
 * Manages SEO meta tags and social media meta tags.
 *
 * @package ProRank\SEO\Modules\Meta
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Modules\Meta;

use ProRank\SEO\Modules\BaseModule;
use ProRank\SEO\Core\RestApi\MetaController;
use ProRank\SEO\Frontend\HeadOutput;

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


/**
 * MetaModule class
 * 
 * Provides comprehensive meta tag management including:
 * - SEO title and description
 * - Canonical URLs
 * - Meta robots directives
 * - Open Graph tags
 * - Twitter Card tags
 */


class MetaModule extends BaseModule {

    /**
     * Required tier for this module
     */
    protected string $feature_tier = 'free';
    
    /**
     * MetaController instance
     *
     * @var MetaController
     */
    private MetaController $meta_controller;
    
    /**
     * HeadOutput instance
     *
     * @var HeadOutput|null
     */
    private ?HeadOutput $head_output = null;
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->slug = 'meta-tags';
        $this->name = 'Meta Tags';
        $this->description = 'Manage SEO meta tags and social media meta tags';
$this->parent_slug = 'on-page-seo';
        
        $this->meta_controller = new MetaController();
    }
    
    /**
     * {@inheritDoc}
     */
    public function init_hooks(): void {
        // Register REST API routes
        add_action('rest_api_init', [$this->meta_controller, 'register_routes']);
        
        // Add meta box save functionality
        add_action('save_post', [$this, 'save_meta_box_data'], 10, 2);
        
        // Add default meta tags filter
        add_filter('prorank_seo_default_meta_tags', [$this, 'get_default_meta_tags'], 10, 2);
        
        // Add social meta tags filter
        add_filter('prorank_seo_social_meta_tags', [$this, 'get_social_meta_tags'], 10, 2);
        
        // HeadOutput is now initialized directly in the Plugin class
        // to ensure it's always loaded for frontend requests
        
        // Log successful initialization
        try {
            $plugin = $this->plugin();
            if ($plugin->is_initialized()) {
                $notification_manager = $plugin->notifications();
                $notification_manager->add_internal_log(
                    '[Meta Module] Initialized successfully',
                    ['module_slug' => $this->slug]
                );
            }
        } catch (\Exception $e) {
            // Fail silently if notification manager not available
        }
    }
    
    
    /**
     * Save meta box data
     *
     * @param int      $post_id Post ID.
     * @param \WP_Post $post    Post object.
     * @return void
     */
    public function save_meta_box_data(int $post_id, \WP_Post $post): void {
        if ( \ProRank\SEO\Plugin::is_elementor_builder_save_request() ) {
            return;
        }

        // Skip autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // Verify nonce
        $nonce = filter_input(INPUT_POST, 'prorank_seo_meta_nonce', FILTER_DEFAULT);
        $nonce = is_string($nonce) ? sanitize_text_field($nonce) : '';
        if (!$nonce || !wp_verify_nonce($nonce, 'prorank_seo_save_meta')) {
            return;
        }
        
        // Check permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // Save SEO meta fields
        $this->save_meta_field($post_id, 'prorank_seo_title', 'sanitize_text_field');
        $this->save_meta_field($post_id, 'prorank_seo_description', 'sanitize_textarea_field');
        $this->save_meta_field($post_id, 'prorank_seo_canonical_url', 'esc_url_raw');
        
        // Save meta robots
        $meta_robots = filter_input(INPUT_POST, 'prorank_meta_robots', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        if ($meta_robots && is_array($meta_robots)) {
            $robots = array_map('sanitize_key', $meta_robots);
            update_post_meta($post_id, '_prorank_meta_robots', $robots);
        } else {
            delete_post_meta($post_id, '_prorank_meta_robots');
        }
        
        // Save social meta fields
        $this->save_meta_field($post_id, 'prorank_og_title', 'sanitize_text_field');
        $this->save_meta_field($post_id, 'prorank_og_description', 'sanitize_textarea_field');
        $this->save_meta_field($post_id, 'prorank_og_image_id', 'absint');
        $this->save_meta_field($post_id, 'prorank_twitter_title', 'sanitize_text_field');
        $this->save_meta_field($post_id, 'prorank_twitter_description', 'sanitize_textarea_field');
        $this->save_meta_field($post_id, 'prorank_twitter_image_id', 'absint');
        $this->save_meta_field($post_id, 'prorank_twitter_card_type', 'sanitize_key');
    }
    
    /**
     * Save individual meta field
     *
     * @param int      $post_id         Post ID.
     * @param string   $field_name      Field name (without underscore prefix).
     * @param callable $sanitize_callback Sanitization callback.
     * @return void
     */
    private function save_meta_field(int $post_id, string $field_name, callable $sanitize_callback): void {
        $value = filter_input(INPUT_POST, $field_name, FILTER_UNSAFE_RAW);
        if ($value !== null) {
            $value = $sanitize_callback($value);
            if (!empty($value)) {
                update_post_meta($post_id, '_' . $field_name, $value);
            } else {
                delete_post_meta($post_id, '_' . $field_name);
            }
        }
    }
    
    /**
     * Get default meta tags for a post
     *
     * @param array $meta_tags Existing meta tags.
     * @param int   $post_id   Post ID.
     * @return array
     */
    public function get_default_meta_tags(array $meta_tags, int $post_id): array {
        // SEO Title
        $seo_title = get_post_meta($post_id, '_prorank_seo_title', true);
        if (!empty($seo_title)) {
            $meta_tags['title'] = $seo_title;
        }
        
        // Meta Description
        $seo_description = get_post_meta($post_id, '_prorank_seo_description', true);
        if (!empty($seo_description)) {
            $meta_tags['description'] = $seo_description;
        }
        
        // Canonical URL
        $canonical_url = get_post_meta($post_id, '_prorank_seo_canonical_url', true);
        if (!empty($canonical_url)) {
            $meta_tags['canonical'] = $canonical_url;
        }
        
        // Meta Robots
        $meta_robots = get_post_meta($post_id, '_prorank_meta_robots', true);
        if (!empty($meta_robots) && is_array($meta_robots)) {
            $meta_tags['robots'] = implode(', ', $meta_robots);
        }
        
        return $meta_tags;
    }
    
    /**
     * Get social meta tags for a post
     *
     * @param array $social_tags Existing social tags.
     * @param int   $post_id     Post ID.
     * @return array
     */
    public function get_social_meta_tags(array $social_tags, int $post_id): array {
        $post = get_post($post_id);
        if (!$post) {
            return $social_tags;
        }
        
        // Open Graph tags
        $og_title = get_post_meta($post_id, '_prorank_og_title', true);
        if (!empty($og_title)) {
            $social_tags['og:title'] = $og_title;
        } elseif (!isset($social_tags['og:title'])) {
            // Fallback to SEO title or post title
            $seo_title = get_post_meta($post_id, '_prorank_seo_title', true);
            $social_tags['og:title'] = !empty($seo_title) ? $seo_title : $post->post_title;
        }
        
        $og_description = get_post_meta($post_id, '_prorank_og_description', true);
        if (!empty($og_description)) {
            $social_tags['og:description'] = $og_description;
        } elseif (!isset($social_tags['og:description'])) {
            // Fallback to SEO description or excerpt
            $seo_description = get_post_meta($post_id, '_prorank_seo_description', true);
            if (!empty($seo_description)) {
                $social_tags['og:description'] = $seo_description;
            } elseif (!empty($post->post_excerpt)) {
                $social_tags['og:description'] = $post->post_excerpt;
            } else {
                $social_tags['og:description'] = wp_trim_words($post->post_content, 30, '...');
            }
        }
        
        $og_image_id = get_post_meta($post_id, '_prorank_og_image_id', true);
        if (!empty($og_image_id)) {
            $image_url = wp_get_attachment_url((int) $og_image_id);
            if ($image_url) {
                $social_tags['og:image'] = $image_url;
            }
        } elseif (!isset($social_tags['og:image'])) {
            // Fallback to featured image
            $featured_image_id = get_post_thumbnail_id($post_id);
            if ($featured_image_id) {
                $image_url = wp_get_attachment_url($featured_image_id);
                if ($image_url) {
                    $social_tags['og:image'] = $image_url;
                }
            }
        }
        
        // Twitter Card tags
        $twitter_card_type = get_post_meta($post_id, '_prorank_twitter_card_type', true);
        $social_tags['twitter:card'] = !empty($twitter_card_type) ? $twitter_card_type : 'summary';
        
        $twitter_title = get_post_meta($post_id, '_prorank_twitter_title', true);
        if (!empty($twitter_title)) {
            $social_tags['twitter:title'] = $twitter_title;
        } elseif (!isset($social_tags['twitter:title'])) {
            // Fallback to OG title
            $social_tags['twitter:title'] = $social_tags['og:title'] ?? $post->post_title;
        }
        
        $twitter_description = get_post_meta($post_id, '_prorank_twitter_description', true);
        if (!empty($twitter_description)) {
            $social_tags['twitter:description'] = $twitter_description;
        } elseif (!isset($social_tags['twitter:description'])) {
            // Fallback to OG description
            $social_tags['twitter:description'] = $social_tags['og:description'] ?? '';
        }
        
        $twitter_image_id = get_post_meta($post_id, '_prorank_twitter_image_id', true);
        if (!empty($twitter_image_id)) {
            $image_url = wp_get_attachment_url((int) $twitter_image_id);
            if ($image_url) {
                $social_tags['twitter:image'] = $image_url;
            }
        } elseif (!isset($social_tags['twitter:image']) && isset($social_tags['og:image'])) {
            // Fallback to OG image
            $social_tags['twitter:image'] = $social_tags['og:image'];
        }
        
        // Default OG type and URL
        if (!isset($social_tags['og:type'])) {
            $social_tags['og:type'] = 'article';
        }
        if (!isset($social_tags['og:url'])) {
            $social_tags['og:url'] = get_permalink($post_id);
        }
        
        return $social_tags;
    }
    
    /**
     * Get meta data for a post
     *
     * @param int $post_id Post ID.
     * @return array
     */
    public function get_post_meta_data(int $post_id): array {
        return [
            'seo_title' => get_post_meta($post_id, '_prorank_seo_title', true) ?: '',
            'seo_description' => get_post_meta($post_id, '_prorank_seo_description', true) ?: '',
            'canonical_url' => get_post_meta($post_id, '_prorank_seo_canonical_url', true) ?: '',
            'meta_robots' => get_post_meta($post_id, '_prorank_meta_robots', true) ?: [],
            'og_title' => get_post_meta($post_id, '_prorank_og_title', true) ?: '',
            'og_description' => get_post_meta($post_id, '_prorank_og_description', true) ?: '',
            'og_image_id' => (int) get_post_meta($post_id, '_prorank_og_image_id', true),
            'twitter_title' => get_post_meta($post_id, '_prorank_twitter_title', true) ?: '',
            'twitter_description' => get_post_meta($post_id, '_prorank_twitter_description', true) ?: '',
            'twitter_image_id' => (int) get_post_meta($post_id, '_prorank_twitter_image_id', true),
            'twitter_card_type' => get_post_meta($post_id, '_prorank_twitter_card_type', true) ?: 'summary',
        ];
    }
}
