<?php
/**
 * Content Labeler
 *
 * Adds AI content labels to posts and pages.
 */

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

class Tiriri_Content_Labeler {

    /**
     * AI content status options
     */
    const STATUS_NONE           = 'none';
    const STATUS_AI_ASSISTED    = 'ai_assisted';
    const STATUS_AI_GENERATED   = 'ai_generated';
    const STATUS_HUMAN_REVIEWED = 'human_reviewed';

    /**
     * Initialize content labeler hooks
     */
    public function init() {
        // Content labeling is a Pro feature
        if ( ! tiriri_is_pro() ) {
            return;
        }

        // Add meta box to post editor
        add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );

        // Enqueue meta box script on post edit screens
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_meta_box_assets' ) );

        // Save meta box data
        add_action( 'save_post', array( $this, 'save_meta_box' ), 10, 2 );

        // Display label on frontend
        add_filter( 'the_content', array( $this, 'maybe_display_label' ) );

        // Add machine-readable metadata to head
        add_action( 'wp_head', array( $this, 'add_meta_tags' ) );

        // Add column to posts list in admin
        add_filter( 'manage_posts_columns', array( $this, 'add_admin_column' ) );
        add_action( 'manage_posts_custom_column', array( $this, 'render_admin_column' ), 10, 2 );

