<?php

namespace RtmBusiness\PostSync\SyncHandlers;

use RtmBusiness\PostSync\Logger;

class ImageSyncHandler extends AbstractSyncHandler
{

    /**
     * @inheritDoc
     */
    public function handle($sourceBlogId, $sourcePostId, $targetBlogId, $targetPostId): void
    {
        global $rtm_source_postdata;
        //Retrieve the fetched post data from the global variable populated by the 'postsync_before_sync' action
        $sourcePostData = $rtm_source_postdata['sourcePostData'];
        $formatted_source_attachments = $rtm_source_postdata['formatted_source_attachments'];
        $sourceThumbnailId = $rtm_source_postdata['sourceThumbnailId'];


        //Handling of images
        $imageUrlMap = [];
        $galleryImagesMapping = [];
        $targetThumbnailId = null;
        foreach ($formatted_source_attachments as $image_data) {
            $filename = $image_data['filename'];
            $filehash = md5_file($filename);

            $sameHashAttachmentQuery = [
                'post_type' => 'attachment',
                'post_status' => 'inherit',
                'post_parent' => $targetPostId,
                'posts_per_page' => 1,
                'meta_query' => [
                    [
                        'key' => 'filehash',
                        'value' => $filehash,
                        'compare' => '=',
                    ]
                ]
            ];

            //Get all the images on target blog with the same hash as source blog image
            $duplicateImages = get_posts($sameHashAttachmentQuery);


            $filetype = wp_check_filetype(basename($filename));

            // Create a temporary copy because media_handle_sideload() will move the file
            $temp_filename = tempnam(sys_get_temp_dir(), 'tmp');
            copy($filename, $temp_filename);

            $file = [
                'name' => basename($filename),
                'type' => $filetype['type'],
                'tmp_name' => $temp_filename,
                'error' => 0,
                'size' => filesize($filename),
            ];

            if (!file_exists($temp_filename)) {
                continue;
            }

            if (!empty($duplicateImages)) {
                $targetAttachmentId = $duplicateImages[0]->ID;
            } else {
                $targetAttachmentId = media_handle_sideload($file, $targetPostId);
            }

            if (is_wp_error($targetAttachmentId)) {
                // Log error or handle it as you wish
                Logger::error("Attachment Upload Failed", "Uploading the attachment to child blog has failed", "PublishAction", 'sync', [
                    'uploadingTo' => $targetBlogId,
                    'error' => $targetAttachmentId->get_error_messages(),
                    'stackTrace' => $targetAttachmentId->get_error_data(),
                    'file' => $file,
                ]);
            } else {
                if ($image_data['is_gallery'] === true) {
                    $galleryImagesMapping[] = $targetAttachmentId;
                }
                $newImageUrl = wp_get_attachment_url($targetAttachmentId);
                $oldImageUrl = $image_data['url'];
                $imageUrlMap[$oldImageUrl] = $newImageUrl;
                // If the current image is the thumbnail, update the target thumbnail ID.
                if ($sourceThumbnailId === $image_data['attachment']->ID) {
                    $targetThumbnailId = $targetAttachmentId;
                }
                update_post_meta($targetAttachmentId, 'filehash', $filehash);
            }


            // If original file was moved, restore it from the temporary copy
            if (!file_exists($filename)) {
                copy($temp_filename, $filename);
            }

            // Delete the temporary file
            unlink($temp_filename);

        }
        //Update the gallery image ids on the target post
        if ($galleryImagesMapping) {
            update_post_meta($targetPostId, '_product_image_gallery', implode(',', $galleryImagesMapping));
        }
        //Replace reference to old image url with new image url
        $sourcePostData['post_content'] = str_replace(array_keys($imageUrlMap), array_values($imageUrlMap), $sourcePostData['post_content']);
        //Set ID so correct post content gets updated
        $sourcePostData['ID'] = $targetPostId;
        //Update the post content with the new post content which has the new image urls
        wp_update_post($sourcePostData);
        // Syncing the featured image
        if ($sourceThumbnailId && $targetThumbnailId) {
            // Set the featured image on the target post
            set_post_thumbnail($targetPostId, $targetThumbnailId);
        }
    }

}