<?php
/**
 * Retriever Functionality
 *
 * @package Nisje
 */

declare( strict_types = 1 );
defined( 'ABSPATH' ) || die( 'Shame on you' );

add_filter( 'the_content', function( string $content ) : string {
	$post = get_post();

	ob_start();

	if ( $post instanceof \WP_Post ) {
		if ( in_array( $post->post_type, [ 'dekode-news', 'nisje-news-group' ], true ) ) {
			while ( has_sub_field( 'flexible_content' ) ) {
				if ( 'lead_text' === get_row_layout() ) {
					printf(
						'<p class="lead">%s</p>',
						esc_html( get_sub_field( 'content' ) )
					);
				} elseif ( 'image_full_pluss' === get_row_layout() ) {
					$image = get_sub_field( 'image' );
					if ( $image ) {
						printf(
							'<img src="%s" alt="">',
							esc_url( $image['url'] )
						);
					}
				} elseif ( 'image_full' === get_row_layout() ) {
					$image = get_sub_field( 'image' );
					if ( $image ) {
						printf(
							'<img src="%s" alt="">',
							esc_url( $image['url'] )
						);
					}
				} elseif ( 'text_editor' === get_row_layout() ) {
					echo wp_kses_post( get_sub_field( 'content' ) );
				} elseif ( 'blockquote' === get_row_layout() ) {
					printf(
						'<blockquote><p>%1$d</p><footer><cite>%2$d</cite></footer></blockquote>',
						esc_html( get_sub_field( 'quote' ) ),
						esc_html( get_sub_field( 'cite' ) )
					);
				} elseif ( 'video' === get_row_layout() ) {
					$oembed = wp_oembed_get( get_sub_field( 'video_link' ) );
					if ( $oembed ) {
						echo $oembed; // phpcs:ignore
					}
				}
			}
		} elseif ( 'dekode-wiki' === $post->post_type ) {
			$wiki_content = get_post_meta( get_the_ID(), 'content', true );
			if ( $wiki_content ) {
				echo wp_kses_post( $wiki_content );
			}

			$file_holder = '';
			if ( have_rows( 'repeater_file_uploads' ) ) {
				echo '<h3>Files</h3>';
				while ( have_rows( 'repeater_file_uploads' ) ) {
					the_row();

					/* phpcs:ignore
					File description
					if ( get_sub_field( 'file_description' ) ) {
						$file_holder .= '<p>' . esc_html(get_sub_field('file_description')) . '</p>';
					}
					*/

					if ( have_rows( 'repeater_files' ) ) {
						$file_holder .= '<ul>';

						while ( have_rows( 'repeater_files' ) ) {
							the_row();
							$file = get_sub_field( 'file' );
							if ( $file ) {
								$file_holder .= '<li><a href="' . esc_url( $file['url'] ) . '" target="_blank" class="' . esc_attr( get_sub_field( 'file_type' ) ) . '" title="Last ned ' . get_sub_field( 'file_type' ) . '-versjon av filen">' . $file['title'] . '</a></li>';
							}
						}

						$file_holder .= '</ul>';
					}
				}
			}

			echo wp_kses_post( $file_holder );

			$link_holder = '';
			if ( have_rows( 'repeater_external_links' ) ) {
				$link_holder .= '<h3>Links</h3><ul>';
				while ( have_rows( 'repeater_external_links' ) ) {
					the_row();

					if ( get_sub_field( 'link_description' ) && get_sub_field( 'link' ) ) {
						$link_holder .= '<li><a href="' . esc_url( get_sub_field( 'link' ) ) . '" target="_blank">' . esc_html( get_sub_field( 'link_description' ) ) . '</a></li>';
					}
				}

				$link_holder .= '</ul>';
			}

			echo wp_kses_post( $link_holder );
		}
	}

	$new_content = ob_get_clean();

	return $content . $new_content;
} );

/**
 * Ham to anon.
 *
 * @param string $display_name Anonymous Name.
 * @return string Anonymous Name.
 */
function nisje_nb_deactivate_anonymous_name( $display_name ) {
	return 'Former user (inactive)';
}
add_filter( 'nisje_deactivate_user_anonymous_name', 'nisje_nb_deactivate_anonymous_name' );

/**
 * Remove fonts if light version
 */
function grieg_remove_fonts() {
	if ( is_user_logged_in() ) {
		if ( function_exists( 'bp_get_profile_field_data' ) ) {
			$light_version_field = bp_get_profile_field_data( [
				'field'   => 'Light version',
				'user_id' => get_current_user_id(),
			] );

			// Remove font if light version.
			if ( 'Yes' === $light_version_field ) {
				wp_deregister_style( 'nisje-font' );
			}
		}
	}
}
add_action( 'wp_enqueue_scripts', 'grieg_remove_fonts', 99 );

/**
 * Parse request to allow bypassing posts for RSS feed.
 */
