<?php

/**
 * Purdue Brand functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package purdue-home-theme-child
 * @since 1.0.0
 */
/* eslint-disable */
 require get_stylesheet_directory() . '/inc/template-tags.php';
 require get_stylesheet_directory() . '/inc/acf-field.php';
 require get_stylesheet_directory() . '/inc/blocks.php';
 //require get_stylesheet_directory() . '/inc/form-submission.php';
 /**
 * Add custom post type class names to the list of post types to initialize.
 *
 * To add a new post type, add it in `{theme}/inc/classes/Post_Type` using
 * `RKV\Utilities\Post_Type\Base` as the base class. See the example
 * post type.
 *
 * @param array $post_types List of custom post type classes to initialize.
 *
 * @return array
 */
if ( ! function_exists( 'purdueBrandChild_scripts' ) ) {
	/**
	 * Enqueue scripts and styles.
	 */
	function purdueBrandChild_scripts() {
        $x = require get_stylesheet_directory() . '/build/app.asset.php';

		// include the css file
		wp_enqueue_style( 'purdueThemeChild-style', get_stylesheet_directory_uri() . '/build/app.css',  array(), $x['version'], false);
		// include the javascript file
		wp_enqueue_script( 'purdueThemeChild-mainscript', get_stylesheet_directory_uri() . '/build/app.js', array('jquery'), $x['version'], true );
    }   
}
add_action( 'wp_enqueue_scripts', 'purdueBrandChild_scripts' );

/**
 * Proper way to enqueue scripts and styles.
 */
function rkv_enqueue_tinyslider_css() {
	wp_enqueue_style( 'tinyslider-css', 'https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.3/tiny-slider.css', [], '2.9.3' );
}
add_action( 'wp_enqueue_scripts', 'rkv_enqueue_tinyslider_css' );

function child_admin_scripts() {
    if (is_admin() && isset($_GET['post'])) {
        wp_enqueue_script( 'child-admin-script', get_stylesheet_directory_uri() . '/build/admin.js', array('jquery'), $x['version'],  $in_footer = false);
    }
    wp_enqueue_style( 'child-admin-styles', get_stylesheet_directory_uri() . '/build/admin.css', array(),  $x['version'], false );
}

add_action('admin_enqueue_scripts', 'child_admin_scripts');

function rkv_theme_initialize_post_types( $post_types ) {
	/**
	 * Instantiate custom post types.
	 *
	 * Example:
	 * RKV\Theme\Post_Type\Example
	 */
	$theme_post_types = [
		'RKV\Theme\Post_Type\Podcast',
	];

	$post_types = wp_parse_args( $post_types, $theme_post_types );

	return $post_types;
}
add_filter( 'rkv_utilities_post_types', 'rkv_theme_initialize_post_types' );

require get_stylesheet_directory() . '/inc/video-post.php';
require get_stylesheet_directory() . '/inc/topics-post.php';

//modify permalink for video and topic posts

function na_remove_slug( $post_link, $post, $leavename ) {

    if ('publish' != $post->post_status) {
        return $post_link;
    }
	if ( 'rkv_video' === $post->post_type) {
    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
	}

    return $post_link;
}
add_filter( 'post_type_link', 'na_remove_slug', 10, 3 );
function na_parse_request( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }

    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'post', 'rkv_video', 'rkv_podcast','topic', 'page' ) );
    }
}
add_action( 'pre_get_posts', 'na_parse_request' );
/**
 * Add custom taxonomy class names to the list of taxonomies to initialize.
 *
 * To add a new taxonomy, add it in `{theme}/inc/classes/Taxonomy` using
 * `RKV\Utilities\Taxonomy\Base` as the base class. See the example
 * taxonomy.
 *
 * @param array $taxonomies List of custom taxonomy classes to initialize.
 *
 * @return array
 */
