<?php

namespace RtmBusiness\PostSync\Action;

use RtmBusiness\PostSync\Logger;
use RtmBusiness\PostSync\SyncController;

/**
 * This action is triggered on permanent delete of a post
 */
class PermanentDeleteAction implements SyncAction
{

    /**
     * @inheritDoc
     */
    public function execute(int $postId)
    {
        // Check if the post is being permanently deleted
        if (!wp_is_post_revision($postId) && !wp_is_post_autosave($postId)) {
            if (!current_user_can("postsync_can_permdelete")) {
                Logger::warning("PermanentDelete", "User doesn't have permission to permanently delete", "PermanentDeleteAction", "sync", ['fromBlog' => get_current_blog_id()]);
                return;
            }
            
            $syncController = SyncController::instance();
            $data = $syncController->getSyncDataWithChild('post', get_current_blog_id(), $postId);
            // If sync relationship exists, disconnect this child because it is being permanently deleted
            if ($data) {
                $data->removeChild($postId);
                $syncController->updateSyncData($data);
                Logger::info("Disconnected from parent", "Child site disconnected from parent successfully", "PermanentDeleteAction", "sync", ['fromBlog' => get_current_blog_id(), 'remainingChildren' => json_encode($data->getLinkedChildren(), true)]);
            }
        }
    }
}
