<?php
/**
 * Per-post SEO meta box: focus keyword, SEO title, description, OG image,
 * noindex/nofollow, and live analyzer score.
 *
 * @package Brainwerk SEO Suite
 */

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

class Seoforge_Post_Meta_Box {

    const NONCE = 'seoforge_post_meta';

    public static function register( Seoforge_Loader $loader ) {
        $loader->add_action( 'add_meta_boxes', __CLASS__, 'register_box' );
        $loader->add_action( 'save_post',      __CLASS__, 'save', 10, 2 );
    }

    public static function register_box() {
        $types = get_post_types( array( 'public' => true ) );
        foreach ( $types as $t ) {
            add_meta_box(
                'seoforge_meta',
                __( 'Brainwerk SEO Suite', 'brainwerk-seo-suite' ),
                array( __CLASS__, 'render' ),
                $t,
                'normal',
                'default'
            );
        }
    }

    public static function render( $post ) {
        $row    = Seoforge_Meta::get_post_meta( $post->ID );
        $score  = isset( $row['score'] ) ? (int) $row['score'] : 0;
        $checks = ! empty( $row['score_payload'] ) ? json_decode( $row['score_payload'], true ) : array();
        $ai_on  = class_exists( 'Seoforge_AI' ) && Seoforge_AI::is_configured();
        wp_nonce_field( self::NONCE, 'seoforge_post_meta_nonce' );
        ?>
        <div class="seoforge-meta-box">
            <div class="seoforge-score seoforge-score-<?php echo esc_attr( self::score_class( $score ) ); ?>">
                <strong><?php echo esc_html( $score ); ?></strong>/100
                <span><?php esc_html_e( 'SEO score', 'brainwerk-seo-suite' ); ?></span>
                <button type="button" class="button" id="seoforge-reanalyze" data-post="<?php echo (int) $post->ID; ?>">
                    <?php esc_html_e( 'Re-analyze', 'brainwerk-seo-suite' ); ?>
                </button>
            </div>

            <p>
                <label for="sf-focus"><?php esc_html_e( 'Focus keyword', 'brainwerk-seo-suite' ); ?></label>
                <?php if ( $ai_on ) : ?>
                    <button type="button" class="button button-small sf-ai-suggest" data-kind="focus" data-post="<?php echo (int) $post->ID; ?>" data-target="#sf-focus" style="float:right">✨ <?php esc_html_e( 'Suggest with AI', 'brainwerk-seo-suite' ); ?></button>
                <?php endif; ?>
                <br>
                <input type="text" id="sf-focus" name="seoforge_meta[focus_keyword]" class="widefat"
                       value="<?php echo esc_attr( $row['focus_keyword'] ?? '' ); ?>"
                       placeholder="<?php esc_attr_e( 'e.g. lauschlabor app', 'brainwerk-seo-suite' ); ?>">
            </p>
            <p>
                <label for="sf-title"><?php esc_html_e( 'SEO title', 'brainwerk-seo-suite' ); ?></label>
                <?php if ( $ai_on ) : ?>
                    <button type="button" class="button button-small sf-ai-suggest" data-kind="titles" data-post="<?php echo (int) $post->ID; ?>" data-target="#sf-title" style="float:right">✨ <?php esc_html_e( 'Suggest with AI', 'brainwerk-seo-suite' ); ?></button>
                <?php endif; ?>
                <br>
                <input type="text" id="sf-title" name="seoforge_meta[seo_title]" class="widefat" maxlength="80"
                       value="<?php echo esc_attr( $row['seo_title'] ?? '' ); ?>">
            </p>
            <p>
                <label for="sf-desc"><?php esc_html_e( 'Meta description', 'brainwerk-seo-suite' ); ?></label>
                <?php if ( $ai_on ) : ?>
                    <button type="button" class="button button-small sf-ai-suggest" data-kind="descriptions" data-post="<?php echo (int) $post->ID; ?>" data-target="#sf-desc" style="float:right">✨ <?php esc_html_e( 'Suggest with AI', 'brainwerk-seo-suite' ); ?></button>
                <?php endif; ?>
                <br>
                <textarea id="sf-desc" name="seoforge_meta[seo_description]" rows="3" class="widefat" maxlength="200"
                ><?php echo esc_textarea( $row['seo_description'] ?? '' ); ?></textarea>
            </p>
            <?php if ( $ai_on ) : ?>
                <p>
                    <button type="button" class="button sf-ai-suggest" data-kind="links" data-post="<?php echo (int) $post->ID; ?>" data-target="#sf-ai-links">
                        ✨ <?php esc_html_e( 'Find internal-link suggestions', 'brainwerk-seo-suite' ); ?>
                    </button>
                </p>
                <div id="sf-ai-links" class="seoforge-ai-results"></div>
            <?php endif; ?>
            <div id="sf-ai-suggestions" class="seoforge-ai-modal" style="display:none">
                <div class="seoforge-ai-modal-inner">
                    <div class="seoforge-ai-modal-head">
                        <strong>✨ <?php esc_html_e( 'AI suggestions', 'brainwerk-seo-suite' ); ?></strong>
                        <button type="button" class="button-link" id="sf-ai-modal-close">×</button>
                    </div>
                    <div id="sf-ai-modal-body" class="seoforge-ai-modal-body">
                        <span class="spinner is-active" style="float:none"></span>
                    </div>
                </div>
            </div>
            <p>
                <label for="sf-og-image"><?php esc_html_e( 'OG image URL', 'brainwerk-seo-suite' ); ?></label><br>
                <input type="url" id="sf-og-image" name="seoforge_meta[og_image]" class="widefat"
                       value="<?php echo esc_url( $row['og_image'] ?? '' ); ?>">
            </p>
            <p>
                <label><input type="checkbox" name="seoforge_meta[robots_noindex]" value="1"
                    <?php checked( ! empty( $row['robots_noindex'] ) ); ?>>
                    <?php esc_html_e( 'Hide from search engines (noindex)', 'brainwerk-seo-suite' ); ?></label><br>
                <label><input type="checkbox" name="seoforge_meta[robots_nofollow]" value="1"
                    <?php checked( ! empty( $row['robots_nofollow'] ) ); ?>>
                    <?php esc_html_e( 'Don\'t follow links (nofollow)', 'brainwerk-seo-suite' ); ?></label>
            </p>

            <?php
            $faq = get_post_meta( $post->ID, '_seoforge_faq', true );
            $faq = is_array( $faq ) ? array_values( $faq ) : array();
            ?>
            <h4><?php esc_html_e( 'FAQ', 'brainwerk-seo-suite' ); ?> 🤖
                <span class="sf-faq-hint" title="Generative Engine Optimization">(<?php esc_html_e( 'for AI answers & rich results', 'brainwerk-seo-suite' ); ?>)</span>
            </h4>
            <p class="description"><?php esc_html_e( 'Question/answer pairs output as FAQPage schema. Leave empty for none.', 'brainwerk-seo-suite' ); ?></p>
            <div id="sf-faq-list">
                <?php foreach ( $faq as $i => $pair ) : ?>
                    <div class="sf-faq-row">
                        <input type="text" name="seoforge_faq[<?php echo (int) $i; ?>][q]" class="widefat" placeholder="<?php esc_attr_e( 'Question', 'brainwerk-seo-suite' ); ?>"
                               value="<?php echo esc_attr( $pair['q'] ?? '' ); ?>">
                        <textarea name="seoforge_faq[<?php echo (int) $i; ?>][a]" rows="2" class="widefat" placeholder="<?php esc_attr_e( 'Answer', 'brainwerk-seo-suite' ); ?>"><?php echo esc_textarea( $pair['a'] ?? '' ); ?></textarea>
                        <button type="button" class="button-link sf-faq-remove" aria-label="<?php esc_attr_e( 'Remove', 'brainwerk-seo-suite' ); ?>">× <?php esc_html_e( 'Remove', 'brainwerk-seo-suite' ); ?></button>
                    </div>
                <?php endforeach; ?>
            </div>
            <button type="button" class="button sf-faq-add">+ <?php esc_html_e( 'Add question', 'brainwerk-seo-suite' ); ?></button>
            <script type="text/html" id="sf-faq-tmpl">
                <div class="sf-faq-row">
                    <input type="text" name="seoforge_faq[__i__][q]" class="widefat" placeholder="<?php esc_attr_e( 'Question', 'brainwerk-seo-suite' ); ?>">
                    <textarea name="seoforge_faq[__i__][a]" rows="2" class="widefat" placeholder="<?php esc_attr_e( 'Answer', 'brainwerk-seo-suite' ); ?>"></textarea>
                    <button type="button" class="button-link sf-faq-remove" aria-label="<?php esc_attr_e( 'Remove', 'brainwerk-seo-suite' ); ?>">× <?php esc_html_e( 'Remove', 'brainwerk-seo-suite' ); ?></button>
                </div>
            </script>

            <?php if ( ! empty( $checks ) && is_array( $checks ) ) : ?>
                <h4><?php esc_html_e( 'Checks', 'brainwerk-seo-suite' ); ?></h4>
                <ul class="seoforge-checks">
                    <?php foreach ( $checks as $key => $c ) : ?>
                        <li class="seoforge-check seoforge-check-<?php echo esc_attr( $c['status'] ); ?>">
                            <span class="seoforge-check-icon" aria-hidden="true"><?php echo esc_html( self::status_icon( $c['status'] ) ); ?></span>
                            <strong><?php echo esc_html( ucwords( str_replace( '_', ' ', $key ) ) ); ?>:</strong>
                            <?php echo esc_html( $c['message'] ); ?>
                            <?php if ( ! empty( $c['tip'] ) && 'ok' !== $c['status'] ) : ?>
                                <div class="seoforge-check-tip"><?php echo esc_html( $c['tip'] ); ?></div>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </div>
        <?php
    }

