<?php

declare(strict_types=1);


if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Podcast RSS Feed Template
 *
 * Supports:
 * - iTunes/Apple Podcasts tags
 * - Podcast 2.0 core tags used by the free podcast feed
 * - Transcript support
 *
 * @package ProRank\SEO
 */

// Get podcast settings from unified option
$settings = get_option('prorank_seo_podcast', []);

// Feed redirect (for migrations). Must run before any output.
$redirect_feed = trim((string) ($settings['podcast_redirect_feed'] ?? ''));
if ('' !== $redirect_feed) {
    wp_redirect(esc_url_raw($redirect_feed), 301);
    exit;
}

$charset = sanitize_text_field( get_option( 'blog_charset' ) );
header( 'Content-Type: application/rss+xml; charset=' . $charset, true );
$more = 1;

echo '<?xml version="1.0" encoding="' . esc_attr( $charset ) . '"?' . '>';

// Get podcast metadata with proper fallbacks
$podcast_title = trim((string) ($settings['podcast_title'] ?? ''));
if ($podcast_title === '') {
    $podcast_title = get_bloginfo('name') . ' Podcast';
}

$podcast_subtitle = trim((string) ($settings['podcast_subtitle'] ?? ''));
if ($podcast_subtitle === '') {
    $podcast_subtitle = trim((string) ($settings['podcast_description'] ?? ''));
}
if ($podcast_subtitle === '') {
    $podcast_subtitle = get_bloginfo('description');
}

$podcast_author = trim((string) ($settings['podcast_author'] ?? ''));
if ($podcast_author === '') {
    $podcast_author = get_bloginfo('name');
}

$podcast_owner_name = trim((string) ($settings['podcast_owner_name'] ?? ''));
if ($podcast_owner_name === '') {
    $podcast_owner_name = $podcast_author;
}

$podcast_owner_email = trim((string) ($settings['podcast_owner_email'] ?? ''));
if ($podcast_owner_email === '') {
    $podcast_owner_email = trim((string) ($settings['podcast_email'] ?? ''));
}
if ($podcast_owner_email === '') {
    $podcast_owner_email = get_option('admin_email');
}

$podcast_category = trim((string) ($settings['podcast_category'] ?? ''));
if ($podcast_category === '') {
    $podcast_category = 'Technology';
}

$podcast_subcategory = trim((string) ($settings['podcast_subcategory'] ?? ''));
$podcast_category_2 = trim((string) ($settings['podcast_category_2'] ?? ''));
$podcast_subcategory_2 = trim((string) ($settings['podcast_subcategory_2'] ?? ''));

// Podcast hosts (for podcast:person at channel level)
$podcast_hosts = $settings['podcast_hosts'] ?? [];
$podcast_explicit = trim((string) ($settings['podcast_explicit'] ?? ''));
if ($podcast_explicit === '') {
    $podcast_explicit = 'no';
}

$podcast_language = trim((string) ($settings['podcast_language'] ?? ''));
if ($podcast_language === '') {
    $podcast_language = str_replace('_', '-', get_locale());
}

$podcast_copyright = trim((string) ($settings['podcast_copyright'] ?? ''));
if ($podcast_copyright === '') {
    $podcast_copyright = '© ' . wp_date('Y') . ' ' . get_bloginfo('name');
}

$podcast_image = trim((string) ($settings['podcast_image'] ?? ''));

$podcast_type = trim((string) ($settings['podcast_type'] ?? ''));
if ($podcast_type === '') {
    $podcast_type = 'episodic';
}

// Feed configuration
$feed_limit = $settings['podcast_feed_limit'] ?? get_option('posts_per_rss', 10);
$enable_itunes = $settings['enable_itunes_tags'] ?? true;
$enable_transcripts = $settings['enable_transcripts'] ?? false;

// Podcast 2.0 settings
$podcast_guid = $settings['podcast_guid'] ?? '';
$podcast_locked = $settings['podcast_locked'] ?? 'no';
$podcast_complete = $settings['podcast_complete'] ?? 'no';
$podcast_block = $settings['podcast_block'] ?? 'no';
$funding_url = $settings['funding_url'] ?? '';
$funding_text = $settings['podcast_funding_text'] ?? 'Support the Show';