function rkv_theme_initialize_taxonomies( $taxonomies ) {
	/**
	 * Instantiate custom taxonomies.
	 *
	 * Example:
	 * RKV\Theme\Taxonomy\Example
	 */
	$theme_taxonomies = [
		'RKV\Theme\Taxonomy\Themes',
		'RKV\Theme\Taxonomy\Media',
		// 'RKV\Theme\Taxonomy\Featured',
	];

	$taxonomies = wp_parse_args( $taxonomies, $theme_taxonomies );

	return $taxonomies;
}
add_filter( 'rkv_utilities_taxonomies', 'rkv_theme_initialize_taxonomies' );
require get_stylesheet_directory() . '/inc/people-tax.php';


 function rkv_archive_card_image_size( $post_type ) {
	switch ( $post_type ) {
		case 'rkv_podcast':
		case 'podcast':
		case 'rkv_video':
		case 'video':
			$image_size = 'rkv-video-card';
			break;
		default:
			$image_size = 'rkv-1280-720';
			break;
	}

	return $image_size;
}

	/** Provides information about the author of the post
	 *
	 * @param int $author_id The author id.
	 * @return WP_Error/object $author_info An array of author info
	 */
    function rkv_get_the_author_info( $author_id = null ) {

        // If $author_id is not set, and we have the coauthors plugin.
        if ( function_exists( 'get_coauthors' ) && ! isset( $author_id ) ) {
            // Get the coauthors.
            $coauthors = (array) get_coauthors();
            // If there is more than one coauthor, and there is an ID set for the first coauthor.
            if ( count( $coauthors ) >= 1 && isset( $coauthors[0]->ID ) ) {
                // Set $author_id to the first coauthor's ID.
                $coauthor  = $coauthors[0];
                $author_id = $coauthors[0]->ID;
            }
        }
    
        // If there still isn't an $author_id set.
        if ( ! isset( $author_id ) ) {
            $author_id = get_the_author_meta( 'ID' );
        }
    
        if ( empty( $author_id ) ) {
            return new WP_Error( 'no_author_id', __( 'No author id for this post.', 'rkv-theme' ) );
        }
    
        // Our return object.
        $author_info = new stdClass();
    
        $author_info->ID = $author_id;
        if ( function_exists( 'coauthors' ) && isset( $coauthor ) ) {
            $author_info->name = $coauthor->display_name;
            $author_info->href = get_author_posts_url( $coauthor->ID, $coauthor->user_nicename );
			$author_info->img = coauthors_get_avatar( $coauthor, 90 );
			$author_info->desc = get_the_coauthor_meta( 'description' )[ $coauthor->ID ];
        } else {
            $author_info->name = get_the_author_meta( 'display_name', $author_info->ID );
            $author_info->href = get_author_posts_url( $author_info->ID );
			$author_info->img = get_avatar( get_the_author_meta( 'ID' ), 90 );
			$author_info->desc = get_the_author_meta( 'description' );
        }
        $author_info->link_text = sprintf(
        // Translators: the placeholder is for the author display name.
            __( 'Posts by %s.', 'rkv-theme' ),
            $author_info->name
        );
    
        return $author_info;
    }
    
        /**
         * Filter the single archive card excerpt length to 20 words.
         *
         * @param array $args The single co-author link args.
         * @return array $args The modified single co-author link args.
         */
    function rkv_coauthors_posts_link( $args ) {
        $args['class'] = 'entry_author-link';
        return $args;
    }
    add_filter( 'coauthors_posts_link', 'rkv_coauthors_posts_link', 10, 1 );

    function rkv_theme_custom_post_types_in_author_archives( $query ) {
        if ( is_author() && empty( $query->query_vars['suppress_filters'] ) ) {
            $query->set(
                'post_type',
                [
                    'post',
                    'rkv_podcast',
					'video',
					'rkv_video',
                ]
            );
        }
        return $query;
    }
        add_filter( 'pre_get_posts', 'rkv_theme_custom_post_types_in_author_archives' );

//include custom post types

function add_custom_post_types_to_category_archive_and_feed($query) {
    if ($query->is_main_query() && ($query->is_category() || $query->is_feed())) {
        $query->set('post_type', array('post', 'rkv_podcast', 'rkv_video', 'video')); // Add your custom post types here
    }
    return $query;
}
add_action('pre_get_posts', 'add_custom_post_types_to_category_archive_and_feed');