    public static function save( $post_id, $post ) {
        if ( ! isset( $_POST['seoforge_post_meta_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['seoforge_post_meta_nonce'] ) ), self::NONCE ) ) {
            return;
        }
        if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
            return;
        }
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
        if ( ! empty( $_POST['seoforge_meta'] ) && is_array( $_POST['seoforge_meta'] ) ) {
            $existing = Seoforge_Meta::get_post_meta( $post_id );
            // Sanitize the submitted array early; Seoforge_Meta::save_post_meta() re-sanitizes each known field per its context (URL/textarea/int) before writing.
            $submitted = map_deep( wp_unslash( $_POST['seoforge_meta'] ), 'sanitize_text_field' );
            $merged    = array_replace( $existing, $submitted );
            Seoforge_Meta::save_post_meta( $post_id, $merged );
        }

        // FAQ pairs (FAQPage schema). Stored separately from the meta fields.
        self::save_faq( $post_id );
    }

    private static function save_faq( $post_id ) {
        if ( empty( $_POST['seoforge_faq'] ) || ! is_array( $_POST['seoforge_faq'] ) ) {
            delete_post_meta( $post_id, '_seoforge_faq' );
            return;
        }
        $raw   = wp_unslash( $_POST['seoforge_faq'] ); // phpcs:ignore WordPress.Security.NonceVerification -- nonce checked at top of save().
        $pairs = array();
        foreach ( (array) $raw as $row ) {
            $q = isset( $row['q'] ) ? sanitize_text_field( $row['q'] ) : '';
            $a = isset( $row['a'] ) ? sanitize_textarea_field( $row['a'] ) : '';
            if ( '' === trim( $q ) || '' === trim( $a ) ) {
                continue;
            }
            $pairs[] = array( 'q' => $q, 'a' => $a );
        }
        if ( empty( $pairs ) ) {
            delete_post_meta( $post_id, '_seoforge_faq' );
        } else {
            update_post_meta( $post_id, '_seoforge_faq', $pairs );
        }
    }

    private static function score_class( $score ) {
        if ( $score >= 80 ) return 'good';
        if ( $score >= 50 ) return 'ok';
        return 'bad';
    }

    /** Text status indicator for a check — kept plain-text so it stays readable without CSS. */
    public static function status_icon( $status ) {
        if ( 'ok' === $status ) return '✓';
        if ( 'warn' === $status ) return '!';
        return '✕';
    }
}
