<?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();
            $currentBlogId = get_current_blog_id();
            $data = $syncController->getSyncDataWithChildOrParent('post', $currentBlogId, $postId);
            // If sync relationship exists, disconnect this child because it is being permanently deleted
            if ($data !== null) {
                if ($data->parentBlogId === get_current_blog_id()) {
                    $syncController->deleteSyncData($currentBlogId, $postId);
                    Logger::info("PermanentDelete", "Parent post with relation has been permanently deleted", "PermanentDeleteAction", "sync", ['fromBlog' => get_current_blog_id()]);
                } else {
                    $data->removeChild($postId);
                    $syncController->updateSyncData($data);
                    Logger::info("PermanentDelete", "Child post with relation has been trashed and softdeleted from parent successfully", "PermanentDeleteAction", "sync", ['fromBlog' => get_current_blog_id(), 'remainingChildren' => json_encode($data->getLinkedChildren(), true)]);
                }
            }
        }
    }
}
