<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-seo-head.php
// Description: Injects SEO meta tags into wp_head — title, meta description, canonical, robots, OG tags, JSON-LD schema - NUCLEAR+++
// Last Edited: 2026-04-25
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

class SeoHead
{
    // --------------------------------------------------
    // Register all hooks — called from automarketer-ai.php boot
    // --------------------------------------------------
    public static function register(): void
    {
        // Override document title
        add_filter('document_title_parts', [self::class, 'filterTitle'], 20);

        // Inject meta tags into <head>
        add_action('wp_head', [self::class, 'outputMetaTags'], 1);

        // Inject JSON-LD schema into <head>
        add_action('wp_head', [self::class, 'outputSchemaOrg'], 2);

        // Remove default wp_head title tag so ours is the only one
        add_theme_support('title-tag');
    }

    // --------------------------------------------------
    // Filter the document title — replaces <title> tag content
    // Only fires on singular posts/pages/products
    // --------------------------------------------------
    public static function filterTitle(array $parts): array
    {
        if (!is_singular()) {
            return $parts;
        }

        $post_id    = (int) get_queried_object_id();
        $meta_title = SeoData::get($post_id, 'meta_title');

        if ($meta_title !== null && $meta_title !== '') {
            $parts['title'] = $meta_title;
        }

        return $parts;
    }

    // --------------------------------------------------
    // Output all meta tags into <head>
    // Only fires on singular posts/pages/products
    // --------------------------------------------------
    public static function outputMetaTags(): void
    {
        if (!is_singular()) {
            return;
        }

        $post_id = (int) get_queried_object_id();
        $post    = get_post($post_id);
        if (!$post instanceof \WP_Post) {
            return;
        }

        $data = SeoData::getAll($post_id);

        $meta_title  = self::coerce($data['meta_title'])       ?? get_the_title($post_id);
        $meta_desc   = self::coerce($data['meta_description']) ?? '';
        $canonical   = self::coerce($data['canonical_url'])    ?? (string) get_permalink($post_id);
        $robots      = self::coerce($data['robots'])           ?? 'index,follow';
        $og_title    = self::coerce($data['og_title'])         ?? $meta_title;
        $og_desc     = self::coerce($data['og_description'])   ?? $meta_desc;
        $og_image_id = (int) ($data['og_image_id'] ?? 0);

        // Derive OG image URL from attachment ID or fall back to featured image
        $og_image_url = '';
        if ($og_image_id > 0) {
            $src = wp_get_attachment_image_url($og_image_id, 'large');
            if ($src !== false) {
                $og_image_url = $src;
            }
        }
        if ($og_image_url === '') {
            $thumb_id = (int) get_post_thumbnail_id($post_id);
            if ($thumb_id > 0) {
                $src = wp_get_attachment_image_url($thumb_id, 'large');
                if ($src !== false) {
                    $og_image_url = $src;
                }
            }
        }

        $site_name = get_bloginfo('name');
        $og_type   = self::ogType($post->post_type);
        $permalink = (string) get_permalink($post_id);

        echo "\n<!-- AutoMarketer AI SEO -->\n";

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

        // robots
        echo '<meta name="robots" content="' . esc_attr($robots) . '" />' . "\n";

        // canonical
        echo '<link rel="canonical" href="' . esc_url($canonical) . '" />' . "\n";

        // Open Graph
        echo '<meta property="og:type" content="' . esc_attr($og_type) . '" />' . "\n";
        echo '<meta property="og:title" content="' . esc_attr($og_title) . '" />' . "\n";
        echo '<meta property="og:url" content="' . esc_url($permalink) . '" />' . "\n";
        echo '<meta property="og:site_name" content="' . esc_attr($site_name) . '" />' . "\n";

        if ($og_desc !== '') {
            echo '<meta property="og:description" content="' . esc_attr($og_desc) . '" />' . "\n";
        }

        if ($og_image_url !== '') {
            echo '<meta property="og:image" content="' . esc_url($og_image_url) . '" />' . "\n";
        }

        // Twitter card
        echo '<meta name="twitter:card" content="' . ($og_image_url !== '' ? 'summary_large_image' : 'summary') . '" />' . "\n";
        echo '<meta name="twitter:title" content="' . esc_attr($og_title) . '" />' . "\n";

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

        if ($og_image_url !== '') {
            echo '<meta name="twitter:image" content="' . esc_url($og_image_url) . '" />' . "\n";
        }

        echo "<!-- /AutoMarketer AI SEO -->\n\n";
    }

    // --------------------------------------------------
    // Output JSON-LD schema into <head>
    // Only fires on singular posts — not pages, archives, or admin
    // --------------------------------------------------
    public static function outputSchemaOrg(): void
    {
        if (!is_singular('post')) {
            return;
        }

        $post_id = (int) get_queried_object_id();
        $post    = get_post($post_id);
        if (!$post instanceof \WP_Post) {
            return;
        }

        $data = SeoData::getAll($post_id);

        $headline   = self::coerce($data['meta_title'])       ?? get_the_title($post_id);
        $description = self::coerce($data['meta_description']) ?? '';
        $keywords   = self::coerce($data['focus_keyword'])    ?? '';
        $permalink  = (string) get_permalink($post_id);
        $published  = gmdate('c', (int) strtotime($post->post_date_gmt . ' UTC'));
        $modified   = gmdate('c', (int) strtotime($post->post_modified_gmt . ' UTC'));

        // Author
        $author_id   = (int) $post->post_author;
        $author_name = get_the_author_meta('display_name', $author_id);

        // Publisher — site identity
        $publisher_name = get_bloginfo('name');
        $publisher_url  = get_bloginfo('url');
        $logo_url       = get_site_icon_url(512);

        // Featured image
        $image_url = '';
        $thumb_id  = (int) get_post_thumbnail_id($post_id);
        if ($thumb_id > 0) {
            $src = wp_get_attachment_image_url($thumb_id, 'large');
            if ($src !== false) {
                $image_url = $src;
            }
        }

        // Build schema array
        $schema = [
            '@context'         => 'https://schema.org',
            '@type'            => 'BlogPosting',
            'headline'         => $headline,
            'url'              => $permalink,
            'datePublished'    => $published,
            'dateModified'     => $modified,
            'author'           => [
                '@type' => 'Person',
                'name'  => $author_name,
            ],
            'publisher'        => [
                '@type' => 'Organization',
                'name'  => $publisher_name,
                'url'   => $publisher_url,
            ],
        ];

        if ($description !== '') {
            $schema['description'] = $description;
        }

        if ($keywords !== '') {
            $schema['keywords'] = $keywords;
        }

        if ($image_url !== '') {
            $schema['image'] = $image_url;
        }

        if ($logo_url !== '') {
            $schema['publisher']['logo'] = [
                '@type' => 'ImageObject',
                'url'   => $logo_url,
            ];
        }

        $json = wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        if ($json === false) {
            return;
        }

        echo "\n<!-- AutoMarketer AI Schema -->\n";
        echo '<script type="application/ld+json">' . "\n" . $json . "\n" . '</script>' . "\n";
        echo "<!-- /AutoMarketer AI Schema -->\n\n";
    }

    // --------------------------------------------------
    // Map post type to OG type
    // --------------------------------------------------
    private static function ogType(string $post_type): string
    {
        return match ($post_type) {
            'product' => 'product',
            'page'    => 'website',
            default   => 'article',
        };
    }

    // --------------------------------------------------
    // Coerce mixed SeoData value to string or null
    // --------------------------------------------------
    private static function coerce(mixed $value): ?string
    {
        if ($value === null || $value === '') {
            return null;
        }
        return (string) $value;
    }
}