        // Quick edit support
        add_action( 'quick_edit_custom_box', array( $this, 'quick_edit_box' ), 10, 2 );
    }

    /**
     * Enqueue JS for the content status meta box on post edit screens
     */
    public function enqueue_meta_box_assets( $hook ) {
        if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
            return;
        }

        wp_enqueue_script(
            'tiriri-meta-box',
            TIRIRI_PLUGIN_URL . 'admin/assets/meta-box.js',
            array( 'jquery' ),
            TIRIRI_VERSION,
            true
        );

        wp_localize_script( 'tiriri-meta-box', 'tiririMetaBox', array(
            'humanReviewedStatus' => self::STATUS_HUMAN_REVIEWED,
        ) );
    }

    /**
     * Add meta box to post/page editor
     */
    public function add_meta_box() {
        $post_types = get_post_types( array( 'public' => true ), 'names' );

        foreach ( $post_types as $post_type ) {
            add_meta_box(
                'tiriri_content_status',
                __( 'AI Content Status', 'tiriri-transparency-for-eu-ai-act' ) . ' <span class="tiriri-badge">EU AI Act</span>',
                array( $this, 'render_meta_box' ),
                $post_type,
                'side',
                'high'
            );
        }
    }

    /**
     * Render the meta box
     */
    public function render_meta_box( $post ) {
        wp_nonce_field( 'tiriri_content_status', 'tiriri_nonce' );

        $status   = get_post_meta( $post->ID, '_tiriri_content_status', true ) ?: self::STATUS_NONE;
        $reviewer = get_post_meta( $post->ID, '_tiriri_reviewer', true );
        $review_date = get_post_meta( $post->ID, '_tiriri_review_date', true );

        ?>
        <div class="tiriri-meta-box">
            <p class="description" style="margin-bottom: 10px;">
                <?php esc_html_e( 'EU AI Act Article 50 requires disclosure of AI-generated content.', 'tiriri-transparency-for-eu-ai-act' ); ?>
            </p>

            <label for="tiriri_status">
                <strong><?php esc_html_e( 'Content AI Status:', 'tiriri-transparency-for-eu-ai-act' ); ?></strong>
            </label>
            <select id="tiriri_status" name="tiriri_content_status" style="width: 100%; margin-top: 5px;">
                <option value="<?php echo esc_attr( self::STATUS_NONE ); ?>" <?php selected( $status, self::STATUS_NONE ); ?>>
                    <?php esc_html_e( 'No AI used', 'tiriri-transparency-for-eu-ai-act' ); ?>
                </option>
                <option value="<?php echo esc_attr( self::STATUS_AI_ASSISTED ); ?>" <?php selected( $status, self::STATUS_AI_ASSISTED ); ?>>
                    <?php esc_html_e( 'AI-assisted content', 'tiriri-transparency-for-eu-ai-act' ); ?>
                </option>
                <option value="<?php echo esc_attr( self::STATUS_AI_GENERATED ); ?>" <?php selected( $status, self::STATUS_AI_GENERATED ); ?>>
                    <?php esc_html_e( 'AI-generated content', 'tiriri-transparency-for-eu-ai-act' ); ?>
                </option>
                <option value="<?php echo esc_attr( self::STATUS_HUMAN_REVIEWED ); ?>" <?php selected( $status, self::STATUS_HUMAN_REVIEWED ); ?>>
                    <?php esc_html_e( 'AI-generated, human reviewed', 'tiriri-transparency-for-eu-ai-act' ); ?>
                </option>
            </select>

            <div id="tiriri-review-fields" style="margin-top: 10px; <?php echo ( self::STATUS_HUMAN_REVIEWED !== $status ) ? 'display:none;' : ''; ?>">
                <label for="tiriri_reviewer">
                    <?php esc_html_e( 'Reviewed by:', 'tiriri-transparency-for-eu-ai-act' ); ?>
                </label>
                <input type="text"
                       id="tiriri_reviewer"
                       name="tiriri_reviewer"
                       value="<?php echo esc_attr( $reviewer ); ?>"
                       style="width: 100%;"
                       placeholder="<?php esc_attr_e( 'Reviewer name', 'tiriri-transparency-for-eu-ai-act' ); ?>" />

                <label for="tiriri_review_date" style="margin-top: 5px; display: block;">
                    <?php esc_html_e( 'Review date:', 'tiriri-transparency-for-eu-ai-act' ); ?>
                </label>
                <input type="date"
                       id="tiriri_review_date"
                       name="tiriri_review_date"
                       value="<?php echo esc_attr( $review_date ); ?>"
                       style="width: 100%;" />

                <p class="description" style="margin-top: 8px;">
                    <?php esc_html_e( 'Under Article 50(4), AI-generated text that has undergone human editorial review with assigned editorial responsibility is exempt from the labeling requirement.', 'tiriri-transparency-for-eu-ai-act' ); ?>
                </p>
            </div>
        </div>
        <?php
    }

    /**
     * Save meta box data
     */
    public function save_meta_box( $post_id, $post ) {
        if ( ! isset( $_POST['tiriri_nonce'] ) ) {
            return;
        }

        $nonce = sanitize_text_field( wp_unslash( $_POST['tiriri_nonce'] ) );
        if ( ! wp_verify_nonce( $nonce, 'tiriri_content_status' ) ) {
            return;
        }

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        if ( isset( $_POST['tiriri_content_status'] ) ) {
            $status         = sanitize_text_field( wp_unslash( $_POST['tiriri_content_status'] ) );
            $valid_statuses = array( self::STATUS_NONE, self::STATUS_AI_ASSISTED, self::STATUS_AI_GENERATED, self::STATUS_HUMAN_REVIEWED );

            if ( in_array( $status, $valid_statuses, true ) ) {
                update_post_meta( $post_id, '_tiriri_content_status', $status );
            }
        }

        if ( isset( $_POST['tiriri_reviewer'] ) ) {
            update_post_meta( $post_id, '_tiriri_reviewer', sanitize_text_field( wp_unslash( $_POST['tiriri_reviewer'] ) ) );
        }
        if ( isset( $_POST['tiriri_review_date'] ) ) {
            update_post_meta( $post_id, '_tiriri_review_date', sanitize_text_field( wp_unslash( $_POST['tiriri_review_date'] ) ) );
        }
    }

    /**
     * Display AI content label on frontend
     */
    public function maybe_display_label( $content ) {
        if ( ! is_singular() || ! in_the_loop() || ! is_main_query() ) {
            return $content;
        }

        $settings = get_option( 'tiriri_settings', array() );
        if ( empty( $settings['content_labeling_enabled'] ) ) {
            return $content;
        }

        $status = get_post_meta( get_the_ID(), '_tiriri_content_status', true );

        if ( empty( $status ) || self::STATUS_NONE === $status ) {
            return $content;
        }

        // Human-reviewed content is exempt from labeling requirement
        if ( self::STATUS_HUMAN_REVIEWED === $status ) {
            return $content;
        }

        $label = $this->get_label_html( $status );

        return $label . $content;
    }

    /**
     * Get the HTML for a content label
     */
    private function get_label_html( $status ) {
        $labels = array(
            self::STATUS_AI_ASSISTED  => __( 'This content was created with AI assistance.', 'tiriri-transparency-for-eu-ai-act' ),
            self::STATUS_AI_GENERATED => __( 'This content was generated by artificial intelligence.', 'tiriri-transparency-for-eu-ai-act' ),
        );

        $text = isset( $labels[ $status ] ) ? $labels[ $status ] : '';

        if ( empty( $text ) ) {
            return '';
        }

        return sprintf(
            '<div class="tiriri-content-label" role="note" aria-label="%s">
                <span class="tiriri-content-label__icon" aria-hidden="true">AI</span>
                <span class="tiriri-content-label__text">%s</span>
            </div>',
            esc_attr__( 'AI Content Disclosure', 'tiriri-transparency-for-eu-ai-act' ),
            esc_html( $text )
        );
    }

    /**
     * Add machine-readable meta tags to page head
     */
    public function add_meta_tags() {
        if ( ! is_singular() ) {
            return;
        }

        $status = get_post_meta( get_the_ID(), '_tiriri_content_status', true );

        if ( empty( $status ) || self::STATUS_NONE === $status ) {
            return;
        }

        $meta_values = array(
            self::STATUS_AI_ASSISTED  => 'ai-assisted',
            self::STATUS_AI_GENERATED => 'ai-generated',
            self::STATUS_HUMAN_REVIEWED => 'ai-generated-human-reviewed',
        );

        if ( isset( $meta_values[ $status ] ) ) {
            printf(
                '<meta name="ai-content-declaration" content="%s" />' . "\n",
                esc_attr( $meta_values[ $status ] )
            );

            // Schema.org markup
            $reviewer = get_post_meta( get_the_ID(), '_tiriri_reviewer', true );
            $review_date = get_post_meta( get_the_ID(), '_tiriri_review_date', true );

            $schema = array(
                '@context' => 'https://schema.org',
                '@type'    => 'WebPage',
                'about'    => array(
                    '@type'       => 'CreativeWork',
                    'description' => 'AI content status: ' . $meta_values[ $status ],
                ),
            );

            if ( self::STATUS_HUMAN_REVIEWED === $status && $reviewer ) {
                $schema['about']['editor'] = array(
                    '@type' => 'Person',
                    'name'  => $reviewer,
                );
                if ( $review_date ) {
                    $schema['about']['dateModified'] = $review_date;
                }
            }

            printf(
                '<script type="application/ld+json">%s</script>' . "\n",
                wp_json_encode( $schema, JSON_UNESCAPED_SLASHES )
            );
        }
    }

    /**
     * Add AI status column to admin posts list
     */
    public function add_admin_column( $columns ) {
        $columns['tiriri_status'] = __( 'AI Status', 'tiriri-transparency-for-eu-ai-act' );
        return $columns;
    }

    /**
     * Render AI status column content
     */
    public function render_admin_column( $column, $post_id ) {
        if ( 'tiriri_status' !== $column ) {
            return;
        }

        $status = get_post_meta( $post_id, '_tiriri_content_status', true );

        $status_labels = array(
            self::STATUS_NONE           => '<span style="color:#999;">&mdash;</span>',
            self::STATUS_AI_ASSISTED    => '<span style="color:#e67e22;">' . esc_html__( 'AI Assisted', 'tiriri-transparency-for-eu-ai-act' ) . '</span>',
            self::STATUS_AI_GENERATED   => '<span style="color:#e74c3c;">' . esc_html__( 'AI Generated', 'tiriri-transparency-for-eu-ai-act' ) . '</span>',
            self::STATUS_HUMAN_REVIEWED => '<span style="color:#27ae60;">' . esc_html__( 'Reviewed', 'tiriri-transparency-for-eu-ai-act' ) . '</span>',
        );

        $output = isset( $status_labels[ $status ] ) ? $status_labels[ $status ] : $status_labels[ self::STATUS_NONE ];
        echo wp_kses( $output, array( 'span' => array( 'style' => array() ) ) );
    }

    /**
     * Quick edit box for AI status
     */
    public function quick_edit_box( $column_name, $post_type ) {
        if ( 'tiriri_status' !== $column_name ) {
            return;
        }
        ?>
        <fieldset class="inline-edit-col-right">
            <div class="inline-edit-col">
                <label>
                    <span class="title"><?php esc_html_e( 'AI Status', 'tiriri-transparency-for-eu-ai-act' ); ?></span>
                    <select name="tiriri_content_status">
                        <option value="<?php echo esc_attr( self::STATUS_NONE ); ?>"><?php esc_html_e( 'No AI', 'tiriri-transparency-for-eu-ai-act' ); ?></option>
                        <option value="<?php echo esc_attr( self::STATUS_AI_ASSISTED ); ?>"><?php esc_html_e( 'AI Assisted', 'tiriri-transparency-for-eu-ai-act' ); ?></option>
                        <option value="<?php echo esc_attr( self::STATUS_AI_GENERATED ); ?>"><?php esc_html_e( 'AI Generated', 'tiriri-transparency-for-eu-ai-act' ); ?></option>
                        <option value="<?php echo esc_attr( self::STATUS_HUMAN_REVIEWED ); ?>"><?php esc_html_e( 'Human Reviewed', 'tiriri-transparency-for-eu-ai-act' ); ?></option>
                    </select>
                </label>
            </div>
        </fieldset>
        <?php
    }
}
