<?php


function add_wine_product_schema($graph, $context)
{
    if (!is_singular('vins')) {
        return $graph;
    }

    global $post;

    // Récupère les données du produit (vin)
    $wine_name = get_the_title();
    $wine_description = get_the_excerpt() ?: wp_trim_words(get_the_content(), 30);
    $wine_image = get_the_post_thumbnail_url($post->ID, 'large');
    $wine_url = get_permalink();

    $wine_brand = 'Laurent-Perrier';
    $wine_category = 'Champagne';
    // Crée le schéma Product
    $product_schema = [
        '@type' => 'Product',
        '@id' => $wine_url . '#product',
        'name' => $wine_name,
        'description' => $wine_description,
        'brand' => [
            '@type' => 'Brand',
            'name' => $wine_brand
        ],
        'category' => $wine_category,
        'url' => $wine_url
    ];


    $chapitres = get_field('chapitre');
    $reviews = [];
    $ratings = [];

    // Collecte les reviews et ratings
    if (!empty($chapitres)) {
        foreach ($chapitres as $key => $value) {
            $flexible = $value['flexible'];
            foreach ($flexible as $flex) {
                if ($flex['acf_fc_layout'] == 'recompenses') {
                    $recompenses = $flex['recompenses'];
                    foreach ($recompenses as $item) {

                        if ($item['note']) {
                            $ratings[] = $item['note'];
                            $review_schema = [
                                '@type' => 'Review',
                                'reviewRating' => [
                                    '@type' => 'Rating',
                                    'ratingValue' => $item['note'],

                                ],
                                'author' => [
                                    '@type' => 'Organization',
                                    'name' => $item['image']['alt'] ?: ''
                                ]
                            ];

                            // Ajoute la date si disponible
                            if (!empty($item['annee'])) {
                                $review_schema['datePublished'] = $item['annee'] . '-01-01';
                            }

                            $reviews[] = $review_schema;
                        }
                    }
                }
            }
        }
    }

    // Ajoute les reviews au produit
    if (!empty($reviews)) {
        $product_schema['review'] = $reviews;

        // Calcule l'aggregateRating
        if (!empty($ratings)) {
            $average_rating = array_sum($ratings) / count($ratings);
            $product_schema['aggregateRating'] = [
                '@type' => 'AggregateRating',
                'ratingValue' => round($average_rating, 1),
                'reviewCount' => count($ratings),
            ];
        }
    }

    // Ajoute l'image si disponible
    if ($wine_image) {
        $product_schema['image'] = $wine_image;
    }

    foreach ($graph as $key => $node) {
        if ($node['@type'] === 'WebPage') {
            // Modifie le noeud WebPage avec le schéma Product
            $graph[$key] = array_merge($node, $product_schema);
            $graph[$key]['@type'] = 'Product';
            break;
        }
    }

    // var_dump($graph);
    return $graph;
}

// Ajoute un schéma Product pour les pages de vins
add_filter('wpseo_schema_graph', 'add_wine_product_schema', 11, 2);

/**
 * Remove Yoast WebPage piece on single article-like views so only the Article piece remains.
 * We do this conservatively: only strip WebPage if an Article node is present in the graph.
 */
function lp_strip_webpage_when_article_present($graph, $context)
{
    // Target only singular content where we expect an Article (e.g., posts and our guides CPT)
    if (!is_singular()) {
        return $graph;
    }

    // If current post type is clearly not article-like, keep default behavior
    $post = isset($context->post) ? $context->post : get_post();
    if ($post && !in_array($post->post_type, array('post', 'guide'), true)) {
        return $graph;
    }

    $has_article = false;
    foreach ($graph as $node) {
        if (!is_array($node)) {
            continue;
        }
        $type = isset($node['@type']) ? $node['@type'] : null;
        if (is_array($type)) {
            if (in_array('Article', $type, true) || in_array('NewsArticle', $type, true) || in_array('BlogPosting', $type, true)) {
                $has_article = true;
                break;
            }
        } elseif ($type === 'Article' || $type === 'NewsArticle' || $type === 'BlogPosting') {
            $has_article = true;
            break;
        }
    }

    if (!$has_article) {
        return $graph;
    }

    // Remove WebPage nodes
    $filtered = array();
    foreach ($graph as $node) {
        if (!is_array($node)) {
            $filtered[] = $node;
            continue;
        }
        $type = isset($node['@type']) ? $node['@type'] : null;
        $is_webpage = false;
        if (is_array($type)) {
            $is_webpage = in_array('WebPage', $type, true);
        } else {
            $is_webpage = ($type === 'WebPage');
        }

        if (!$is_webpage) {
            $filtered[] = $node;
        }
    }

    // Reindex array to keep graph a clean list
    return array_values($filtered);
}

// Run late to ensure Yoast has built the full graph first
add_filter('wpseo_schema_graph', 'lp_strip_webpage_when_article_present', 99, 2);
