<?php
/**
 * Tool: delete_block
 *
 * Remove a block (and its innerBlocks) from a page. Locator targets
 * the block to remove. The before-snapshot is shipped back so the rail
 * can offer a one-click Undo.
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_delete_block($input, $ctx) {
    $page_arg = isset($input['page']) ? $input['page'] : 'current';
    $locator  = isset($input['locator']) && is_array($input['locator']) ? $input['locator'] : null;

    if (!$locator) {
        return ['ok' => false, 'message' => 'I need to know which block to remove. Click the block in the page or describe it.'];
    }

    $resolved = swcp_resolve_or_error($page_arg, $ctx['post_id'] ?? 0);
    if (is_array($resolved) && isset($resolved['ok']) && !$resolved['ok']) return $resolved;
    $post = $resolved;

    $before_html = (string) $post->post_content;
    $blocks      = swcp_get_blocks($post);

    $found = swcp_find_block_by_locator($blocks, $locator);
    if (!$found) {
        return swcp_locator_ambiguous_or_missing($blocks, $locator) + ['page_id' => (int) $post->ID];
    }

    $name    = isset($found['block']['blockName']) ? (string) $found['block']['blockName'] : 'block';
    $preview = swcp_locator_preview_for($found['block']);

    $ok = swcp_mutate_at_path($blocks, $found['path'], function ($block) {
        return '__delete__';
    });

    if (!$ok) {
        return ['ok' => false, 'message' => 'Found the block but failed to remove it.'];
    }

    $saved = swcp_save_blocks($post->ID, $blocks);
    if (!$saved) {
        return ['ok' => false, 'message' => 'Found the block but failed to save the page.'];
    }

    return [
        'ok'               => true,
        'page_id'          => (int) $post->ID,
        'message'          => 'Removed the ' . $name . ' block (' . $preview . ') from "' . esc_html(get_the_title($post)) . '".',
        'view_url'         => swcp_view_url_for($post->ID),
        'edit_url'         => swcp_edit_url_for($post->ID),
        'removed_block'    => $name,
        'requires_refresh' => true,
        'undo' => [
            'tool'  => 'restore_page_version',
            'input' => ['post_id' => (int) $post->ID, 'snapshot_html' => $before_html],
            'label' => 'Undo',
        ],
    ];
}
