<?php


namespace Eventman\Admin;

use threewp_broadcast\api\api;
use WPSEO_Meta;
use Yoast\WP\SEO\Presentations\Indexable_Presentation;
use Yoast\WP\SEO\Values\Open_Graph\Images;

/**
 * Fixes Yoast's OG: tags for canonincals, images etc.
 */
class OpengraphFix
{

    public function __construct()
    {
        add_filter('wpseo_add_opengraph_images', [$this, 'add_og_images'], 10, 2);
        add_filter('wpseo_canonical', [$this, 'get_parent_post_canonical'], 10);
        add_filter('wpseo_opengraph_url', [$this, 'og_url_to_canonical'], 10);
    }

    public function get_parent_post_canonical(?string $url = null)
    {
        global $post;
        $api = new api();
        $linking = $api->linking(get_current_blog_id(), $post->ID);
        if ($linking->is_child()) {
            $parent = $linking->parent();

            // set the canonical parent URL
            switch_to_blog($parent['blog_id']);
            $url = get_permalink($parent['post_id']);
            restore_current_blog();
        }

        return $url;
    }

    public function og_url_to_canonical(?string $opengraph_url = null)
    {
        return $this->get_parent_post_canonical($opengraph_url);
    }


    public function add_og_images(Images $images_container)
    {
        global $post;

        if (!empty($post->ID) && !$images_container->has_images()) {
            $attachment = current(get_posts([
                'post_type' => 'attachment',
                'posts_per_page' => -1,
                'post_parent' => $post->ID
            ]));

            if ($attachment) {
                $images_container->add_image_by_id($attachment->ID);
            }
        }
    }

}