<?php
/**
 * Tool: insert_image_block
 *
 * Add a single image (already in the WP media library) to a page at a
 * named position. This is the Gutenberg-friendly path: it just inserts
 * a core/image block, leaving every other block alone. No Opus, no
 * full redesign — for users who want to keep using their normal editor
 * and just need a hand placing the photo.
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_insert_image_block($input, $ctx) {
    $page_arg = isset($input['page']) ? $input['page'] : 'current';
    $url      = isset($input['image_url']) ? trim((string) $input['image_url']) : '';
    $position = isset($input['position']) ? trim((string) $input['position']) : '';
    $alt      = isset($input['alt']) ? sanitize_text_field((string) $input['alt']) : '';
    $caption  = isset($input['caption']) ? sanitize_text_field((string) $input['caption']) : '';

    if (!$url || !preg_match('#^https?://#i', $url)) {
        return ['ok' => false, 'message' => 'I need the URL of the image (from the media library) to add 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;

    $blocks = swcp_get_blocks($post);
    $image_block = swcp_build_image_block($url, $alt, $caption);

    list($insert_index, $position_label) = swcp_find_image_insert_index($blocks, $position);

    array_splice($blocks, $insert_index, 0, [$image_block]);

    $saved = swcp_save_blocks($post->ID, $blocks);
    if (!$saved) {
        return ['ok' => false, 'message' => 'Could not save the image into the page.'];
    }

    return [
        'ok'             => true,
        'message'        => 'Added the image to "' . esc_html(get_the_title($post)) . '" ' . $position_label . '. If you have the editor open right now, reload it to see the new image on screen.',
        'page_id'        => $post->ID,
        'view_url'       => swcp_view_url_for($post->ID),
        'edit_url'       => swcp_edit_url_for($post->ID),
        'insert_index'   => $insert_index,
        'position_used'  => $position_label,
    ];
}

function swcp_build_image_block($url, $alt, $caption) {
    $alt     = (string) $alt;
    $caption = (string) $caption;
    $alt_attr  = esc_attr($alt);
    $url_attr  = esc_url($url);
    $img_html  = '<img src="' . $url_attr . '" alt="' . $alt_attr . '"/>';
    $cap_html  = $caption !== '' ? '<figcaption class="wp-element-caption">' . esc_html($caption) . '</figcaption>' : '';
    $figure    = "\n<figure class=\"wp-block-image size-large\">" . $img_html . $cap_html . "</figure>\n";
    return [
        'blockName'    => 'core/image',
        'attrs'        => array_filter([
            'url'      => $url,
            'alt'      => $alt,
            'caption'  => $caption !== '' ? $caption : null,
            'sizeSlug' => 'large',
        ], function ($v) { return $v !== null && $v !== ''; }),
        'innerBlocks'  => [],
        'innerHTML'    => $figure,
        'innerContent' => [$figure],
    ];
}

/**
 * Parse a free-text "position" hint and return [insert_index, label].
 * Supports English + a bit of Dutch:
 *   "" / "bottom" / "end" / "onderaan"        → end of list
 *   "top" / "start" / "bovenaan"              → 0
 *   "after <text>" / "under <text>" / "onder" → after first block whose text contains <text>
 *   "before <text>" / "above <text>" / "boven"/"voor" → before first match
 */
function swcp_find_image_insert_index($blocks, $position) {
    $count = count($blocks);
    $p = strtolower(trim((string) $position));

    if ($p === '' || preg_match('/(bottom|end|onderaan|achteraan|laatst)/u', $p)) {
        return [$count, 'at the end of the page'];
    }
    if (preg_match('/^(top|start|first|bovenaan|begin)/u', $p)) {
        return [0, 'at the top of the page'];
    }

    if (preg_match('/(?:after|under|below|onder|na)\s+(?:the\s+)?(?:heading\s+|section\s+|text\s+|tekst\s+)?["\'“”‘’]?([^"\'“”‘’]+?)["\'“”‘’]?\s*$/u', $p, $m)) {
        $needle = trim($m[1]);
        $idx = swcp_first_block_matching($blocks, $needle);
        if ($idx !== null) return [$idx + 1, 'just after "' . $needle . '"'];
    }
    if (preg_match('/(?:before|above|over|boven|voor)\s+(?:the\s+)?(?:heading\s+|section\s+|text\s+|tekst\s+)?["\'“”‘’]?([^"\'“”‘’]+?)["\'“”‘’]?\s*$/u', $p, $m)) {
        $needle = trim($m[1]);
        $idx = swcp_first_block_matching($blocks, $needle);
        if ($idx !== null) return [$idx, 'just above "' . $needle . '"'];
    }
    // Last resort: try treating the entire hint as a needle to land near
    if ($p !== '') {
        $idx = swcp_first_block_matching($blocks, $p);
        if ($idx !== null) return [$idx + 1, 'just after the section that mentions "' . $p . '"'];
    }
    return [$count, 'at the end of the page'];
}

function swcp_first_block_matching($blocks, $needle) {
    $needle = strtolower(trim((string) $needle));
    if ($needle === '') return null;
    foreach ($blocks as $i => $b) {
        $text = strtolower(swcp_block_text($b));
        if ($text !== '' && strpos($text, $needle) !== false) {
            return $i;
        }
    }
    return null;
}