//adjust search result page
function exclude_attachments_from_search($query) {
    if ($query->is_search) {
        $query->set('post_type', array('post', 'rkv_podcast', 'rkv_video', 'video','topic'));
    }
    return $query;
}
add_filter('pre_get_posts', 'exclude_attachments_from_search');
/** Include Image Sizes for Carousel
 * 2:1
 * 4:5
 * Slider Variation 2: 685 x 395 @ 2x
 * Slider Variation 4: 880 x 546 @ 2x
 * Slider Variation 5: 318 x 318 @ 2x
 * updated 03/21/2022: updated rkv-video-card size from 432x392 to 500x454
 * updated 03/31/2022: updated rkv-video-card size from 500x454 to 550x500
 */
function rkv_after_setup_theme_add_image_size() {
	add_image_size( 'rkv-two-to-one', 1920, 1080, true );
	add_image_size( 'rkv-two-to-one--half', 1600, 900, true );
	add_image_size( 'rkv-four-to-five', 800, 1000, true );
	add_image_size( 'rkv-1280-720', 480, 270 );
	add_image_size( 'rkv-video-card', 600, 338, true );
	add_image_size( 'rkv-variation-2-slider', 685, 395, true );
	add_image_size( 'rkv-variation-4-slider', 880, 546, true );
	add_image_size( 'rkv-square-variation-5-slider', 636, 636, true );
}
add_action( 'after_setup_theme', 'rkv_after_setup_theme_add_image_size' );

/** Give the Image Sizes a Proper Readable Name
 *
 * @param string[] $sizes Array of image size labels keyed by their name.
 */
function rkv_custom_image_size_name_choose( $sizes ) {
	return array_merge(
		$sizes,
		array(
			'rkv-two-to-one'                => __( '2:1', 'rkv' ),
			'rkv-four-to-five'              => __( '4:5', 'rkv' ),
			'rkv-square-variation-5-slider' => __( '318px Square', 'rkv' ),

		)
	);
}
add_filter( 'image_size_names_choose', 'rkv_custom_image_size_name_choose' );

/**
 * Find the images in a gallery and return them in a new wrapping <div> to be targeted by Flickity for a carousel
 *
 * @param string $block_content The block content about to be appended.
 * @param array  $block   The full block, including name and attributes.
 *
 * @return string
 */