function grieg_request_handle() {
	$rss  = filter_input( INPUT_GET, 'key', FILTER_SANITIZE_STRING );
	$user = absint( filter_input( INPUT_GET, 'user', FILTER_SANITIZE_NUMBER_INT ) );

	$skey = filter_input( INPUT_GET, 'skey', FILTER_SANITIZE_STRING );

	if ( $rss ) {
		if ( 'grieg_allowed' !== $rss || ! $user ) {
			wp_die( '404 - Not found' );
		} else {
			$retriever = filter_input( INPUT_GET, 'retriever', FILTER_VALIDATE_BOOLEAN );
			$user      = absint( filter_input( INPUT_GET, 'user', FILTER_SANITIZE_NUMBER_INT ) );

			wp_clear_auth_cookie();
			wp_set_current_user( $user );
			wp_set_auth_cookie( $user, true, false );

			$user_skey = get_user_meta( $user, 'nisje_rss_users_security_key', true );
			if ( ! $user_skey || empty( $user_skey ) || $user_skey !== $skey ) {
				wp_die( '401 - Wrong key' );
			}

			$groups    = [ 0 ];
			$group_ids = groups_get_user_groups( $user );
			foreach ( $group_ids['groups'] as $group_id ) {
				$groups[] = $group_id;
			}

			/**
			 * Filters allowed post types.
			 *
			 * @param array $post_types Allowd post types.
			 */
			$post_type = apply_filters( 'nisje_feed_post_types', [] );

			if ( $retriever ) {
				$post_type[] = 'nisje-retriever';
			}

			query_posts( [ // phpcs:ignore
				'paged'           => 1,
				'posts_per_page'  => 20,
				'post_type'       => $post_type,
				'post_status'     => 'publish',
				'post_parent__in' => $groups,
			] );

			remove_action( 'rss2_head', 'rss2_site_icon' );

			header( 'Content-Type: ' . feed_content_type( 'rss-http' ) . '; charset=' . esc_attr( get_option( 'blog_charset' ) ), true );
			echo '<?xml version="1.0" encoding="' . esc_attr( 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><?php bloginfo_rss( 'name' ); ?> - Feed</title>
					<atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" />
					<link><?php echo esc_html( get_bloginfo_rss( 'url' ) ); ?></link>
					<description><?php echo esc_html( bloginfo_rss( 'description' ) ); ?></description>
					<lastBuildDate><?php echo esc_html( mysql2date( 'D, d M Y H:i:s +0000', get_lastpostmodified( 'GMT' ), false ) ); ?></lastBuildDate>
					<language>en-US</language>
					<sy:updatePeriod><?php echo esc_html( apply_filters( 'rss_update_period', 'hourly' ) ); ?></sy:updatePeriod>
					<sy:updateFrequency><?php echo esc_html( apply_filters( 'rss_update_frequency', '1' ) ); ?></sy:updateFrequency>

					<?php do_action( 'rss2_head' ); ?>

					<?php
					while ( have_posts() ) :
						the_post();
						?>
						<item>
							<?php if ( 'nisje-user-content' === get_post_type() || empty( get_the_title_rss() ) ) : ?>
								<title>Wall post from <?php the_author(); ?></title>
							<?php else : ?>
								<title><?php the_title_rss(); ?></title>
							<?php endif; ?>
							<link><?php the_permalink_rss(); ?></link>
							<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>
							<dc:creator><?php the_author(); ?></dc:creator>
							<guid isPermaLink="false"><?php the_guid(); ?></guid>
							<?php
							add_filter( 'the_excerpt_rss', 'grieg_optimize_rss_content_output' );
							add_filter( 'the_content_feed', 'grieg_optimize_rss_content_output' );

							$content = '';

							$content = get_the_content_feed( 'rss2' );
							$content = str_replace( 'src="/content/', 'src="https://135.grieg.com/content/', $content );
							?>

							<description><![CDATA[<?php echo $content; ?>]]></description><?php // phpcs:ignore ?>
							<content:encoded><![CDATA[<?php echo $content; ?>]]></content:encoded><?php // phpcs:ignore ?>
							<?php
							remove_filter( 'the_excerpt_rss', 'grieg_optimize_rss_content_output' );
							remove_filter( 'the_content_feed', 'grieg_optimize_rss_content_output' );
							?>
							<?php rss_enclosure(); ?>

							<?php do_action( 'rss2_item' ); ?>
						</item>
					<?php endwhile; ?>
				</channel>
			</rss>

			<?php
			die();
		}
	}
}
add_action( 'parse_request', 'grieg_request_handle' );

/**
 * Content filter to allow images in feed.
 *
 * @param string $content Content.
 */
function grieg_optimize_rss_content_output( $content ) {
	global $post;

	if ( has_post_thumbnail( $post->ID ) ) {
		$content = '<img src="' . wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) ) . '">' . $content;
	}

	if ( 'nisje-user-content' === $post->post_type ) {
		$images = get_post_meta( $post->ID, 'nisje-images', true );
		if ( ! empty( $images ) && is_array( $images ) ) {
			foreach ( $images as $image ) {
				$image_data = nisje_populate_image_data( $image );
				if ( is_array( $image_data ) && isset( $image_data['url'] ) ) {
					$content = '<img src="' . esc_url( $image_data['url'] ) . '">' . $content;
				}
			}
		}
	}

	return $content;
}

/**
 * Add settings page
 */
function grieg_register_settings_field_group() {
	require 'acf/field-groups/acf-field-group-rss-user.php';
}
add_action( 'nisje_settings_register_field_groups', 'grieg_register_settings_field_group' );
