<?php
/**
 * MCP Tool: Post Meta Operations
 *
 * Provides tools for managing WordPress post meta fields,
 * specifically SEO-related metadata.
 *
 * @package    MetaSync
 * @subpackage MCP_Server/Tools
 */

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

/**
 * Update Post Meta Tool
 */
class MCP_Tool_Update_Post_Meta extends MCP_Tool_Base {

    public function get_name() {
        return 'wordpress_update_post_meta';
    }

    public function get_description() {
        return 'Update a WordPress post meta field (SEO data like title, description, keywords, robots settings, Open Graph/social meta)';
    }

    public function get_input_schema() {
        return [
            'type' => 'object',
            'properties' => [
                'post_id' => [
                    'type' => 'integer',
                    'description' => 'WordPress post or page ID',
                    'minimum' => 1
                ],
                'meta_key' => [
                    'type' => 'string',
                    'description' => 'Meta field to update',
                    'enum' => [
                        '_metasync_metatitle',
                        '_metasync_metadesc',
                        '_metasync_focus_keyword',
                        '_metasync_robots_index',
                        '_metasync_canonical_url',
                        '_metasync_og_enabled',
                        '_metasync_og_title',
                        '_metasync_og_description',
                        '_metasync_og_image',
                        '_metasync_og_url',
                        '_metasync_og_type',
                        '_metasync_twitter_title',
                        '_metasync_twitter_description'
                    ]
                ],
                'meta_value' => [
                    'type' => 'string',
                    'description' => 'Value to set for the meta field'
                ]
            ],
            'required' => ['post_id', 'meta_key', 'meta_value']
        ];
    }

    public function execute($params) {
        // Validate and sanitize
        $this->validate_params($params);
        $this->require_capability('edit_posts');

        $post_id = $this->sanitize_integer($params['post_id']);
        $meta_key = $this->sanitize_string($params['meta_key']);
        $meta_value = $this->sanitize_textarea($params['meta_value']);

        // SECURITY: Additional sanitization for URL fields (prevent javascript: protocol)
        if (in_array($meta_key, ['_metasync_og_image', '_metasync_og_url', '_metasync_canonical_url'])) {
            $meta_value = esc_url_raw($meta_value);
        }

        // Verify post exists
        $post = $this->verify_post_exists($post_id);

        // SECURITY: Check user has permission to edit this specific post
        $this->check_post_permission($post_id);

        // Update meta
        $current_value = get_post_meta($post_id, $meta_key, true);
        if ($current_value === $meta_value) {
            // Value already matches — return success without update
            return $this->success([
                'post_id'    => $post_id,
                'meta_key'   => $meta_key,
                'meta_value' => $current_value,
                'updated'    => false,
                'post_title' => $post->post_title,
                'post_type'  => $post->post_type
            ], 'Meta value already matches, no update needed');
        }
        $updated = update_post_meta($post_id, $meta_key, $meta_value);

        if ($updated === false) {
            throw new Exception("Failed to update meta key '{$meta_key}'");
        }

        $stored_value = get_post_meta($post_id, $meta_key, true);
        return $this->success([
            'post_id'    => $post_id,
            'meta_key'   => $meta_key,
            'meta_value' => $stored_value,
            'updated'    => true,
            'post_title' => $post->post_title,
            'post_type'  => $post->post_type
        ], "Meta field '{$meta_key}' updated successfully");
    }
}

/**
 * Get Post Meta Tool
 */
class MCP_Tool_Get_Post_Meta extends MCP_Tool_Base {

    public function get_name() {
        return 'wordpress_get_post_meta';
    }

    public function get_description() {
        return 'Get WordPress post meta field value(s)';
    }

    public function get_input_schema() {
        return [
            'type' => 'object',
            'properties' => [
                'post_id' => [
                    'type' => 'integer',
                    'description' => 'WordPress post or page ID',
                    'minimum' => 1
                ],
                'meta_key' => [
                    'type' => 'string',
                    'description' => 'Specific meta key to retrieve (optional - omit to get all SEO meta)',
                ]
            ],
            'required' => ['post_id']
        ];
    }