function rkv_block_wrapper_edit_purdue_gallery( $block_content, $block ) {
	if ( isset( $block['attrs']['className'] ) ) {
		if ( 'core/gallery' === $block['blockName'] && 'purdue_carousel_default' === $block['attrs']['className'] ) {
			// Array for the element wrapper class.
			$wrapper_class = [ 'purdue_carousel_default_wrapper' ];
			if ( isset( $block['attrs']['spacingLevel'] ) ) {
				$wrapper_class[] = 'rkv-bm-' . esc_attr( $block['attrs']['spacingLevel'] );
			}

			$return_array = [];
			preg_match_all( '/<figure[^>]*>(.*?)<\/figure>/mi', $block_content, $matches, PREG_SET_ORDER, 0 );
			foreach ( $matches as $match ) {
				$return_array[] = $match[0];
			}
			$size_attribute = isset( $block['attrs']['sizeSlug'] ) ? 'data-size="' . esc_attr( $block['attrs']['sizeSlug'] ) . '"' : '';

			$wrapper_class_string = implode( ' ', apply_filters( 'rkv_block_editor_purdue_default_carousel_wrapper_class', $wrapper_class ) );

			$image_array_as_string = str_replace( '<img', '<img loading="eager"', implode( '', $return_array ) );
			$output                = "<div class='" . esc_attr( $wrapper_class_string ) . "'>
                <div class='purdue_carousel_default'".$size_attribute.">
                   ". $image_array_as_string . '

                </div>
                <div class="slider-controls">
                <button class="glide__arrow arrow--left tiny-slider-arrow tiny-slider-arrow-previous">prev</button>
                <div class="tiny-slider-navigation glide__bullets">';
                foreach ( $return_array as $i => $layout_post ) :
					if($i == 0):$class = ' tns-nav-active';else:$class = '';endif;
                    $output.='<button class="glide__bullet'.$class.'" type="button"></button>';
                endforeach;
                $output.='</div>
                <button class="glide__arrow arrow--right tiny-slider-arrow tiny-slider-arrow-next">next</button>            
            </div>
            </div>';

			return $output;
		}
	}
	return $block_content;
}
add_filter( 'render_block', 'rkv_block_wrapper_edit_purdue_gallery', 10, 2 );


	/**
	 * Image Block - Full Width Parallax with Caption Slideout
	 *
	 * @param string $block_content The block content about to be appended.
	 * @param array  $block   The full block, including name and attributes.
	 *
	 * @return string
	 */
	function rkv_render_block_full_width_parallax_with_caption_slideout( $block_content, $block ) {
		if ( isset( $block['attrs']['className'] ) ) {
			if ( 'core/image' === $block['blockName'] && false !== strpos( $block['attrs']['className'], 'is-style-full-width-parallax' ) ) {
				$image_id       = $block['attrs']['id'];
				$image_metadata = wp_get_attachment_metadata( $image_id );
				$image_url      = wp_get_attachment_image_url( $image_id, 'full', false );
	
				$image_caption = get_post( $image_id )->post_excerpt;
				if ( ! empty( $image_caption ) ) {
					$image_caption = sprintf( '<figcaption>%s</figcaption>', esc_html( $image_caption ) );
				}
	
				preg_match( '/<figcaption.*?>(.+)<\ /figcaption>/', $block['innerHTML'], $output_array );

    $figcaption = $output_array ? sprintf( '<p>%s</p>', $output_array[1] ) : '';

    $padding_top = ( ( $image_metadata['height'] / $image_metadata['width'] ) * 100 ) . '%';
    return sprintf( "<div class='purdue-parallax-image-wrap'>
        <figure class='purdue-parallax-image alignfull' style='background-image:url(%s); padding-top:%s;'></figure>
        <div class='purdue-parallax-image__caption'>%s</div>
    </div>", esc_url( $image_url ), esc_attr( $padding_top ), $figcaption );
    }
    }
    return $block_content;
    }

    add_filter( 'render_block', 'rkv_render_block_full_width_parallax_with_caption_slideout', 10, 2 );
    /* phpcs:enable */
    /**
    * Add a Featured Video and Featured Video URL field
    *
    * @return void
    */
    function rkv_add_featured_video_fields() {
    $rkv_featured_video_url = new Fieldmanager_Link(
    [
    'name' => 'video_url',
    'description' => __( 'The URL to a video, such as YouTube. If set, this will replace the Featured Image.',
    'rkv-theme' ),
    'label' => __( 'Featured Video URL', 'rkv-theme' ),
    ]
    );
    $rkv_featured_video_file = new Fieldmanager_Media(
    [
    'name' => 'video_file',
    'description' => __( 'A video file that acts as a preview. Used in the background of top banner.', 'rkv-theme' ),
    'mime_type' => 'video',
    'button_label' => __( 'Select a Video', 'rkv-theme' ),
    'modal_button_label' => __( 'Use this Video', 'rkv-theme' ),
    'modal_title' => __( 'Select a Video', 'rkv-theme' ),
    'label' => __( 'Featured Video Preview', 'rkv-theme' ),
    ]
    );
    $custom_featured_video = new Fieldmanager_Group(
    [
    'name' => 'rkv_featured_video',
    'serialize_data' => false,
    'children' => [
    'video_url' => $rkv_featured_video_url,
    'video_file' => $rkv_featured_video_file,
    ],
    ]
    );
    $custom_featured_video->add_meta_box( __( 'Featured Video', 'rkv-theme' ), [ 'post', 'rkv_video' ], 'side' );
    }

     //add_action( 'fm_post_post', 'rkv_add_featured_video_fields' );
    // add_action( 'fm_post_rkv_video', 'rkv_add_featured_video_fields' );

    /**
    * Returns the html of the featured video
    *
    * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
    * @return string
    */
    function rkv_get_featured_video_html( $post = null ) {
    $post = get_post( $post );

    if ( ! $post ) {
    return false;
    }

    if ( rkv_has_featured_video( $post ) ) {
    $rkv_featured_video_url = get_post_meta( $post->ID, 'rkv_featured_video_video_url', true );
    if ( isset( $rkv_featured_video_url ) && ! empty( $rkv_featured_video_url ) && wp_http_validate_url(
    $rkv_featured_video_url ) ) {
    return youtube_lite_embed_oembed_html( '', $rkv_featured_video_url );
    }
    }
    }


    /**
    * Register meta for 'byline_toggle' in Page post type.
    */
    function rkv_register_rkv_byline_toggle_meta() {
    register_post_meta(
    'post',
    'byline_toggle',
    [
    'show_in_rest' => true,
    'single' => true,
    'type' => 'boolean',
    'auth_callback' => function() {
    return current_user_can( 'edit_posts' );
    }
    ]
    );
    }
    add_action( 'init', 'rkv_register_rkv_byline_toggle_meta' );

    //Using field manager to add fields for external link posts

    add_action( 'fm_post_post', function() {
    $fm1 = new Fieldmanager_Checkbox( array(
    'name' => 'hide_on_homepage',
    'label' => 'Hide on homepage?',
    ));
    $fm2 = new Fieldmanager_Checkbox(
    array(
    'name' => 'new_tab',
    'label' => 'Open in a new tab?',
    ));
    $fm = new Fieldmanager_Group(
    [
    'name' => 'external_post',
    'serialize_data' => false,
    'children' => [
    'hide_on_homepage' => $fm1,
    'new_tab' => $fm2,
    ],
    ]
    );
    // $fm->add_meta_box( 'For external post', array( 'post' ), 'side' );
    } );
    /**
    * Returns whether the featured video field is set.
    *
    * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
    * @return bool
    */
    function rkv_has_featured_video( $post = null ) {
    $post = get_post( $post );

    if ( ! $post ) {
    return false;
    }

    $rkv_featured_video_url = get_post_meta( $post->ID, 'rkv_featured_video_video_url', true );

    if ( isset( $rkv_featured_video_url ) && ! empty( $rkv_featured_video_url ) && wp_http_validate_url(
    $rkv_featured_video_url ) ) {
    return true;
    }
    return false;
    }

    /**
    * Returns whether the featured video thumbnail file field is set.
    *
    * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
    * @return bool
    */
    function rkv_has_featured_video_thumbnail( $post = null ) {
    $post = get_post( $post );

    if ( ! $post ) {
    return false;
    }

    $rkv_featured_video_file = get_post_meta( $post->ID, 'rkv_featured_video_video_file', true );
    if ( isset( $rkv_featured_video_file ) && ! empty( $rkv_featured_video_file ) && intval( $rkv_featured_video_file )
    ) {
    return true;
    }
    return false;
    }
    /**
    * Echos the featured video file's <video> html
        *
        * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
        * @return void
        */
        function rkv_the_featured_video_file_html( $post = null ) {
        global $allowedtags;
        $featured_video_allowedtags = $allowedtags;
        $featured_video_allowedtags['video'] = array(
        'width' => true,
        'height' => true,
        'preload' => true,
        );
        $featured_video_allowedtags['source'] = array(
        'src' => true,
        'type' => true,
        );

        echo wp_kses( rkv_get_featured_video_file_html( $post ), $featured_video_allowedtags );
        }


        /**
        * Returns the featured video file's <video> html
            *
            * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
            * @return string/bool
            */
            function rkv_get_featured_video_file_html( $post = null ) {
            $post = get_post( $post );

            if ( ! $post ) {
            return false;
            }

            $video_file_url = wp_get_attachment_url( rkv_get_featured_video_file_id( $post ) );
            if ( false !== $video_file_url && wp_http_validate_url( $video_file_url ) ) {
            return sprintf( '<video class="rkv-thumbnail-video" preload="metadata">
                <source src="%s#t=0.5" />
            </video>', esc_url( $video_file_url ) );
            }
            }

            /**
            * Returns the ID for a featured video, if set.
            *
            * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
            * @return int/bool
            */
            function rkv_get_featured_video_file_id( $post = null ) {
            $post = get_post( $post );


            $rkv_featured_video_file = get_post_meta( $post->ID, 'rkv_featured_video_video_file', true );
            if ( isset( $rkv_featured_video_file ) && intval( $rkv_featured_video_file ) ) {
            return $rkv_featured_video_file;
            }
            return false;
            }
            /**
            * Returns human readable duration for a featured video.
            * From a previously saved meta_key for `rkv_featured_video_duration`
            *
            * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
            * @return string/bool on Failuire.
            */
            function rkv_get_featured_video_readable_duration( $post = null ) {
            $post = get_post( $post );

            if ( ! $post ) {
            return false;
            }

            if ( get_post_meta( $post->ID, 'rkv_featured_video_duration', true ) ) {
            $iso_duration = get_post_meta( $post->ID, 'rkv_featured_video_duration', true );
            $interval = new DateInterval( $iso_duration );
            return $interval->format( '%i:%s' );
            }
            }


            /**
            * Returns human readable duration for an attachment.
            *
            * @param int $attachment_id The attachment ID.
            * @return string/bool on Failuire.
            */
            function rkv_get_attachment_readable_duration( $attachment_id ) {
            $meta = wp_get_attachment_metadata( $attachment_id );
            if ( $meta ) {
            if ( isset( $meta['length_formatted'] ) ) {
            $file_length = $meta['length_formatted'];
            $file_length_human_readable = human_readable_duration( $meta['length_formatted'] );
            return $file_length;
            }
            }
            return false;
            }

            /**
            * Adds a classname to the post_class for the media_type
            *
            * @param string[] $classes An array of post class names.
            * @param string[] $class An array of additional class names added to the post.
            * @param int $post_id The post ID.
            */
            function rkv_add_media_type_post_class( $classes, $class, $post_id ) {
            if ( is_admin() ) { // only on the Frontend.
            return $classes;
            }

            if ( $post_id ) {
            $media_terms = wp_get_post_terms(
            $post_id,
            'rkv-media',
            [
            'fields' => 'slugs',
            'number' => 1,
            'slug' => 'video',
            ]
            );
            if ( ! is_wp_error( $media_terms ) && isset( $media_terms[0] ) ) {
            $media_term = $media_terms[0];
            // If there is a media term set, that is going to be our post type.
            $classes[] = sanitize_title_with_dashes( "has-media-tax-$media_term" );
            }
            }

            return $classes;
            }
            add_filter( 'post_class', 'rkv_add_media_type_post_class', 10, 3 );

            function custom_acf_set_postType_tag_default_value($value, $post_id, $field) {
            // Check if it's the correct ACF field and post type
            if ($field['key'] === 'field_650de7e74a440') {
            // Set your new default value here
            $value = "Yes";
            }

            return $value;
            }

            add_filter('acf/load_value', 'custom_acf_set_postType_tag_default_value', 10, 3);

            //add theme feed
            add_action('init', 'themeRSS');
            function themeRSS(){
            add_feed('theme', 'themeRSSFunc');
            }

            function add_query_vars_filter( $vars ){
            $vars[] = "theme_term";
            return $vars;
            }
            add_filter( 'query_vars', 'add_query_vars_filter' );
    function themeRSSFunc(){
                header('Content-Type: '.feed_content_type('rss-http').'; charset='.get_option('blog_charset'), true);
                // prettier-ignore
                echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>';
    ?>
                <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"
                    xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/"
                    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
                    xmlns:slash="http://purl.org/rss/1.0/modules/slash/" <?php do_action('rss2_ns'); ?>>
                    <channel>
                        <title>My News - Feed</title>
                        <atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" />
                        <link><?php bloginfo_rss('url') ?></link>
                        <description><?php bloginfo_rss('description') ?></description>
                        <lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?>
                        </lastBuildDate>
                        <language><?php echo get_option('rss_language'); ?></language>
                        <sy:updatePeriod><?php echo apply_filters( 'rss_update_period', 'hourly' ); ?></sy:updatePeriod>
                        <sy:updateFrequency><?php echo apply_filters( 'rss_update_frequency', '1' ); ?></sy:updateFrequency>
                        <?php do_action('rss2_head'); ?>
                        <?php 
                    $postType = get_query_var('post_type')?get_query_var('post_type'):"any";
                    $query = array(
                        'post_type' => $postType,
                    );
                    $tax = get_query_var('theme_term');
                    if($tax) {
                        $query['tax_query'] = array(
                            array (
                                'taxonomy' => '_theme',
                                'field' => 'slug',
                                'terms' => $tax,
                            )
                        );
                    }
                    $cat = get_query_var('category');
                    if($cat) {
                        $cat_query =array (
                                'taxonomy' => 'category',
                                'field' => 'slug',
                                'terms' => $cat,
                        );
                        array_push($query_args['tax_query'], $cat_query);
                    }
                    $the_query = new WP_Query($query);
     
                    while ( $the_query->have_posts() ) :
                        $the_query->the_post();
                        $post_id = get_the_ID();
                        $category_object = get_the_category($post_id);
                        $category_name = $category_object[0]->name;
                    ?>
                        <item>
                            <title><?php the_title_rss(); ?></title>
                            <link><?php the_permalink_rss(); ?></link>
                            <pubDate>
                                <?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?>
                            </pubDate>
                            <dc:creator><?php the_author(); ?></dc:creator>
                            <guid isPermaLink="false"><?php the_guid(); ?></guid>
                            <description>
                                <![CDATA[<?php the_excerpt_rss() ?>]]>
                            </description>
                            <category><?php echo $category_name; ?></category>
                            <content:encoded>
                                <![CDATA[<?php the_excerpt_rss() ?>]]>
                            </content:encoded>
                            <?php rss_enclosure(); ?>
                            <?php do_action('rss2_item'); ?>
                        </item>
                        <?php
                    endwhile;
                ?>
                    </channel>
                </rss>
                <?php }
function add_theme_to_rss_feed() {
    global $post;

    $terms = get_the_terms($post->ID, '_theme');

    if ($terms) {
        foreach ($terms as $term) {
            echo "<mycustomfields:theme>{$term->name}</mycustomfields:theme>\n";
        }
    }
}
add_action('rss2_item', 'add_theme_to_rss_feed');


//Caluculate Post reading time

function calc_reading_time($post_id) {
    // Fetch the post content
    $content = get_post_field('post_content', $post_id);

    // Calculate the word count
    $word_count = str_word_count(strip_tags($content));

    // Define the average reading speed (words per minute)
    $reading_speed = 189;

    // Calculate the estimated reading time in minutes
    $reading_time = round($word_count / $reading_speed, 0, PHP_ROUND_HALF_UP);

    return $reading_time;
}

add_filter( 'gform_notification_4', 'update_notification', 10, 3 );
function update_notification( $notification, $form, $entry ) {

    $url = rgar( $entry, '3' );  
    $url = strtok($url, "?");
    $notification['message'] .= '<p>Enjoy this story from Purdue University: <a href="'.$url.'?utm_source=tpp-read-later&utm_medium=email">{embed_post:post_title}</a></p>';

 return $notification;
}

add_filter( 'ppp_nonce_life', 'my_nonce_life' );
function my_nonce_life() {
    return 365 * DAY_IN_SECONDS;
}


$GLOBALS['render_hero'] = [];

add_filter( 'render_block_data', function( $block ) {

    // Match any blockName that contains "storytelling-hero".
    if ( empty( $block['blockName'] ) || false === strpos( $block['blockName'], 'storytelling-hero' ) ) {
        return $block;
    }
    $GLOBALS['render_hero'][] = $block['attrs'] ?? [];

    return $block; // MUST return block intact
}, 10 );




function get_storytelling_hero_attrs_from_post( $post_id = null ) {
    $post = get_post( $post_id );
    if ( ! $post ) {
        return null;
    }

    $blocks = parse_blocks( $post->post_content );
    $finder = function( $blocks ) use ( & $finder ) {
        foreach ( $blocks as $block ) {
            if ( isset( $block['blockName'] ) && is_string( $block['blockName'] ) && false !== strpos( $block['blockName'], 'storytelling-hero' ) ) {
                return $block['attrs'] ?? null;
            }
            if ( ! empty( $block['innerBlocks'] ) ) {
                $found = $finder( $block['innerBlocks'] );
                if ( $found ) {
                    return $found;
                }
            }
        }
        return null;
    };

    return $finder( $blocks );
}