<?php
add_action("post_updated", function ($post_ID, $post_after, $post_before){
    if (
        defined('DOING_AUTOSAVE') && DOING_AUTOSAVE
        || wp_is_post_revision($post_ID)
        || in_array($post_after->post_status, ['auto-draft', 'trash', 'inherit'])
    ) return;

    
    if (!function_exists("pll_get_post_translations") || !function_exists('get_field')) return;

    $translations = pll_get_post_translations($post_ID);
    if (!$translations || count($translations) < 2) return;

    $default_lang = pll_default_language();
    $default_id   = $translations[$default_lang] ?? 0;
    $current_lang = array_search($post_ID, $translations);

    // لا تنفذ إلا من داخل اللغة الأصلية
    if ($post_ID != $default_id) return;

    unset($translations[$current_lang]);
    $post_type = get_post_type($post_ID);

    foreach ($translations as $translated_id) {
        $fields_to_sync = [];

        if ($post_type === 'page') {
            // صفحات: استخدم meta خاص باسم الخانات المطلوب مزامنتها
            $fields_to_sync = get_post_meta($translated_id, 'sync_meta_items', true);
        } elseif (function_exists('ds1_checkSettings')) {
            // غير ذلك: استخدم إعداد من الكود
            $fields_to_sync = ds1_checkSettings('sync_meta_items_' . $post_type);
            $dont_sync = get_post_meta($post_ID, 'dont_sync_meta_items', true);
            if ($dont_sync) continue;
        }

        if (!is_array($fields_to_sync) || empty($fields_to_sync)) continue;

        $all_meta = get_post_meta($post_ID);

        foreach ($fields_to_sync as $meta_key) {
            $field_key = get_post_meta($post_ID, "_$meta_key", true);
            $acf_field = $field_key ? get_field_object($field_key) : false;

            // Repeater
            if ($acf_field && $acf_field['type'] === 'repeater') {
                foreach ($all_meta as $meta_name => $meta_value) {
                    if (str_starts_with($meta_name, $meta_key) || str_starts_with($meta_name, "_$meta_key")) {
                        update_post_meta($translated_id, $meta_name, $meta_value[0]);
                    }
                }
            } else {
                // عادي
                $value = get_post_meta($post_ID, $meta_key, true);
                update_post_meta($translated_id, $meta_key, $value);
            }
        }
    }

}, 10, 3);
