<?php
/**
 * DBA Frontend v2 — Full SEO code structure
 *
 * Outputs per your spec:
 *  1. JSON-LD: Article (EEAT-enhanced) + BreadcrumbList + FAQPage + HowTo + Speakable + Place
 *  2. EEAT hidden meta (not visible frontend)
 *  3. RSS alternate links (Google Discover)
 *  4. Article + FAQ accordion CSS (reduced vertical spacing)
 *  5. hreflang tags
 *  6. OG + Twitter meta (fallback if no Yoast)
 *  7. Content wrapper with .damalion-article class
 */
class DBA_Frontend {

    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) self::$instance = new self();
        return self::$instance;
    }

    private function __construct() {
        add_action( 'wp_head', array( $this, 'output_all_head_code' ), 1 );
        add_action( 'wp_head', array( $this, 'output_pe_schema' ), 2 );
        add_filter( 'the_content', array( $this, 'enhance_content' ), 20 );
    }

    /**
     * Check if current post is a DBA post
     */
    private function is_dba_post() {
        if ( ! is_single() || get_post_type() !== 'post' ) return false;
        global $post;
        if ( empty( $post ) ) return false;
        return (bool) get_post_meta( $post->ID, '_dba_auto_created', true );
    }

    /**
     * Get the full stored JSON data for this post
     */
    private function get_post_data( $post_id ) {
        $raw = get_post_meta( $post_id, '_dba_json_data', true );
        if ( empty( $raw ) ) return array();
        $data = json_decode( $raw, true );
        return is_array( $data ) ? $data : array();
    }

    /* =================================================================
     *  MASTER HEAD OUTPUT
     * ================================================================= */

    public function output_all_head_code() {
        if ( ! $this->is_dba_post() ) return;

        global $post;
        $data = $this->get_post_data( $post->ID );

        // 1. Article CSS + FAQ accordion CSS
        $this->output_article_css();

        // 2. EEAT hidden meta
        $this->output_eeat_meta( $post );

        // 3. RSS alternate links (Google Discover)
        $this->output_rss_alternates( $post, $data );

        // 4. OG + Twitter meta (fallback)
        $this->output_og_meta( $post );

        // 5. hreflang
        $this->output_hreflang( $post->ID );

        // 6. JSON-LD: all 6 schemas (one <script> block each, line by line)
        $this->output_jsonld_article( $post, $data );
        $this->output_jsonld_breadcrumb( $post, $data );
        $this->output_jsonld_faqpage( $post, $data );
        $this->output_jsonld_howto( $post, $data );
        $this->output_jsonld_speakable( $post, $data );
        $this->output_jsonld_place();
    }

    /* =================================================================
     *  1. ARTICLE + FAQ ACCORDION CSS (reduced vertical spacing)
     * ================================================================= */

    private function output_article_css() {
        echo '<style>' . "\n";
        echo '.damalion-article p {' . "\n";
        echo '  margin: 0.35em 0;' . "\n";
        echo '}' . "\n";
        echo '.damalion-article h2 {' . "\n";
        echo '  margin: 1em 0 0.4em 0;' . "\n";
        echo '}' . "\n";
        echo '.damalion-article h3 {' . "\n";
        echo '  margin: 0.7em 0 0.35em 0;' . "\n";
        echo '}' . "\n";
        echo '.damalion-article ul,' . "\n";
        echo '.damalion-article ol {' . "\n";
        echo '  margin: 0.35em 0 0.55em 1.4em;' . "\n";
        echo '}' . "\n";
        echo '.damalion-article .dba-last-updated {' . "\n";
        echo '  font-size: 0.9em;' . "\n";
        echo '  color: #666;' . "\n";
        echo '  margin: 0.3em 0 0.8em 0;' . "\n";
        echo '}' . "\n";
        echo '.faq-accordion {' . "\n";
        echo '  margin: 0.4em 0;' . "\n";
        echo '}' . "\n";
        echo '.faq-accordion details {' . "\n";
        echo '  margin: 0.1em 0;' . "\n";
        echo '  border-bottom: 1px solid #eee;' . "\n";
        echo '  padding: 0.3em 0;' . "\n";
        echo '}' . "\n";
        echo '.faq-accordion summary {' . "\n";
        echo '  cursor: pointer;' . "\n";
        echo '  font-weight: 600;' . "\n";
        echo '  padding: 0.4em 0;' . "\n";
        echo '  list-style: none;' . "\n";
        echo '  display: flex;' . "\n";
        echo '  justify-content: space-between;' . "\n";
        echo '  align-items: center;' . "\n";
        echo '}' . "\n";
        echo '.faq-accordion summary::after {' . "\n";
        echo '  content: "▸";' . "\n";
        echo '  font-size: 1.2em;' . "\n";
        echo '  transition: transform 0.2s;' . "\n";
        echo '}' . "\n";
        echo '.faq-accordion details[open] summary::after {' . "\n";
        echo '  transform: rotate(90deg);' . "\n";
        echo '}' . "\n";
        echo '.faq-accordion summary::-webkit-details-marker {' . "\n";
        echo '  display: none;' . "\n";
        echo '}' . "\n";
        echo '.faq-accordion details p {' . "\n";
        echo '  padding: 0.2em 0 0.4em 0.5em;' . "\n";
        echo '  color: #444;' . "\n";
        echo '}' . "\n";
        echo '.damalion-article .dba-glossary-section {' . "\n";
        echo '  margin-top: 1.2em;' . "\n";
        echo '}' . "\n";
        echo '</style>' . "\n";
    }

    /* =================================================================
     *  2. E-E-A-T HIDDEN META (not visible frontend — for Google SEO)
     * ================================================================= */

    private function output_eeat_meta( $post ) {
        $theme   = get_post_meta( $post->ID, '_dba_theme', true );
        $subject = get_post_meta( $post->ID, '_dba_subject', true );

        // EEAT signals — hidden meta
        echo '<!-- EEAT Signals -->' . "\n";
        echo '<meta name="author" content="Damalion — Independent Consulting Corporation" />' . "\n";
        echo '<meta name="expertise" content="Luxembourg corporate structuring, international tax, ' . esc_attr( $theme ) . '" />' . "\n";
        echo '<meta name="experience" content="Damalion advises international investors, family offices, and fund managers on Luxembourg holding structures since 2011." />' . "\n";
        echo '<meta name="authoritativeness" content="Damalion is a registered independent consulting firm licensed in Luxembourg, serving clients across 30+ jurisdictions." />' . "\n";
        echo '<meta name="trustworthiness" content="All content reviewed by qualified professionals. Sources include official legislation, government agencies, and verified industry data." />' . "\n";
        echo '<meta name="content-type" content="Expert analysis — ' . esc_attr( ucfirst( $subject ) ) . ' — ' . esc_attr( $theme ) . '" />' . "\n";
        echo '<meta name="geo.region" content="LU" />' . "\n";
        echo '<meta name="geo.placename" content="Luxembourg" />' . "\n";
        echo '<meta name="geo.position" content="49.6117;6.1300" />' . "\n";
        echo '<meta name="ICBM" content="49.6117, 6.1300" />' . "\n";
    }

    /* =================================================================
     *  3. RSS ALTERNATE LINKS (Google Discover optimization)
     * ================================================================= */

    private function output_rss_alternates( $post, $data ) {
        // Main feed
        echo '<link rel="alternate" type="application/rss+xml" title="Damalion Blog Feed" href="https://www.damalion.com/feed/" />' . "\n";

        // Category-specific feed (contextual to the post)
        $categories = get_the_category( $post->ID );
        if ( ! empty( $categories ) ) {
            foreach ( $categories as $cat ) {
                $slug = $cat->slug;
                $name = esc_attr( $cat->name );
                echo '<link rel="alternate" type="application/rss+xml" title="' . $name . ' Feed" href="https://www.damalion.com/category/' . esc_attr( $slug ) . '/feed/" />' . "\n";
            }
        }

        // Breadcrumb category feed (from generated data)
        $bc = $data['breadcrumb_category'] ?? '';
        if ( ! empty( $bc ) ) {
            $bc_slug = sanitize_title( $bc );
            echo '<link rel="alternate" type="application/rss+xml" title="' . esc_attr( $bc ) . ' Feed" href="https://www.damalion.com/category/' . esc_attr( $bc_slug ) . '/feed/" />' . "\n";
        }
    }

    /* =================================================================
     *  4. OG + TWITTER META (fallback if Yoast not active)
     * ================================================================= */

    private function output_og_meta( $post ) {
        if ( defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'AIOSEO_VERSION' ) ) return;

        $title   = get_the_title( $post );
        $excerpt = wp_strip_all_tags( get_the_excerpt( $post ) );
        $url     = get_permalink( $post );

        echo '<meta property="og:title" content="' . esc_attr( $title ) . '" />' . "\n";
        echo '<meta property="og:description" content="' . esc_attr( $excerpt ) . '" />' . "\n";
        echo '<meta property="og:type" content="article" />' . "\n";
        echo '<meta property="og:url" content="' . esc_url( $url ) . '" />' . "\n";
        echo '<meta property="og:site_name" content="Damalion" />' . "\n";
        echo '<meta property="article:published_time" content="' . get_the_date( 'c', $post ) . '" />' . "\n";
        echo '<meta property="article:modified_time" content="' . get_the_modified_date( 'c', $post ) . '" />' . "\n";

        if ( has_post_thumbnail( $post ) ) {
            $img = wp_get_attachment_image_url( get_post_thumbnail_id( $post ), 'large' );
            if ( $img ) echo '<meta property="og:image" content="' . esc_url( $img ) . '" />' . "\n";
        }

        echo '<meta name="twitter:card" content="summary_large_image" />' . "\n";
        echo '<meta name="twitter:title" content="' . esc_attr( $title ) . '" />' . "\n";
        echo '<meta name="twitter:description" content="' . esc_attr( $excerpt ) . '" />' . "\n";

        if ( ! empty( $excerpt ) ) {
            echo '<meta name="description" content="' . esc_attr( $excerpt ) . '" />' . "\n";
        }
    }

    /* =================================================================
     *  5. HREFLANG
     * ================================================================= */

    private function output_hreflang( $post_id ) {
        if ( function_exists( 'icl_get_languages' ) ) return; // WPML handles it
        $lang = get_post_meta( $post_id, '_dba_language', true );
        if ( ! empty( $lang ) ) {
            echo '<link rel="alternate" hreflang="' . esc_attr( $lang ) . '" href="' . esc_url( get_permalink( $post_id ) ) . '" />' . "\n";
        }
    }

    /* =================================================================
     *  6a. JSON-LD: ARTICLE (EEAT-enhanced)
     * ================================================================= */

    private function output_jsonld_article( $post, $data ) {
        $title   = get_the_title( $post );
        $excerpt = wp_strip_all_tags( get_the_excerpt( $post ) );
        $url     = get_permalink( $post );
        $theme   = get_post_meta( $post->ID, '_dba_theme', true );
        $img_url = '';

        if ( has_post_thumbnail( $post ) ) {
            $img_url = wp_get_attachment_image_url( get_post_thumbnail_id( $post ), 'full' );
        }

        $s = array();
        $s['@context']         = 'https://schema.org';
        $s['@type']            = 'Article';
        $s['mainEntityOfPage'] = array(
            '@type' => 'WebPage',
            '@id'   => $url,
        );
        $s['headline']       = $title;
        $s['description']    = $excerpt;
        $s['datePublished']  = get_the_date( 'c', $post );
        $s['dateModified']   = get_the_modified_date( 'c', $post );
        $s['url']            = $url;

        if ( $img_url ) {
            $s['image'] = array(
                '@type'  => 'ImageObject',
                'url'    => $img_url,
                'width'  => 950,
                'height' => 762,
            );
        }

        $s['author'] = array(
            '@type'       => 'Organization',
            'name'        => 'Damalion',
            'url'         => 'https://www.damalion.com',
            'description' => 'Independent consulting corporation — Luxembourg corporate structuring, fund setup, tax advisory.',
        );

        $s['publisher'] = array(
            '@type' => 'Organization',
            'name'  => 'Damalion',
            'url'   => 'https://www.damalion.com',
            'logo'  => array(
                '@type'  => 'ImageObject',
                'url'    => 'https://www.damalion.com/wp-content/uploads/2021/03/damalion-logo.png',
                'width'  => 300,
                'height' => 60,
            ),
        );

        if ( $theme ) {
            $s['articleSection'] = $theme;
        }

        $s['inLanguage'] = get_post_meta( $post->ID, '_dba_language', true ) ?: 'en';

        // Keywords from tags
        $tags = get_the_tags( $post->ID );
        if ( $tags ) {
            $s['keywords'] = implode( ', ', wp_list_pluck( $tags, 'name' ) );
        }

        $this->echo_jsonld( $s );
    }

    /* =================================================================
     *  6b. JSON-LD: BREADCRUMBLIST
     * ================================================================= */

    private function output_jsonld_breadcrumb( $post, $data ) {
        $bc_cat = $data['breadcrumb_category'] ?? '';
        $categories = get_the_category( $post->ID );
        $cat_name = ! empty( $categories ) ? $categories[0]->name : $bc_cat;
        $cat_slug = ! empty( $categories ) ? $categories[0]->slug : sanitize_title( $bc_cat );

        $s = array();
        $s['@context'] = 'https://schema.org';
        $s['@type']    = 'BreadcrumbList';
        $s['itemListElement'] = array(
            array(
                '@type'    => 'ListItem',
                'position' => 1,
                'name'     => 'Home',
                'item'     => 'https://www.damalion.com',
            ),
            array(
                '@type'    => 'ListItem',
                'position' => 2,
                'name'     => $cat_name ?: 'Blog',
                'item'     => 'https://www.damalion.com/category/' . ( $cat_slug ?: 'blog' ) . '/',
            ),
            array(
                '@type'    => 'ListItem',
                'position' => 3,
                'name'     => get_the_title( $post ),
                'item'     => get_permalink( $post ),
            ),
        );

        $this->echo_jsonld( $s );
    }

    /* =================================================================
     *  6c. JSON-LD: FAQPAGE (mirrors visible FAQ accordion word-for-word)
     * ================================================================= */

    private function output_jsonld_faqpage( $post, $data ) {
        $faqs = $data['faqs'] ?? array();
        if ( empty( $faqs ) || ! is_array( $faqs ) ) return;

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

        if ( empty( $entities ) ) return;

        $s = array();
        $s['@context']      = 'https://schema.org';
        $s['@type']         = 'FAQPage';
        $s['mainEntity']    = $entities;

        $this->echo_jsonld( $s );
    }

    /* =================================================================
     *  6d. JSON-LD: HOWTO (from howto_steps)
     * ================================================================= */

    private function output_jsonld_howto( $post, $data ) {
        $steps = $data['howto_steps'] ?? array();
        if ( empty( $steps ) || ! is_array( $steps ) ) return;

        $step_items = array();
        $pos = 1;
        foreach ( $steps as $step ) {
            if ( empty( $step['name'] ) ) continue;
            $step_items[] = array(
                '@type'    => 'HowToStep',
                'position' => $pos,
                'name'     => $step['name'],
                'text'     => $step['text'] ?? $step['name'],
                'url'      => get_permalink( $post ) . '#step-' . $pos,
            );
            $pos++;
        }

        if ( empty( $step_items ) ) return;

        $s = array();
        $s['@context']    = 'https://schema.org';
        $s['@type']       = 'HowTo';
        $s['name']        = 'How to structure a ' . ( get_post_meta( $post->ID, '_dba_subject', true ) ?: 'holding' ) . ' — ' . get_the_title( $post );
        $s['description'] = wp_strip_all_tags( get_the_excerpt( $post ) );
        $s['step']        = $step_items;

        $this->echo_jsonld( $s );
    }

    /* =================================================================
     *  6e. JSON-LD: SPEAKABLE
     * ================================================================= */

    private function output_jsonld_speakable( $post, $data ) {
        $speakable = $data['speakable_text'] ?? '';
        if ( empty( $speakable ) ) {
            // Fallback: headline + excerpt
            $speakable = get_the_title( $post ) . '. ' . wp_strip_all_tags( get_the_excerpt( $post ) );
        }

        $s = array();
        $s['@context']  = 'https://schema.org';
        $s['@type']     = 'WebPage';
        $s['name']      = get_the_title( $post );
        $s['url']       = get_permalink( $post );
        $s['speakable'] = array(
            '@type'    => 'SpeakableSpecification',
            'cssSelector' => array(
                '.damalion-article h1',
                '.damalion-article > p:first-of-type',
            ),
        );

        $this->echo_jsonld( $s );
    }

    /* =================================================================
     *  6f. JSON-LD: PLACE (Luxembourg office — static)
     * ================================================================= */

    private function output_jsonld_place() {
        $s = array();
        $s['@context'] = 'https://schema.org';
        $s['@type']    = 'Place';
        $s['name']     = 'Damalion — Luxembourg Office';
        $s['address']  = array(
            '@type'           => 'PostalAddress',
            'streetAddress'   => '17, Boulevard Royal',
            'addressLocality' => 'Luxembourg',
            'postalCode'      => 'L-2449',
            'addressCountry'  => 'LU',
        );
        $s['geo'] = array(
            '@type'     => 'GeoCoordinates',
            'latitude'  => 49.6117,
            'longitude' => 6.1300,
        );
        $s['url'] = 'https://www.damalion.com';

        $this->echo_jsonld( $s );
    }

    /* =================================================================
     *  JSON-LD OUTPUT HELPER — strict formatting: one property per line
     * ================================================================= */

    /**
     * Output Article schema for PE/Capital Markets news posts
     */
    public function output_pe_schema() {
        if ( ! is_single() || get_post_type() !== 'post' ) return;
        global $post;
        if ( empty( $post ) ) return;

        // Only PE posts (not core DBA posts)
        $is_pe = get_post_meta( $post->ID, '_dba_pe_auto_created', true );
        if ( ! $is_pe ) return;

        $schema_raw = get_post_meta( $post->ID, '_dba_pe_schema', true );
        $geo      = get_post_meta( $post->ID, '_dba_pe_geography', true );
        $company  = get_post_meta( $post->ID, '_dba_pe_company', true );
        $category = get_post_meta( $post->ID, '_dba_pe_category', true );

        // Build Article schema
        $s = array(
            '@context'       => 'https://schema.org',
            '@type'          => 'Article',
            'headline'       => get_the_title( $post->ID ),
            'datePublished'  => get_the_date( 'c', $post->ID ),
            'dateModified'   => get_the_modified_date( 'c', $post->ID ),
            'articleSection' => $category ? $category : 'Capital markets',
            'about'          => array(
                '@type' => 'Thing',
                'name'  => $company ? $company : '',
            ),
            'author'         => array(
                '@type' => 'Organization',
                'name'  => get_bloginfo( 'name' ),
                'url'   => home_url(),
            ),
            'publisher'      => array(
                '@type' => 'Organization',
                'name'  => get_bloginfo( 'name' ),
                'url'   => home_url(),
            ),
            'mainEntityOfPage' => get_permalink( $post->ID ),
        );

        // Merge any schema from OpenAI response
        if ( ! empty( $schema_raw ) ) {
            if ( is_string( $schema_raw ) ) {
                $extra = json_decode( $schema_raw, true );
            } else {
                $extra = $schema_raw;
            }
            if ( is_array( $extra ) ) {
                $s = array_merge( $s, $extra );
            }
        }

        // Add featured image if available
        if ( has_post_thumbnail( $post->ID ) ) {
            $s['image'] = get_the_post_thumbnail_url( $post->ID, 'full' );
        }

        $this->echo_jsonld( $s );
    }

    private function echo_jsonld( $schema ) {
        echo '<script type="application/ld+json">' . "\n";
        echo wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
        echo "\n" . '</script>' . "\n";
    }

    /* =================================================================
     *  CONTENT ENHANCEMENT
     * ================================================================= */

    public function enhance_content( $content ) {
        if ( ! is_single() || get_post_type() !== 'post' ) return $content;

        $post_id = get_the_ID();
        $is_dba  = get_post_meta( $post_id, '_dba_auto_created', true );
        if ( ! $is_dba ) return $content;

        $theme   = get_post_meta( $post_id, '_dba_theme', true );
        $subject = get_post_meta( $post_id, '_dba_subject', true );

        // Theme/subject badge
        $badge = '';
        if ( $theme ) {
            $badge = '<div class="dba-article-meta">';
            $badge .= '<span class="dba-theme-badge">' . esc_html( $theme ) . '</span>';
            if ( $subject ) {
                $badge .= ' <span class="dba-subject-badge">' . esc_html( $subject ) . '</span>';
            }
            $badge .= '</div>';
        }

        // Wrap with .damalion-article class (required for CSS + speakable selector)
        $content = '<div class="damalion-article">' . $badge . $content . '</div>';

        return $content;
    }
}
