<?php
/* ********************
** WORDPRESS GALLERY **
******************** */
add_filter('use_default_gallery_style', '__return_false');
// modify attr
remove_shortcode('gallery');
add_shortcode('gallery', 'my_own_gallery_shortcode');
function my_own_gallery_shortcode($attr)
{
    $attr['itemtag']      = 'div';
    $attr['icontag']      = 'span';
    $attr['captiontag']   = 'figcaption';
    $attr['size']         = 'square';
    $output = gallery_shortcode($attr);
    $output = preg_replace(array('/<br[^>]*>/', '/<span[^>]*>/', '/<\/span>/'), '', $output);
    return $output;
}


function getIDFromString($str)
{
    $id = strtolower(preg_replace('/\s+/', '-', $str));
    $unwanted_array = array(
        'Š' => 'S',
        'š' => 's',
        'Ž' => 'Z',
        'ž' => 'z',
        'À' => 'A',
        'Á' => 'A',
        'Â' => 'A',
        'Ã' => 'A',
        'Ä' => 'A',
        'Å' => 'A',
        'Æ' => 'A',
        'Ç' => 'C',
        'È' => 'E',
        'É' => 'E',
        'Ê' => 'E',
        'Ë' => 'E',
        'Ì' => 'I',
        'Í' => 'I',
        'Î' => 'I',
        'Ï' => 'I',
        'Ñ' => 'N',
        'Ò' => 'O',
        'Ó' => 'O',
        'Ô' => 'O',
        'Õ' => 'O',
        'Ö' => 'O',
        'Ø' => 'O',
        'Ù' => 'U',
        'Ú' => 'U',
        'Û' => 'U',
        'Ü' => 'U',
        'Ý' => 'Y',
        'Þ' => 'B',
        'ß' => 'Ss',
        'à' => 'a',
        'á' => 'a',
        'â' => 'a',
        'ã' => 'a',
        'ä' => 'a',
        'å' => 'a',
        'æ' => 'a',
        'ç' => 'c',
        'è' => 'e',
        'é' => 'e',
        'ê' => 'e',
        'ë' => 'e',
        'ì' => 'i',
        'í' => 'i',
        'î' => 'i',
        'ï' => 'i',
        'ð' => 'o',
        'ñ' => 'n',
        'ò' => 'o',
        'ó' => 'o',
        'ô' => 'o',
        'õ' => 'o',
        'ö' => 'o',
        'ø' => 'o',
        'ù' => 'u',
        'ú' => 'u',
        'û' => 'u',
        'ý' => 'y',
        'þ' => 'b',
        'ÿ' => 'y'
    );
    $id = strtr($id, $unwanted_array);
    $id = preg_replace('/[^a-zA-Z0-9-_\.]/', '', $id);
    return $id;
}


/**
 * Responsive Image Helper Function
 *
 * @param string $image_id the id of the image (from ACF or similar)
 * @param string $image_size the size of the thumbnail image or custom image size
 * @param string $max_width the max width this image will be shown to build the sizes attribute
 */

function acf_responsive_image($image_id, $image_size, $max_width, $srcset = true)
{

    // check the image ID is not blank
    if ($image_id != '') {
        // set the default src image size
        $image_src = wp_get_attachment_image_url($image_id, $image_size);
        // set the srcset with various image sizes
        if ($srcset) {
            $image_srcset = wp_get_attachment_image_srcset($image_id, $image_size);
            echo 'src="' . $image_src . '" srcset="' . $image_srcset . '" sizes="(max-width: ' . $max_width . ') 100vw, ' . $max_width . '"';
        } else {
            echo 'src="' . $image_src . '"';
        }
        // generate the markup for the responsive image
    } else {
        echo 'src="pixel.gif"';
    }
}

