<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Trendly_AI_Post_SEO_Preview {
    public function register_meta_box() : void {
        add_meta_box(
            'trendly_seo_preview',
            __( 'Trendly SEO Preview', 'trendly-ai-post' ),
            [ $this, 'render_meta_box' ],
            'post',
            'side',
            'default'
        );
    }

    public function render_meta_box( $post ) : void {
        wp_nonce_field( 'trendly_seo_preview_nonce', 'trendly_seo_preview_nonce' );
        $meta_desc = get_post_meta( $post->ID, '_trendly_meta_description', true );
        echo '<p><strong>' . esc_html__( 'Meta Description', 'trendly-ai-post' ) . '</strong></p>';
        echo '<textarea name="trendly_meta_description" style="width:100%" rows="4">' . esc_textarea( $meta_desc ) . '</textarea>';
        echo '<p style="font-size:12px;color:#666">' . esc_html__( 'Shows how your post may appear in search results.', 'trendly-ai-post' ) . '</p>';
    }

    public function save_meta( int $post_id, WP_Post $post ) : void {
        if ( ! isset( $_POST['trendly_seo_preview_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['trendly_seo_preview_nonce'] ) ), 'trendly_seo_preview_nonce' ) ) {
            return;
        }
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
        if ( ! current_user_can( 'edit_post', $post_id ) ) return;

        if ( isset( $_POST['trendly_meta_description'] ) ) {
            update_post_meta( $post_id, '_trendly_meta_description', sanitize_text_field( wp_unslash( $_POST['trendly_meta_description'] ) ) );
        }
    }
}
