<?php
/**
 * Tool: convert_testimonials_to_carousel
 *
 * Find a testimonials section on the page and convert its stacked cards
 * into a horizontal scroll-snap carousel using a pure-CSS pattern (no JS,
 * no theme dependency). Also collapses any duplicate adjacent titles
 * caused by copy-paste.
 *
 * Detection heuristic (v1):
 *   1. Find a core/heading block whose text matches "testimonial",
 *      "review", "what people say", "what clients say", or matches the
 *      caller-provided section_hint.
 *   2. Take that heading + every subsequent block until the next heading
 *      at the same or higher level (smaller number). That's the section.
 *   3. Wrap the testimonial-content blocks (everything after the heading)
 *      in a core/group with className "swcp-testimonial-carousel".
 *   4. Theme-agnostic CSS for the class is enqueued by the plugin.
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_convert_testimonials_to_carousel($input, $ctx) {
    $page_arg = isset($input['page']) ? $input['page'] : 'front';
    $hint     = isset($input['section_hint']) ? strtolower((string) $input['section_hint']) : '';
    $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);
    if (empty($blocks)) {
        return ['ok' => false, 'message' => 'The page "' . esc_html(get_the_title($post)) . '" has no content blocks to convert.'];
    }

    $candidates = ['testimonial', 'testimonials', 'review', 'reviews', 'what people say', 'what clients say', 'kind words', 'getuig', 'recensie'];
    if ($hint) array_unshift($candidates, $hint);

    // Find the heading index that matches.
    $heading_idx = -1;
    $heading_level = 0;
    foreach ($blocks as $i => $b) {
        if (!isset($b['blockName']) || $b['blockName'] !== 'core/heading') continue;
        $text = strtolower(swcp_block_text($b));
        if ($text === '') continue;
        foreach ($candidates as $needle) {
            if ($needle && strpos($text, $needle) !== false) {
                $heading_idx   = $i;
                $heading_level = swcp_heading_level($b);
                break 2;
            }
        }
    }

    if ($heading_idx === -1) {
        return [
            'ok'      => false,
            'message' => 'I could not find a testimonials section on "' . esc_html(get_the_title($post)) . '". The headings I scanned do not match testimonial / review patterns. Try mentioning the exact section title.',
        ];
    }

    // Determine the end of the section: next heading at same or higher level.
    $end_idx = count($blocks);
    for ($j = $heading_idx + 1; $j < count($blocks); $j++) {
        $bn = $blocks[$j]['blockName'] ?? null;
        if ($bn === 'core/heading') {
            $lvl = swcp_heading_level($blocks[$j]);
            if ($lvl > 0 && $lvl <= $heading_level) {
                $end_idx = $j;
                break;
            }
        }
    }

    // Collapse any consecutive duplicate headings inside the section
    // (the copy-paste bug — "What people say" appearing twice).
    $heading_block = $blocks[$heading_idx];
    $heading_text  = strtolower(swcp_block_text($heading_block));
    $body_blocks   = [];
    $duplicates_removed = 0;
    for ($k = $heading_idx + 1; $k < $end_idx; $k++) {
        $bk = $blocks[$k];
        if (
            isset($bk['blockName']) && $bk['blockName'] === 'core/heading'
            && strtolower(swcp_block_text($bk)) === $heading_text
            && swcp_heading_level($bk) === $heading_level
        ) {
            $duplicates_removed++;
            continue;
        }
        $body_blocks[] = $bk;
    }

    if (empty($body_blocks)) {
        return ['ok' => false, 'message' => 'The testimonials heading was found but the section underneath is empty. Nothing to convert.'];
    }

    // Build the carousel wrapper: core/group with the marker className.
    $carousel = swcp_build_group_block('swcp-testimonial-carousel', $body_blocks);

    // Stitch together: keep blocks before heading, keep heading, replace section body with the carousel, then keep the rest.
    $before = array_slice($blocks, 0, $heading_idx + 1);
    $after  = array_slice($blocks, $end_idx);
    $new    = array_merge($before, [$carousel], $after);

    $saved = swcp_save_blocks($post->ID, $new);
    if (!$saved) return ['ok' => false, 'message' => 'Failed to save the converted testimonials section.'];

    $count = count($body_blocks);
    $extra = $duplicates_removed ? ' Also removed ' . $duplicates_removed . ' duplicate heading(s).' : '';

    return [
        'ok'        => true,
        'message'   => 'Converted the testimonials section on "' . esc_html(get_the_title($post)) . '" into a horizontal carousel with ' . $count . ' item(s).' . $extra . ' Visitors will see one testimonial at a time and can scroll through the rest.',
        'page_id'   => $post->ID,
        'view_url'  => swcp_view_url_for($post->ID),
        'edit_url'  => swcp_edit_url_for($post->ID),
    ];
}

/**
 * Build a core/group block wrapping inner blocks with a marker className.
 */
function swcp_build_group_block($class_name, $inner_blocks) {
    $attrs_json = wp_json_encode([
        'className' => $class_name,
        'tagName'   => 'div',
    ]);
    $opening = "<div class=\"wp-block-group " . esc_attr($class_name) . "\">";
    $closing = "</div>";

    return [
        'blockName'    => 'core/group',
        'attrs'        => [
            'className' => $class_name,
            'tagName'   => 'div',
        ],
        'innerBlocks'  => $inner_blocks,
        'innerHTML'    => $opening . $closing,
        'innerContent' => [$opening, null, $closing],
    ];
}
