<?php
namespace ZS_SEO\AuditOptimization\Core;

defined( 'ABSPATH' ) || exit;

class SchemaManager {

    public function __construct() {
        add_action( 'wp_head', [ $this, 'inject_schema' ], 5 );
    }

    public function inject_schema(): void {
        if ( ! get_option( 'zs_seo_schema_enabled', true ) ) return;

        $schemas = [];

        // WebSite schema (always on homepage)
        if ( is_front_page() || is_home() ) {
            $schemas[] = $this->website_schema();
            $schemas[] = $this->organization_schema();
        }

        // Article / Page schema
        if ( is_singular() ) {
            $schemas[] = $this->article_schema();

            // FAQ schema if FAQs exist
            $faqs = get_post_meta( get_the_ID(), '_zs_seo_faqs', true );
            if ( ! empty( $faqs ) ) {
                $schemas[] = $this->faq_schema( $faqs );
            }

            // Breadcrumb
            $schemas[] = $this->breadcrumb_schema();
        }

        foreach ( array_filter( $schemas ) as $schema ) {
            printf(
                '<script type="application/ld+json">%s</script>' . "\n",
                wp_json_encode( $schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT )
            );
        }
    }

    // ── WebSite ───────────────────────────────────────────────────────────────
    private function website_schema(): array {
        return [
            '@context' => 'https://schema.org',
            '@type'    => 'WebSite',
            'name'     => get_bloginfo( 'name' ),
            'url'      => home_url( '/' ),
            'potentialAction' => [
                '@type'       => 'SearchAction',
                'target'      => [
                    '@type'       => 'EntryPoint',
                    'urlTemplate' => home_url( '/?s={search_term_string}' ),
                ],
                'query-input' => 'required name=search_term_string',
            ],
        ];
    }

    // ── Organization ─────────────────────────────────────────────────────────
    private function organization_schema(): array {
        $logo = get_site_icon_url( 512 );
        $schema = [
            '@context' => 'https://schema.org',
            '@type'    => 'Organization',
            'name'     => get_bloginfo( 'name' ),
            'url'      => home_url( '/' ),
        ];
        if ( $logo ) $schema['logo'] = $logo;
        return $schema;
    }

    // ── Article ───────────────────────────────────────────────────────────────
    private function article_schema(): array {
        $post_id   = get_the_ID();
        $post      = get_post( $post_id );
        $post_type = get_post_type( $post_id );
        $type      = ( $post_type === 'page' ) ? 'WebPage' : 'Article';

        $schema = [
            '@context'         => 'https://schema.org',
            '@type'            => $type,
            'headline'         => get_the_title(),
            'url'              => get_permalink(),
            'datePublished'    => get_the_date( 'c', $post_id ),
            'dateModified'     => get_the_modified_date( 'c', $post_id ),
            'description'      => wp_trim_words( wp_strip_all_tags( $post->post_content ?? '' ), 30 ),
            'author'           => [
                '@type' => 'Person',
                'name'  => get_the_author_meta( 'display_name', $post->post_author ?? 0 ),
            ],
            'publisher'        => [
                '@type' => 'Organization',
                'name'  => get_bloginfo( 'name' ),
                'url'   => home_url( '/' ),
            ],
        ];

        $image = get_the_post_thumbnail_url( $post_id, 'large' );
        if ( $image ) {
            $schema['image'] = $image;
        }

        return $schema;
    }

    // ── FAQ (GEO ─ Answer Engine Optimization) ────────────────────────────────
    private function faq_schema( $faqs ): ?array {
        if ( ! is_array( $faqs ) || empty( $faqs ) ) return null;

        $entities = [];
        foreach ( $faqs as $faq ) {
            if ( empty( $faq['question'] ) || empty( $faq['answer'] ) ) continue;
            $entities[] = [
                '@type'          => 'Question',
                'name'           => sanitize_text_field( $faq['question'] ),
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text'  => wp_kses_post( $faq['answer'] ),
                ],
            ];
        }

        if ( empty( $entities ) ) return null;

        return [
            '@context'   => 'https://schema.org',
            '@type'      => 'FAQPage',
            'mainEntity' => $entities,
        ];
    }

    // ── Breadcrumb ────────────────────────────────────────────────────────────
    private function breadcrumb_schema(): ?array {
        if ( ! is_singular() ) return null;

        $items = [];
        $pos   = 1;

        // Home
        $items[] = [
            '@type'    => 'ListItem',
            'position' => $pos++,
            'name'     => __('Home', 'zs-seo-audit-optimization'),
            'item'     => home_url( '/' ),
        ];

        // Category (posts)
        if ( is_single() ) {
            $cats = get_the_category();
            if ( ! empty( $cats ) ) {
                $items[] = [
                    '@type'    => 'ListItem',
                    'position' => $pos++,
                    'name'     => esc_html( $cats[0]->name ),
                    'item'     => get_category_link( $cats[0]->term_id ),
                ];
            }
        }

        // Current page
        $items[] = [
            '@type'    => 'ListItem',
            'position' => $pos,
            'name'     => esc_html( get_the_title() ),
            'item'     => get_permalink(),
        ];

        return [
            '@context'        => 'https://schema.org',
            '@type'           => 'BreadcrumbList',
            'itemListElement' => $items,
        ];
    }
}