/* ***************************
** Yoast TOC localization (single-guide)
** - Replace the visible text of the first and last top-level items with localized strings
** - Done server-side for SEO and accessibility (screen readers, indexing)
*************************** */
/*
add_filter('render_block', function ($block_content, $block) {
    if (!is_singular('guide')) {
        return $block_content;
    }
    if (!isset($block['blockName']) || $block['blockName'] !== 'yoast-seo/table-of-contents') {
        return $block_content;
    }

    if (trim($block_content) === '') {
        return $block_content;
    }

    // Safely parse and modify the HTML
    $intro_label = __('Introduction', 'laurentperrier');
    $concl_label = __('Conclusion', 'laurentperrier');

    $dom = new DOMDocument('1.0', 'UTF-8');
    $prev = libxml_use_internal_errors(true);
    // Prepend XML encoding trick to preserve UTF-8
    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $block_content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();
    libxml_use_internal_errors($prev);

    $xpath = new DOMXPath($dom);
    // Target the Yoast TOC container
    $container = $xpath->query('//*[contains(concat(" ", normalize-space(@class), " "), " yoast-table-of-contents ")]')->item(0);
    if ($container) {
        // Find the first UL within the container (top-level list)
        $ul = $xpath->query('.//ul', $container)->item(0);
        if ($ul) {
            // First LI: prepend a label span before the anchor (outside the link)
            $firstLi = $xpath->query('./li[1]', $ul)->item(0);
            if ($firstLi) {
                // Avoid duplicate insertion if filter runs multiple times
                $existingLabel = $xpath->query('.//span[contains(concat(" ", normalize-space(@class), " "), " toc-label--intro ")]', $firstLi)->item(0);
                if (!$existingLabel) {
                    $firstA = $xpath->query('./a', $firstLi)->item(0);
                    if ($firstA) {
                        $labelSpanIntro = $dom->createElement('span');
                        $labelSpanIntro->setAttribute('class', 'toc-label toc-label--intro');
                        $labelSpanIntro->appendChild($dom->createTextNode($intro_label . ' — '));
                        $firstLi->insertBefore($labelSpanIntro, $firstA);
                    }
                }
            }

            // Last LI: prepend a label span before the anchor (outside the link)
            $lastLi = $xpath->query('./li[last()]', $ul)->item(0);
            if ($lastLi) {
                $existingLabel = $xpath->query('.//span[contains(concat(" ", normalize-space(@class), " "), " toc-label--conclusion ")]', $lastLi)->item(0);
                if (!$existingLabel) {
                    $lastA = $xpath->query('./a', $lastLi)->item(0);
                    if ($lastA) {
                        $labelSpanConcl = $dom->createElement('span');
                        $labelSpanConcl->setAttribute('class', 'toc-label toc-label--conclusion');
                        $labelSpanConcl->appendChild($dom->createTextNode($concl_label . ' — '));
                        $lastLi->insertBefore($labelSpanConcl, $lastA);
                    }
                }
            }
        }
    }

    // Return the modified HTML (DOM was loaded without implied html/body)
    return $dom->saveHTML();
}, 10, 2);
*/


/* ***************************
** SEO: Localized meta for Guides archive (level 1)
** - Overrides Yoast title and description on the main Guides archive
** - Sources values from ACF Options (translatable per language via WPML/Polylang)
** - Appends pagination to title when on page > 1
*************************** */

if (!function_exists('lp_is_guides_archive')) {
    function lp_is_guides_archive()
    {
        return function_exists('is_post_type_archive') && is_post_type_archive('guide');
    }
}

// add_filter('wpseo_title', function ($title) {
//     if (!lp_is_guides_archive()) {
//         return $title;
//     }

//     // Pull localized ACF option (expects per-language values via WPML/Polylang)
//     $custom = get_field('guide_meta_titre', 'option');
//     if (!$custom) {
//         return $title;
//     }

//     $paged = max(1, (int) (get_query_var('paged') ?: get_query_var('page') ?: 1));
//     if ($paged > 1) {
//         $custom .= ' - ' . sprintf('%s %d', __('Page', 'laurentperrier'), $paged);
//     }

//     return wp_strip_all_tags($custom);
// }, 10, 1);

// add_filter('wpseo_metadesc', function ($desc) {
//     if (!lp_is_guides_archive()) {
//         return $desc;
//     }

//     $custom = get_field('guide_meta_description', 'option');
//     if (!$custom) {
//         return $desc;
//     }

//     return wp_strip_all_tags($custom);
// }, 10, 1);

// /* ***************************
// ** SEO: Open Graph for Guides archive
// ** - og:title from ACF option 'guide_meta_titre' (no pagination)
// ** - og:description from ACF option 'guide_meta_description'
// *************************** */

// add_filter('wpseo_opengraph_title', function ($og_title) {
//     if (!lp_is_guides_archive()) {
//         return $og_title;
//     }

//     $custom = get_field('guide_meta_titre', 'option');
//     if (!$custom) {
//         return $og_title;
//     }

//     return wp_strip_all_tags($custom);
// }, 10, 1);

// add_filter('wpseo_opengraph_desc', function ($og_desc) {
//     if (!lp_is_guides_archive()) {
//         return $og_desc;
//     }

//     $custom = get_field('guide_meta_description', 'option');
//     if (!$custom) {
//         return $og_desc;
//     }

//     return wp_strip_all_tags($custom);
// }, 10, 1);


add_filter('wpseo_title', function ($title) {
    if (!is_tax(LP_TAX_GUIDE_CATEGORY)) {
        return $title;
    }

    $term_title = single_term_title('', false);
    if (!$term_title) {
        return $title;
    }

    $paged = max(1, (int) (get_query_var('paged') ?: get_query_var('page') ?: 1));
    if ($paged > 1) {
        $term_title .= ' - ' . sprintf('%s %d', __('Page', 'laurentperrier'), $paged);
    }

    return wp_strip_all_tags($term_title . ' - ' . get_bloginfo('name'));
}, 10, 1);
