<?php
function hotel26_repeater_register( $wp_customize ) {

	require_once HOTEL_26_PARENT_INC_DIR . '/customizer-repeater/class/customizer-repeater-control.php';
	
}
add_action( 'customize_register', 'hotel26_repeater_register' );

function hotel_26_repeater_sanitize( $input ) {

    $decoded = json_decode( $input, true );

    if ( empty( $decoded ) ) {
        return $input;
    }

    foreach ( $decoded as $i => $item ) {

        foreach ( $item as $key => $value ) {

            switch ( $key ) {

                // ICON
                case 'icon_value':
                case 'icon':
                    $decoded[$i][$key] = sanitize_key( $value );
                    break;

                // URL fields
                case 'link':
                case 'link2':
                case 'link3':
                case 'link4':
                case 'link5':
                case 'link6':
                case 'link7':
                    $decoded[$i][$key] = esc_url_raw( $value );
                    break;

                // NESTED SOCIAL REPEATER
                case 'social_repeater':
                    // Do NOT sanitize as HTML — decode JSON instead
                    $inner = json_decode( html_entity_decode( $value ), true );

                    if ( is_array( $inner ) ) {
                        foreach ( $inner as $k => $inner_item ) {
                            // sanitize nested icon/title/subtitle/link
                            $inner[$k]['icon']     = isset($inner_item['icon']) ? sanitize_key($inner_item['icon']) : '';
                            $inner[$k]['image']     = isset($inner_item['image']) ? sanitize_text_field($inner_item['image']) : '';
                            $inner[$k]['title']    = isset($inner_item['title']) ? sanitize_text_field($inner_item['title']) : '';
                            $inner[$k]['subtitle'] = isset($inner_item['subtitle']) ? sanitize_text_field($inner_item['subtitle']) : '';
                            $inner[$k]['link']     = isset($inner_item['link']) ? esc_url_raw($inner_item['link']) : '';
                            $inner[$k]['id']       = isset($inner_item['id']) ? sanitize_text_field($inner_item['id']) : '';
                        }
                    }

                    $decoded[$i][$key] = wp_json_encode( $inner );
                    break;

                // ALL OTHER TEXT FIELDS
                default:
                    $decoded[$i][$key] = sanitize_text_field( $value );
            }
        }
    }

    return wp_json_encode( $decoded );
}
