<?php
namespace Eventman\Admin;


use threewp_broadcast\api\api;
use threewp_broadcast\ThreeWP_Broadcast;

class WPML
{
    
    use LogTrait;

    /**
     * Broadcast completed WPML translations to the blogs the original post is broadcasted to.
     *
     * Meant to be executed on 'wpml_pro_translation_completed', but works with any post id of a translation post.
     *
     * @param $postId string|int post ID of translation post.
     */
    public function broadcastCompletedTranslation($postId) {
        $this->log('Starting broadcast on translation finish.');
        // Get original post
        $originalPostId = apply_filters('wpml_original_element_id', NULL, $postId);
        if ($originalPostId) {
            $this->log("Translation post id: $postId, Original post id: $originalPostId");
            // get the broadcast links for original post
            $api = new api();
            $originalPostLinkController = $api->linking($originalPostId);

//            $this->log("Got original post linking: " . join(" -> ", $originalPostLinkController->));
            if ($originalPostLinkController->is_parent()) {
                // post is parent post
                $broadcastedBlogIds = array_keys($originalPostLinkController->children());

                // get the translation links
                $translationLinkController = $api->linking($postId);
                $translationBroadcastedBlogIds = array_keys($translationLinkController->children());

                // diff blog ids for translation and original
//                $blogIdsToBroadcastTo = array_diff($broadcastedBlogIds, $translationBroadcastedBlogIds);
                $this->log("Broadcasting translation to: " . join(', ', $broadcastedBlogIds));

                // broadcast to remaining blogs
                $api->broadcast_children($postId, $broadcastedBlogIds);
            }
        }
    }

}