<?php

namespace RtmBusiness\PostSync\SyncHandlers;

class DefaultSyncHandler extends AbstractSyncHandler
{

    /**
     * @inheritDoc
     */
    public function handle($sourceBlogId, $sourcePostId, $targetBlogId, $targetPostId): void
    {
        global $rtm_source_postdata;
        $sourceMetaData = $rtm_source_postdata['sourceMetaData'];
        $sourcePostData = $rtm_source_postdata['sourcePostData'];

        $sync_metadata = get_site_option('postsync_sync_metadata', false) == 1;

        if ($sync_metadata) {
            $excluded_meta_fields = get_site_option("postsync_" . $sourcePostData['post_type'] . "_excluded_meta_fields", []);
            // Allow other plugins to modify the excluded meta fields
            $excluded_meta_fields = apply_filters('postsync_excluded_meta_fields', $excluded_meta_fields, $sourcePostData['post_type']);

            //Define some default excluded fields
            $excluded_meta_fields[] = '_wp_old_slug';
            $excluded_meta_fields[] = '_thumbnail_id';
            $excluded_meta_fields[] = '_product_image_gallery';

            //Syncing the metadata
            foreach ($sourceMetaData as $meta_key => $meta_values) {
                if (in_array($meta_key, $excluded_meta_fields)) {
                    continue;
                }
                foreach ($meta_values as $meta_value) {
                    update_post_meta($targetPostId, $meta_key, $meta_value);
                }
            }
        }
    }
}