    public function execute($params) {
        $this->validate_params($params);
        $this->require_capability('read');

        $post_id = $this->sanitize_integer($params['post_id']);

        // Verify post exists
        $post = $this->verify_post_exists($post_id);

        // SECURITY: Check user has permission to read this specific post
        $this->check_post_permission($post_id);

        // Get meta
        if (isset($params['meta_key'])) {
            $meta_key = $this->sanitize_string($params['meta_key']);
            $meta_value = get_post_meta($post_id, $meta_key, true);

            return $this->success([
                'post_id' => $post_id,
                'post_title' => $post->post_title,
                'meta_key' => $meta_key,
                'meta_value' => $meta_value
            ]);
        } else {
            // Get all SEO meta
            $seo_meta = [
                'metatitle' => get_post_meta($post_id, '_metasync_metatitle', true),
                'metadesc' => get_post_meta($post_id, '_metasync_metadesc', true),
                'focus_keyword' => get_post_meta($post_id, '_metasync_focus_keyword', true),
                'robots_index' => get_post_meta($post_id, '_metasync_robots_index', true),
                'canonical_url' => get_post_meta($post_id, '_metasync_canonical_url', true)
            ];

            // Get Open Graph meta
            $opengraph_meta = [
                'og_enabled' => get_post_meta($post_id, '_metasync_og_enabled', true),
                'og_title' => get_post_meta($post_id, '_metasync_og_title', true),
                'og_description' => get_post_meta($post_id, '_metasync_og_description', true),
                'og_image' => get_post_meta($post_id, '_metasync_og_image', true),
                'og_url' => get_post_meta($post_id, '_metasync_og_url', true),
                'og_type' => get_post_meta($post_id, '_metasync_og_type', true)
            ];

            return $this->success([
                'post_id' => $post_id,
                'post_title' => $post->post_title,
                'post_type' => $post->post_type,
                'post_status' => $post->post_status,
                'seo_meta' => $seo_meta,
                'opengraph_meta' => $opengraph_meta
            ]);
        }
    }
}

/**
 * Get SEO Meta Tool
 */
class MCP_Tool_Get_SEO_Meta extends MCP_Tool_Base {

    public function get_name() {
        return 'wordpress_get_seo_meta';
    }

    public function get_description() {
        return 'Get all SEO-related metadata for a post including title, description, keywords, indexing settings, and Open Graph/social meta';
    }

    public function get_input_schema() {
        return [
            'type' => 'object',
            'properties' => [
                'post_id' => [
                    'type' => 'integer',
                    'description' => 'WordPress post or page ID',
                    'minimum' => 1
                ]
            ],
            'required' => ['post_id']
        ];
    }

    public function execute($params) {
        $this->validate_params($params);
        $this->require_capability('read');

        $post_id = $this->sanitize_integer($params['post_id']);

        // Verify post exists
        $post = $this->verify_post_exists($post_id);

        // Get all SEO meta
        $seo_data = [
            'post_info' => [
                'id' => $post_id,
                'title' => $post->post_title,
                'type' => $post->post_type,
                'status' => $post->post_status,
                'url' => get_permalink($post_id)
            ],
            'seo_meta' => [
                'meta_title' => get_post_meta($post_id, '_metasync_metatitle', true),
                'meta_description' => get_post_meta($post_id, '_metasync_metadesc', true),
                'focus_keyword' => get_post_meta($post_id, '_metasync_focus_keyword', true),
                'robots_index' => get_post_meta($post_id, '_metasync_robots_index', true),
                'canonical_url' => get_post_meta($post_id, '_metasync_canonical_url', true)
            ],
            'opengraph_meta' => [
                'enabled' => get_post_meta($post_id, '_metasync_og_enabled', true),
                'title' => get_post_meta($post_id, '_metasync_og_title', true),
                'description' => get_post_meta($post_id, '_metasync_og_description', true),
                'image' => get_post_meta($post_id, '_metasync_og_image', true),
                'url' => get_post_meta($post_id, '_metasync_og_url', true),
                'type' => get_post_meta($post_id, '_metasync_og_type', true)
            ],
            'analysis' => [
                'meta_title_length' => mb_strlen(get_post_meta($post_id, '_metasync_metatitle', true)),
                'meta_desc_length' => mb_strlen(get_post_meta($post_id, '_metasync_metadesc', true)),
                'has_focus_keyword' => !empty(get_post_meta($post_id, '_metasync_focus_keyword', true)),
                'is_indexable' => get_post_meta($post_id, '_metasync_robots_index', true) !== 'noindex',
                'og_enabled' => get_post_meta($post_id, '_metasync_og_enabled', true) === '1',
                'has_og_image' => !empty(get_post_meta($post_id, '_metasync_og_image', true))
            ]
        ];

        return $this->success($seo_data);
    }
}
