<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * Core SEO support for TNC FlipBook 3D.
 *
 * Outputs meta tags, Open Graph, Twitter Cards, and JSON-LD schema
 * for the standalone flipbook viewer template. Provides action/filter
 * hooks so a future SEO addon can extend behaviour.
 *
 * Hooks used:
 *   - tncfb3d_viewer_head  (action)  - outputs meta into <head>
 *   - tncfb3d_seo_title    (filter)  - customise the resolved title
 *   - tncfb3d_seo_description (filter)
 *   - tncfb3d_seo_og_image (filter)
 *   - tncfb3d_seo_schema   (filter)  - customise JSON-LD object
 *   - tncfb3d_seo_head     (action)  - addon hook for extra <head> output
 *   - tncfb3d_seo_body_content (action) - hidden content in <body> for crawlers
 */
class TNC_Flipbook_3D_SEO {

    public static function init() {
        add_action( 'tncfb3d_viewer_head', array( __CLASS__, 'output_meta_tags' ), 10, 2 );

        // Sitemap support
        add_filter( 'wp_sitemaps_posts_entry', array( __CLASS__, 'sitemap_entry' ), 10, 2 );
    }

    /**
     * Output all SEO meta tags into the viewer <head>.
     *
     * @param int        $post_id  The flipbook post ID.
     * @param array|null $payload  Optional config payload (unused, reserved for future).
     */
    public static function output_meta_tags( $post_id, $payload = null ) {
        $p = TNC_FLIPBOOK_3D_PREFIX;

        // Title
        $seo_title = get_post_meta( $post_id, $p . 'seo_title', true );
        $title     = $seo_title ? $seo_title : ( get_the_title( $post_id ) ? get_the_title( $post_id ) : __( 'FlipBook', 'tnc-flipbook-3d-lite' ) );
        $title     = apply_filters( 'tncfb3d_seo_title', $title, $post_id );

        // Description
        $description = get_post_meta( $post_id, $p . 'seo_description', true );
        $description = apply_filters( 'tncfb3d_seo_description', $description, $post_id );

        // Canonical
        $canonical = get_post_meta( $post_id, $p . 'seo_canonical', true );
        if ( ! $canonical ) {
            $canonical = get_permalink( $post_id );
        }

        /**
         * @hook tncfb3d_seo_canonical
         * @param string $canonical Canonical URL for the flipbook.
         * @param int    $post_id   Flipbook post ID.
         * @return string
         */
        $canonical = apply_filters( 'tncfb3d_seo_canonical', $canonical, $post_id );

        // Robots
        $robots = get_post_meta( $post_id, $p . 'seo_robots', true );
        if ( ! $robots ) {
            $robots = 'index';
        }

        /**
         * @hook tncfb3d_seo_robots
         * @param string $robots  Robots meta directive (e.g. 'index', 'noindex').
         * @param int    $post_id Flipbook post ID.
         * @return string
         */
        $robots = apply_filters( 'tncfb3d_seo_robots', $robots, $post_id );

        // OG Image
        $og_image_id = absint( get_post_meta( $post_id, $p . 'seo_og_image_id', true ) );
        $og_image    = '';
        if ( $og_image_id ) {
            $og_image = wp_get_attachment_url( $og_image_id );
        }
        if ( ! $og_image ) {
            // Fallback to featured image
            $thumb_id = get_post_thumbnail_id( $post_id );
            if ( $thumb_id ) {
                $og_image = wp_get_attachment_url( $thumb_id );
            }
        }
        $og_image = apply_filters( 'tncfb3d_seo_og_image', $og_image, $post_id );

        // ── Output ───────────────────────────────────────────────────────
        if ( $description ) {
            echo '<meta name="description" content="' . esc_attr( $description ) . '">' . "\n";
        }
        echo '<link rel="canonical" href="' . esc_url( $canonical ) . '">' . "\n";
        echo '<meta name="robots" content="' . esc_attr( $robots ) . ', follow">' . "\n";

        // Open Graph
        echo '<meta property="og:type" content="article">' . "\n";
        echo '<meta property="og:title" content="' . esc_attr( $title ) . '">' . "\n";
        if ( $description ) {
            echo '<meta property="og:description" content="' . esc_attr( $description ) . '">' . "\n";
        }
        if ( $og_image ) {
            echo '<meta property="og:image" content="' . esc_url( $og_image ) . '">' . "\n";
        }
        echo '<meta property="og:url" content="' . esc_url( $canonical ) . '">' . "\n";
        echo '<meta property="og:site_name" content="' . esc_attr( get_bloginfo( 'name' ) ) . '">' . "\n";

        // Twitter Card
        echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
        echo '<meta name="twitter:title" content="' . esc_attr( $title ) . '">' . "\n";
        if ( $description ) {
            echo '<meta name="twitter:description" content="' . esc_attr( $description ) . '">' . "\n";
        }
        if ( $og_image ) {
            echo '<meta name="twitter:image" content="' . esc_url( $og_image ) . '">' . "\n";
        }

        // Schema.org JSON-LD (basic - addon can enhance via filter)
        $schema = array(
            '@context' => 'https://schema.org',
            '@type'    => 'WebPage',
            'name'     => $title,
            'url'      => $canonical,
        );
        if ( $description ) {
            $schema['description'] = $description;
        }
        if ( $og_image ) {
            $schema['thumbnailUrl'] = $og_image;
        }

        $schema = apply_filters( 'tncfb3d_seo_schema', $schema, $post_id );
        if ( ! empty( $schema ) ) {
            echo '<script type="application/ld+json">' . wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP ) . '</script>' . "\n";
        }

        // Addon hook for additional meta
        do_action( 'tncfb3d_seo_head', $post_id );
    }

    /**
     * Get the resolved SEO title for a flipbook.
     *
     * @param  int    $post_id  The flipbook post ID.
     * @return string
     */
    public static function get_title( $post_id ) {
        $p         = TNC_FLIPBOOK_3D_PREFIX;
        $seo_title = get_post_meta( $post_id, $p . 'seo_title', true );
        $title     = $seo_title ? $seo_title : ( get_the_title( $post_id ) ? get_the_title( $post_id ) : __( 'FlipBook', 'tnc-flipbook-3d-lite' ) );
        return apply_filters( 'tncfb3d_seo_title', $title, $post_id );
    }

    /**
     * Enhance sitemap entries for flipbook posts.
     *
     * @param  array   $entry  Sitemap entry data.
     * @param  WP_Post $post   The post object.
     * @return array
     */
    public static function sitemap_entry( $entry, $post ) {
        if ( isset( $post->post_type ) && TNC_FLIPBOOK_3D_CPT === $post->post_type ) {
            $entry['lastmod'] = wp_date( 'Y-m-d\TH:i:sP', strtotime( $post->post_modified_gmt ) );
        }
        return $entry;
    }
}
