<?php
/**
 * TABLEAUX :
 * - ajoute <caption> depuis le champ Gutenberg
 * - ajoute scope="col" et scope="row"
 */
add_filter('render_block', function($block_content, $block) {

    if ($block['blockName'] !== 'core/table') {
        return $block_content;
    }

    /*
     * CAPTION
     */
    if (!empty($block['attrs']['tableTitle']) && strpos($block_content, '<caption>') === false) {
        $title = esc_html($block['attrs']['tableTitle']);

        $block_content = preg_replace(
            '/<table([^>]*)>/',
            '<table$1><caption>' . $title . '</caption>',
            $block_content,
            1
        );
    }

    /*
     * SCOPE COL
     */
    $block_content = preg_replace_callback(
        '/<thead>(.*?)<\/thead>/is',
        function($matches) {
            return preg_replace(
                '/<th(?=\s|>)(?![^>]*scope=)/i',
                '<th scope="col"',
                $matches[0]
            );
        },
        $block_content
    );

    /*
     * SCOPE ROW (si la case est cochée)
     */
    if (!empty($block['attrs']['rowHeaders'])) {

        $block_content = preg_replace_callback(
            '/<tbody>(.*?)<\/tbody>/is',
            function($matches) {

                $tbody = $matches[0];

                // Convertit le premier <td> de chaque ligne en <th scope="row">
                $tbody = preg_replace(
                    '/<tr>\s*<td>/',
                    '<tr><th scope="row">',
                    $tbody
                );

                // Ferme correctement la balise
                $tbody = preg_replace(
                    '/<\/td>/',
                    '</th>',
                    $tbody,
                    1
                );

                return $tbody;
            },
            $block_content
        );
    }

    return $block_content;

}, 10, 2);
