<?php
/**
 * Plugin Name: MB Blocks Wpml
 * Description: WPML Translations support for mb blo .
 * Version:     0.0.1
 * Text Domain: mb-blocks
 * Domain Path: /languages/
 *
 * @package    Meta Box
 * @subpackage MB Blocks Wpml
 */

// Prevent loading this file directly.
defined("ABSPATH") || die();

if (!is_plugin_active("sitepress-multilingual-cms/sitepress.php")) {
  return;
}

const WPML_ALLOWED_METABOX_TYPES = ["text", "textarea", "wysiwyg"];

function mb_block_get_wpml_cfg($nodes) {
  $result = [];

  foreach ($nodes as $node) {
    $type = $node["type"];
    $translate = isset($node["translate"])
      ? $node["translate"]
      : in_array($type, WPML_ALLOWED_METABOX_TYPES);

    if ($translate) {
      $result[] = [
        "value" => "",
        "attr" => [
          "name" => $node["id"],
        ],
      ];
    } else {
      if (isset($node["fields"]) && $node["fields"]) {
        $sub = mb_block_get_wpml_cfg($node["fields"]);
        if (count($sub)) {
          $result[] = [
            "value" => "",
            "attr" => [
              "name" => $node["id"],
            ],
            "key" => [
              "value" => "",
              "attr" => [
                "name" => "*",
              ],
              "key" => $sub,
            ],
          ];
        }
      }
    }
  }
  return $result;
}

add_filter("wpml_config_array", function ($config) {
  $rwmb_registry = rwmb_get_registry("meta_box");
  $blocks = $rwmb_registry->get_by(["type" => "block"]);

  foreach ($blocks as $mb_id => $block) {
    $cfg = mb_block_get_wpml_cfg($block->meta_box["fields"]);
    if (count($cfg)) {
      $config["wpml-config"]["gutenberg-blocks"]["gutenberg-block"][] = [
        "value" => "",
        "attr" => [
          "type" => "meta-box/$mb_id",
          "translate" => "1",
        ],
        "key" => [
          "value" => "",
          "attr" => [
            "name" => "data",
          ],
          "key" => $cfg,
        ],
      ];
    }
  }

  return $config;
});

add_filter("rwmb_meta_render_reusable_block_id", function ($post_id) {
  return apply_filters("wpml_object_id", $post_id, "wp_block", true, null);
});