// Trailer settings
$trailer_url = $settings['podcast_trailer_url'] ?? '';
$trailer_title = $settings['podcast_trailer_title'] ?? '';
$trailer_pubdate = $settings['podcast_trailer_pubdate'] ?? '';
$trailer_duration = $settings['podcast_trailer_duration'] ?? '';

// Prevent duplicate podcast item tags from the legacy rss2_item hook.
$GLOBALS['prorank_podcast_template_active'] = true;

/**
 * Fires between the xml and rss tags in a feed.
 *
 * @since 4.0.0
 */
do_action('rss_tag_pre', 'rss2');
?>
<rss version="2.0"
    xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:podcast="https://podcastindex.org/namespace/1.0"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
>

<channel>
    <title><?php echo esc_html($podcast_title); ?></title>
    <link><?php bloginfo_rss('url'); ?></link>
    <description><?php echo esc_html($podcast_subtitle); ?></description>
    <lastBuildDate><?php echo esc_html( mysql2date( 'D, d M Y H:i:s +0000', get_lastpostmodified( 'GMT' ), false ) ); ?></lastBuildDate>
    <language><?php echo esc_html($podcast_language); ?></language>
    <copyright><?php echo esc_html($podcast_copyright); ?></copyright>
    <atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" />

    <?php
    /**
     * Fires at the end of the RSS2 Feed Header.
     */
    do_action('rss2_head');
    ?>

    <?php if ($enable_itunes): ?>
    <!-- iTunes/Apple Podcasts specific tags -->
    <itunes:subtitle><?php echo esc_html(wp_trim_words($podcast_subtitle, 50, '...')); ?></itunes:subtitle>
    <itunes:author><?php echo esc_html($podcast_author); ?></itunes:author>
    <itunes:summary><![CDATA[<?php echo esc_html($podcast_subtitle); ?>]]></itunes:summary>
    <itunes:owner>
        <itunes:name><?php echo esc_html($podcast_owner_name); ?></itunes:name>
        <itunes:email><?php echo esc_html($podcast_owner_email); ?></itunes:email>
    </itunes:owner>
    <itunes:explicit><?php echo esc_html($podcast_explicit); ?></itunes:explicit>
    <itunes:type><?php echo esc_html($podcast_type); ?></itunes:type>

    <?php if ($podcast_image): ?>
    <itunes:image href="<?php echo esc_url($podcast_image); ?>" />
    <image>
        <url><?php echo esc_url($podcast_image); ?></url>
        <title><?php echo esc_html($podcast_title); ?></title>
        <link><?php bloginfo_rss('url'); ?></link>
    </image>
    <?php endif; ?>

    <!-- Primary Category -->
    <itunes:category text="<?php echo esc_attr($podcast_category); ?>">
        <?php if ($podcast_subcategory): ?>
        <itunes:category text="<?php echo esc_attr($podcast_subcategory); ?>" />
        <?php endif; ?>
    </itunes:category>

    <?php if ($podcast_category_2): ?>
    <!-- Secondary Category -->
    <itunes:category text="<?php echo esc_attr($podcast_category_2); ?>">
        <?php if ($podcast_subcategory_2): ?>
        <itunes:category text="<?php echo esc_attr($podcast_subcategory_2); ?>" />
        <?php endif; ?>
    </itunes:category>
    <?php endif; ?>

    <?php if ($podcast_complete === 'yes'): ?>
    <itunes:complete>Yes</itunes:complete>
    <?php endif; ?>

    <?php if ($podcast_block === 'yes'): ?>
    <itunes:block>Yes</itunes:block>
    <?php endif; ?>
    <?php endif; // end enable_itunes ?>

    <!-- Podcast 2.0 Channel Tags -->
    <?php if ($podcast_guid): ?>
    <podcast:guid><?php echo esc_html($podcast_guid); ?></podcast:guid>
    <?php endif; ?>

    <?php if ($podcast_locked === 'yes'): ?>
    <podcast:locked owner="<?php echo esc_attr($podcast_owner_email); ?>">yes</podcast:locked>
    <?php else: ?>
    <podcast:locked>no</podcast:locked>
    <?php endif; ?>

    <?php if ($funding_url): ?>
    <podcast:funding url="<?php echo esc_url($funding_url); ?>"><?php echo esc_html($funding_text); ?></podcast:funding>
    <?php endif; ?>

    <?php if ($trailer_url && $trailer_title): ?>
    <!-- Podcast Trailer -->
    <podcast:trailer
        url="<?php echo esc_url($trailer_url); ?>"
        pubdate="<?php echo esc_attr($trailer_pubdate ?: wp_date('r')); ?>"
        <?php if ($trailer_duration): ?>length="<?php echo esc_attr($trailer_duration); ?>"<?php endif; ?>
        type="<?php echo esc_attr(wp_check_filetype($trailer_url)['type'] ?: 'audio/mpeg'); ?>"
    ><?php echo esc_html($trailer_title); ?></podcast:trailer>
    <?php endif; ?>

    <!-- Podcast 2.0 Person Tags (Channel Level Hosts) -->
    <?php
    if (!empty($podcast_hosts) && is_array($podcast_hosts)) {
        foreach ($podcast_hosts as $host) {
            if (empty($host['name'])) continue;
            $role = $host['role'] ?? 'host';
            echo '<podcast:person role="' . esc_attr( $role ) . '"';
            if ( ! empty( $host['url'] ) ) {
                echo ' href="' . esc_url( $host['url'] ) . '"';
            }
            if ( ! empty( $host['img'] ) ) {
                echo ' img="' . esc_url( $host['img'] ) . '"';
            }
            echo '>' . esc_html( $host['name'] ) . '</podcast:person>' . "\n    ";
        }
    }
    ?>

    <?php
    // Query podcast episodes
    $args = [
        'post_type' => 'prorank_podcast',
        'posts_per_page' => intval($feed_limit),
        'orderby' => 'date',
        'order' => 'DESC',
        'post_status' => 'publish',
    ];

    $podcast_query = new WP_Query($args);

    while ($podcast_query->have_posts()) : $podcast_query->the_post();
        // Get episode meta
        $audio_url = get_post_meta(get_the_ID(), '_prorank_podcast_audio_url', true);
        $duration = get_post_meta(get_the_ID(), '_prorank_podcast_duration', true);
        $episode_number = get_post_meta(get_the_ID(), '_prorank_podcast_episode_number', true);
        $season_number = get_post_meta(get_the_ID(), '_prorank_podcast_season_number', true);
        $episode_explicit = get_post_meta(get_the_ID(), '_prorank_podcast_explicit', true);
        $episode_type = get_post_meta(get_the_ID(), '_prorank_podcast_episode_type', true);
        $video_url = get_post_meta(get_the_ID(), '_prorank_podcast_video_url', true);
        $transcript = get_post_meta(get_the_ID(), '_prorank_podcast_transcript', true);
        $chapters = get_post_meta(get_the_ID(), '_prorank_podcast_chapters', true);
        $chapters_url = get_post_meta(get_the_ID(), '_prorank_podcast_chapters_url', true);
        $transcript_url = get_post_meta(get_the_ID(), '_prorank_podcast_transcript_url', true);
        $show_notes = get_post_meta(get_the_ID(), '_prorank_podcast_show_notes', true);
        $episode_description = get_post_meta(get_the_ID(), '_prorank_podcast_description', true);
        $episode_hosts = get_post_meta(get_the_ID(), '_prorank_podcast_hosts', true);
        $episode_guests = get_post_meta(get_the_ID(), '_prorank_podcast_guests', true);
        // Get stable episode GUID (falls back to WordPress GUID if not set)
        $episode_guid = get_post_meta(get_the_ID(), '_prorank_podcast_guid', true);
        if (empty($episode_guid)) {
            $episode_guid = get_the_guid();
        }
    ?>
    <item>
        <title><?php the_title_rss(); ?></title>
        <link><?php the_permalink_rss(); ?></link>
        <guid isPermaLink="false"><?php echo esc_html($episode_guid); ?></guid>
        <pubDate><?php echo esc_html( mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true ), false ) ); ?></pubDate>

        <?php if (get_comments_number() || comments_open()) : ?>
        <comments><?php comments_link_feed(); ?></comments>
        <?php endif; ?>

        <dc:creator><![CDATA[<?php the_author(); ?>]]></dc:creator>

        <?php
        // Get categories (series)
        $series = get_the_terms(get_the_ID(), 'podcast_series');
        if ($series && !is_wp_error($series)) {
            foreach ($series as $term) {
                echo '<category><![CDATA[' . esc_html($term->name) . ']]></category>' . "\n";
            }
        }
        ?>

        <description><![CDATA[<?php
            echo $episode_description
                ? esc_html( $episode_description )
                : esc_html( wp_strip_all_tags( get_the_excerpt() ) );
        ?>]]></description>

        <content:encoded><![CDATA[<?php
        if ($show_notes) {
            echo wp_kses_post($show_notes);
        } else {
            the_content_feed('rss2');
        }
        ?>]]></content:encoded>

        <?php if ($audio_url):
            // Get file info
            $audio_info = wp_check_filetype($audio_url);
            $audio_type = $audio_info['type'] ?: 'audio/mpeg';
            $audio_size = 0; // Size will be 0 if not determinable
        ?>
        <enclosure url="<?php echo esc_url($audio_url); ?>" length="<?php echo esc_attr($audio_size); ?>" type="<?php echo esc_attr($audio_type); ?>" />

        <?php if ($enable_itunes): ?>
        <itunes:duration><?php echo esc_html($duration ?: '00:00:00'); ?></itunes:duration>

        <?php if ($episode_number): ?>
        <itunes:episode><?php echo esc_html($episode_number); ?></itunes:episode>
        <?php endif; ?>

        <?php if ($season_number): ?>
        <itunes:season><?php echo esc_html($season_number); ?></itunes:season>
        <?php endif; ?>

        <itunes:explicit><?php echo $episode_explicit ? 'yes' : 'no'; ?></itunes:explicit>

        <?php if ($episode_type): ?>
        <itunes:episodeType><?php echo esc_html($episode_type); ?></itunes:episodeType>
        <?php endif; ?>

        <itunes:summary><![CDATA[<?php
            echo $episode_description
                ? esc_html( $episode_description )
                : esc_html( wp_strip_all_tags( get_the_excerpt() ) );
        ?>]]></itunes:summary>

        <?php
        $thumbnail_id = get_post_thumbnail_id(get_the_ID());
        if ($thumbnail_id):
            $image_url = wp_get_attachment_url($thumbnail_id);
        ?>
        <itunes:image href="<?php echo esc_url($image_url); ?>" />
        <?php endif; ?>
        <?php endif; // end enable_itunes ?>

        <?php endif; // end audio_url ?>

        <!-- Podcast 2.0 Episode Tags -->
        <?php if ($enable_transcripts && ($transcript_url || $transcript)): ?>
        <podcast:transcript
            url="<?php echo esc_url($transcript_url ?: get_permalink(get_the_ID()) . '#transcript'); ?>"
            type="<?php echo $transcript_url ? 'text/vtt' : 'text/html'; ?>"
        />
        <?php endif; ?>

        <!-- Podcast 2.0 Person Tags (Episode Level) -->
        <?php
        // Output episode hosts
        if (!empty($episode_hosts) && is_array($episode_hosts)) {
            foreach ($episode_hosts as $host) {
                if (empty($host['name'])) continue;
                $role = $host['role'] ?? 'host';
                echo sprintf(
                    '        <podcast:person role="%s"%s%s>%s</podcast:person>' . "\n",
                    esc_attr($role),
                    !empty($host['url']) ? ' href="' . esc_url($host['url']) . '"' : '',
                    !empty($host['img']) ? ' img="' . esc_url($host['img']) . '"' : '',
                    esc_html($host['name'])
                );
            }
        }
        // Output episode guests
        if (!empty($episode_guests) && is_array($episode_guests)) {
            foreach ($episode_guests as $guest) {
                if (empty($guest['name'])) continue;
                $role = $guest['role'] ?? 'guest';
                echo sprintf(
                    '        <podcast:person role="%s"%s%s>%s</podcast:person>' . "\n",
                    esc_attr($role),
                    !empty($guest['url']) ? ' href="' . esc_url($guest['url']) . '"' : '',
                    !empty($guest['img']) ? ' img="' . esc_url($guest['img']) . '"' : '',
                    esc_html($guest['name'])
                );
            }
        }
        ?>

        <?php
        /**
         * Fires at the end of each RSS2 feed item.
         */
        do_action('rss2_item');
        ?>
    </item>
    <?php endwhile; wp_reset_postdata(); ?>
</channel>
</rss>
