<?php

/**
 * Manage Podcasts.
 *
 * @link    https://aiopodcasting.com
 * @since   1.0.0
 *
 * @package AiO_Podcast_Studio
 */

// Exit if accessed directly
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * AIOPOD_Admin_Podcasts class.
 *
 * @since 1.0.0
 */
class AIOPOD_Admin_Podcasts {

	/**
	 * Add "All Podcasts" menu.
	 *
	 * @since 1.0.0
	 */
	public function admin_menu() {	
		add_submenu_page(
			'aio-podcast-studio',
			__( 'AiO Podcast Studio - Podcasts', 'aio-podcast-studio' ),
			__( 'All Podcasts', 'aio-podcast-studio' ),
			'manage_aiopod_options',
			'edit.php?post_type=aiopod_podcasts'
		);

		add_submenu_page(
			'aio-podcast-studio',
			__( 'AiO Podcast Studio - Add New Podcast', 'aio-podcast-studio' ),
			__( 'Add New Podcast', 'aio-podcast-studio' ),
			'manage_aiopod_options',
			'aiopod-podcast-new',
			array( $this, 'render_add_new_podcast_page' )
		);
	}

	/**
	 * Render the "Add New Podcast" page content.
	 *
	 * @since 1.0.0
	 */
	public function render_add_new_podcast_page() {
		require_once AIOPOD_PLUGIN_DIR . 'admin/partials/podcasts/podcast-new.php';		
	}

	/**
	 * Move "All Podcasts" submenu under our plugin's main menu.
	 *
	 * @since  1.0.0
	 * @param  string $parent_file The parent file.
	 * @return string $parent_file The parent file.
	 */
	public function parent_file( $parent_file ) {
		global $submenu_file, $current_screen;

		if ( 'aiopod_podcasts' === $current_screen->post_type ) {
			$parent_file = 'aio-podcast-studio';

			if ( 'post' === $current_screen->base && 'add' === $current_screen->action ) {
				// Highlight "Add New Podcast"
				$submenu_file = 'aiopod-podcast-new';
			} else {
				// Highlight "All Podcasts"
				$submenu_file = 'edit.php?post_type=aiopod_podcasts';
			}
		}

		return $parent_file;
	}

	/**
	 * Redirect the "Add New Podcast" button on the CPT list table to the custom podcast-new page.
	 *
	 * Only applies on the podcasts list screen so the "Start a New Podcast" button inside
	 * podcast-new.php (which also calls admin_url with the same path) is not affected.
	 *
	 * @since  1.0.0
	 * @param  string $url  The full admin URL.
	 * @param  string $path The path passed to admin_url().
	 * @return string       Filtered URL.
	 */
	public function filter_admin_url( $url, $path ) {
		if ( 'post-new.php?post_type=aiopod_podcasts' === $path ) {
			$screen = get_current_screen();

			if ( $screen && in_array( $screen->base, array( 'post', 'edit' ), true ) && 'aiopod_podcasts' === $screen->post_type ) {
				return str_replace( 'post-new.php?post_type=aiopod_podcasts', 'admin.php?page=aiopod-podcast-new', $url );
			}
		}

		return $url;
	}

	/**
	 * Register the custom post type "aiopod_podcasts".
	 *
	 * @since 1.0.0
	 */
	public function register_post_type() {			
		$appearance_settings = aiopod_get_option( 'aiopod_appearance_settings' );
		$pages_settings      = aiopod_get_option( 'aiopod_pages_settings' );
		
		$labels = array(
			'name'                  => _x( 'Podcasts', 'Post Type General Name', 'aio-podcast-studio' ),
			'singular_name'         => _x( 'Podcast', 'Post Type Singular Name', 'aio-podcast-studio' ),
			'menu_name'             => __( 'Podcasts', 'aio-podcast-studio' ),
			'name_admin_bar'        => __( 'Podcast', 'aio-podcast-studio' ),
			'archives'              => __( 'Podcast Archives', 'aio-podcast-studio' ),
			'attributes'            => __( 'Podcast Attributes', 'aio-podcast-studio' ),
			'parent_item_colon'     => __( 'Parent Podcast:', 'aio-podcast-studio' ),
			'all_items'             => __( 'All Podcasts', 'aio-podcast-studio' ),
			'add_new_item'          => __( 'Add New Podcast', 'aio-podcast-studio' ),
			'add_new'               => __( 'Add New', 'aio-podcast-studio' ),
			'new_item'              => __( 'New Podcast', 'aio-podcast-studio' ),
			'edit_item'             => __( 'Edit Podcast', 'aio-podcast-studio' ),
			'update_item'           => __( 'Update Podcast', 'aio-podcast-studio' ),
			'view_item'             => __( 'View Podcast', 'aio-podcast-studio' ),
			'view_items'            => __( 'View Podcasts', 'aio-podcast-studio' ),
			'search_items'          => __( 'Search Podcasts', 'aio-podcast-studio' ),
			'not_found'             => __( 'No podcasts found.', 'aio-podcast-studio' ),
			'not_found_in_trash'    => __( 'No podcasts found in trash.', 'aio-podcast-studio' ),
			'featured_image'        => __( 'Featured Image', 'aio-podcast-studio' ),
			'set_featured_image'    => __( 'Set featured image', 'aio-podcast-studio' ),
			'remove_featured_image' => __( 'Remove featured image', 'aio-podcast-studio' ),
			'use_featured_image'    => __( 'Use as featured image', 'aio-podcast-studio' ),
			'insert_into_item'      => __( 'Insert into podcast', 'aio-podcast-studio' ),
			'uploaded_to_this_item' => __( 'Uploaded to this podcast', 'aio-podcast-studio' ),
			'items_list'            => __( 'Podcasts list', 'aio-podcast-studio' ),
			'items_list_navigation' => __( 'Podcasts list navigation', 'aio-podcast-studio' ),
			'filter_items_list'     => __( 'Filter podcasts list', 'aio-podcast-studio' ),
		);
		
		$supports = array( 'title', 'editor', 'excerpt', );			
		if ( ! empty( $appearance_settings['enable_featured_images'] ) ) {
			$supports[] = 'thumbnail';
		}
		
		$args = array(
			'label'                 => __( 'Podcast', 'aio-podcast-studio' ),
			'description'           => __( 'Podcast Description', 'aio-podcast-studio' ),
			'labels'                => $labels,
			'supports'              => $supports,
			'taxonomies'            => array(),
			'hierarchical'          => false,
			'public'                => true,
			'show_ui'               => true,
			'show_in_menu'          => false,
			'show_in_nav_menus'     => true,
			'show_in_admin_bar'     => true,
			'show_in_rest'          => true,
			'can_export'            => true,
			'has_archive'           => true,		
			'exclude_from_search'   => false,
			'publicly_queryable'    => true,
			'capability_type'       => 'aiopod_podcast',
			'map_meta_cap'          => true,
		);

		if ( ! empty( $pages_settings['podcast_archive_page'] ) ) {
			$page_id = (int) $pages_settings['podcast_archive_page'];
			$post    = get_post( $page_id );

			if ( $post && 'publish' === $post->post_status ) {
				$permalink = get_permalink( $page_id );

				if ( $permalink ) {
					$site_url = trailingslashit( home_url() );

					$slug = str_replace( $site_url, '', $permalink );            
					$slug = trim( $slug, '/' );
					$slug = urldecode( $slug );

					$args['rewrite'] = array(
						'slug' => $slug
					);

					$args['has_archive'] = false;
				}
			}
		}
		
		register_post_type( 'aiopod_podcasts', $args );	
	}
	
	/**
	 * Filters the title field placeholder text.
	 *
	 * @since  1.0.0
	 * @param  string $text Placeholder text. Default "Add title".
	 * @return string $text Custom placeholder text.
	 */	
	public function change_default_title( $text ) {	
    	$screen = get_current_screen();
	
    	if ( 'aiopod_podcasts' === $screen->post_type ) {
        	$text = __( 'Enter your show name', 'aio-podcast-studio' );
    	}
	
    	return $text;	
	}

	/**
	 * Adds custom meta fields in the "Publish" meta box.
	 *
	 * @since 1.0.0
	 */
	public function post_submitbox_misc_actions() {	
		global $post, $post_type;
		
		if ( 'aiopod_podcasts' === $post_type ) {
			$post_id = $post->ID;
			require_once AIOPOD_PLUGIN_DIR . 'admin/partials/podcasts/metabox-publish.php';
		}		
	}
	
	/**
	 * Register meta boxes.
	 *
	 * @since 1.0.0
	 */
	public function add_meta_boxes() {
		add_meta_box( 
			'aiopod-metabox-podcast-info', 
			__( 'Podcast Info', 'aio-podcast-studio' ), 
			array( $this, 'display_meta_box_podcast_info' ), 
			'aiopod_podcasts', 
			'normal', 
			'high' 
		);
	}

	/**
	 * Display "Podcast Info" meta box.
	 *
	 * @since 1.0.0
	 * @param WP_Post $post WordPress Post object.
	 */
	public function display_meta_box_podcast_info( $post ) {
		$post_meta = get_post_meta( $post->ID );
		$post_meta = apply_filters( 'aiopod_get_post_meta', $post_meta, $post->ID, '', false, 'aiopod_podcasts' );

		require_once AIOPOD_PLUGIN_DIR . 'admin/partials/podcasts/metabox-podcast-info.php';
	}
	
	/**
	 * Save meta data.
	 *
	 * @since  1.0.0
	 * @param  int     $post_id Post ID.
	 * @param  WP_Post $post    The post object.
	 * @return int     $post_id If the save was successful or not.
	 */
	public function save_meta_data( $post_id, $post ) {	
		if ( ! isset( $_POST['post_type'] ) ) {
        	return $post_id;
    	}
	
		// Check this is the "aiopod_podcasts" custom post type
    	if ( ! $post || 'aiopod_podcasts' !== $post->post_type ) {
        	return $post_id;
    	}
		
		// If this is an autosave, our form has not been submitted, so we don't want to do anything
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        	return $post_id;
		}

		// Check if this is a revision
		if ( wp_is_post_revision( $post_id ) ) {
			return $post_id;
		}
		
		// Check the logged in user has permission to edit this post
    	if ( ! aiopod_current_user_can( 'edit_aiopod_podcast', $post_id ) ) {
        	return $post_id;
    	}
		
		// Check if "aiopod_podcast_metabox_nonce" nonce is set
    	if ( isset( $_POST['aiopod_podcast_metabox_nonce'] ) ) {		
			// Verify that the nonce is valid
    		if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aiopod_podcast_metabox_nonce'] ) ), 'aiopod_save_podcast_metabox' ) ) {			
				// OK to save meta data	
				$appearance_settings  = aiopod_get_option( 'aiopod_appearance_settings' );

				$image = isset( $_POST['image'] ) ? aiopod_sanitize_url( wp_unslash( $_POST['image'] ) ) : '';
				update_post_meta( $post_id, 'image', $image );

				// Resolve the attachment ID from the image URL (the single source of truth).
				$image_id = ! empty( $image ) ? (int) attachment_url_to_postid( $image ) : 0;
				
				if ( ! empty( $appearance_settings['enable_featured_images'] ) ) { // Set featured image
					$set_featured_image = isset( $_POST['set_featured_image'] ) ? (int) wp_unslash( $_POST['set_featured_image'] ) : 0;
					update_post_meta( $post_id, 'set_featured_image', $set_featured_image );

					if ( ! empty( $image ) && ! empty( $set_featured_image ) ) {
						// External image: download a local copy so it can be resized.
						if ( empty( $image_id ) && ! empty( $appearance_settings['download_external_images'] ) ) {
							$image_id = aiopod_create_attachment_from_external_image_url( $image, $post_id );
						}

						if ( ! empty( $image_id ) ) {
							set_post_thumbnail( $post_id, $image_id );
						}
					}
				}

				update_post_meta( $post_id, 'image_id', $image_id );

				$podcast_language = isset( $_POST['podcast_language'] ) ? sanitize_text_field( wp_unslash( $_POST['podcast_language'] ) ) : '';
				update_post_meta( $post_id, 'podcast_language', $podcast_language );

				$podcast_type = isset( $_POST['podcast_type'] ) ? sanitize_text_field( wp_unslash( $_POST['podcast_type'] ) ) : '';
				update_post_meta( $post_id, 'podcast_type', $podcast_type );

				$is_explicit = isset( $_POST['is_explicit'] ) ? (int) wp_unslash( $_POST['is_explicit'] ) : 0;
				update_post_meta( $post_id, 'is_explicit', $is_explicit );

				$is_completed = isset( $_POST['is_completed'] ) ? (int) wp_unslash( $_POST['is_completed'] ) : 0;
				update_post_meta( $post_id, 'is_completed', $is_completed );

				$author_name = isset( $_POST['author_name'] ) ? sanitize_text_field( wp_unslash( $_POST['author_name'] ) ) : '';
				update_post_meta( $post_id, 'author_name', $author_name );

				$author_email = isset( $_POST['author_email'] ) ? sanitize_text_field( wp_unslash( $_POST['author_email'] ) ) : '';
				update_post_meta( $post_id, 'author_email', $author_email );

				$website_url = isset( $_POST['website_url'] ) ? sanitize_text_field( wp_unslash( $_POST['website_url'] ) ) : '';
				update_post_meta( $post_id, 'website_url', $website_url );

				$copyright_text = isset( $_POST['copyright_text'] ) ? sanitize_text_field( wp_unslash( $_POST['copyright_text'] ) ) : '';
				update_post_meta( $post_id, 'copyright_text', $copyright_text );

				delete_post_meta( $post_id, 'participants' );
				wp_set_object_terms( $post_id, array(), 'aiopod_participants' );

				if ( ! empty( $_POST['participant_id'] ) ) {
					$term_ids          = array();
					$participant_ids   = wp_unslash( (array) $_POST['participant_id'] );
					$participant_roles = wp_unslash( (array) $_POST['participant_role'] );

					foreach ( $participant_ids as $key => $value ) {
						$id   = (int) $value;
						$role = sanitize_text_field( $participant_roles[ $key ] );

						if ( empty( $id ) || empty( $role ) ) continue;

						$participant = array(
							'id'   => $id,
							'role' => $role
						);

						add_post_meta( $post_id, 'participants', $participant );
						$term_ids[] = $id;
					}

					if ( ! empty( $term_ids ) ) {
						wp_set_object_terms( $post_id, array_unique( $term_ids ), 'aiopod_participants', false );
					}
				}

				delete_post_meta( $post_id, 'subscribe_buttons' );
				if ( ! empty( $_POST['subscribe_platform'] ) ) {
					$subscribe_platforms = wp_unslash( (array) $_POST['subscribe_platform'] );
					$subscribe_urls      = wp_unslash( (array) $_POST['subscribe_url'] );

					foreach ( $subscribe_platforms as $key => $value ) {
						$platform = sanitize_text_field( $value );
						$url      = aiopod_sanitize_url( $subscribe_urls[ $key ] );

						if ( empty( $platform ) || empty( $url ) ) continue;

						$subscribe_button = array(
							'platform' => $platform,
							'url'      => $url
						);

						add_post_meta( $post_id, 'subscribe_buttons', $subscribe_button );
					}
				}

				$facebook_url = isset( $_POST['facebook_url'] ) ? aiopod_sanitize_url( wp_unslash( $_POST['facebook_url'] ) ) : '';
				update_post_meta( $post_id, 'facebook_url', $facebook_url );

				$twitter_url = isset( $_POST['twitter_url'] ) ? aiopod_sanitize_url( wp_unslash( $_POST['twitter_url'] ) ) : '';
				update_post_meta( $post_id, 'twitter_url', $twitter_url );

				$instagram_url = isset( $_POST['instagram_url'] ) ? aiopod_sanitize_url( wp_unslash( $_POST['instagram_url'] ) ) : '';
				update_post_meta( $post_id, 'instagram_url', $instagram_url );

				$linkedin_url = isset( $_POST['linkedin_url'] ) ? aiopod_sanitize_url( wp_unslash( $_POST['linkedin_url'] ) ) : '';
				update_post_meta( $post_id, 'linkedin_url', $linkedin_url );

				$youtube_url = isset( $_POST['youtube_url'] ) ? aiopod_sanitize_url( wp_unslash( $_POST['youtube_url'] ) ) : '';
				update_post_meta( $post_id, 'youtube_url', $youtube_url );

				$rss_feed_url = isset( $_POST['rss_feed_url'] ) ? aiopod_sanitize_url( wp_unslash( $_POST['rss_feed_url'] ) ) : '';
				update_post_meta( $post_id, 'rss_feed_url', $rss_feed_url );

				$update_existing_content = isset( $_POST['update_existing_content'] ) ? (int) wp_unslash( $_POST['update_existing_content'] ) : 0;
				update_post_meta( $post_id, 'update_existing_content', $update_existing_content );

				$auto_update_episodes = isset( $_POST['auto_update_episodes'] ) ? (int) wp_unslash( $_POST['auto_update_episodes'] ) : 0;
				update_post_meta( $post_id, 'auto_update_episodes', $auto_update_episodes );

				$auto_update_frequency = isset( $_POST['auto_update_frequency'] ) ? (int) wp_unslash( $_POST['auto_update_frequency'] ) : 0;
				update_post_meta( $post_id, 'auto_update_frequency', $auto_update_frequency );

				$new_feed_url = isset( $_POST['new_feed_url'] ) ? aiopod_sanitize_url( wp_unslash( $_POST['new_feed_url'] ) ) : '';
				update_post_meta( $post_id, 'new_feed_url', $new_feed_url );

				$is_blocked = isset( $_POST['is_blocked'] ) ? (int) wp_unslash( $_POST['is_blocked'] ) : 0;
				update_post_meta( $post_id, 'is_blocked', $is_blocked );				

				// Seed sort keys so WP_Query meta_value_num sorts include this post.
				add_post_meta( $post_id, 'total_downloads', 0, true );
				add_post_meta( $post_id, 'total_plays', 0, true );
				add_post_meta( $post_id, 'total_downloads_plays', 0, true );
			}
		}

		return $post_id;
	}

	/**
	 * Add custom filter options.
	 *
	 * @since 1.0.0
	 */
	public function restrict_manage_posts() {	
		global $typenow, $wp_query;
		
		if ( 'aiopod_podcasts' === $typenow ) {
			// Filter by category
        	wp_dropdown_categories( array(
            	'show_option_none'  => __( "All Categories", 'aio-podcast-studio' ),
				'option_none_value' => 0,
            	'taxonomy'          => 'aiopod_categories',
            	'name'              => 'aiopod_categories',
            	'orderby'           => 'name',
            	'selected'          => isset( $wp_query->query['aiopod_categories'] ) ? $wp_query->query['aiopod_categories'] : '',
            	'hierarchical'      => true,
            	'depth'             => 3,
            	'show_count'        => false,
            	'hide_empty'        => false
        	) );	
			
			// Filter by participant
        	wp_dropdown_categories( array(
            	'show_option_none'  => __( "All Participants", 'aio-podcast-studio' ),
				'option_none_value' => 0,
            	'taxonomy'          => 'aiopod_participants',
            	'name'              => 'aiopod_participants',
            	'orderby'           => 'name',
            	'selected'          => isset( $wp_query->query['aiopod_participants'] ) ? $wp_query->query['aiopod_participants'] : '',
            	'hierarchical'      => false,
            	'show_count'        => false,
            	'hide_empty'        => false
        	) );	

			// Filter by explicit, completed, etc
			$filter_by = isset( $_GET['filter_by'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_by'] ) ) : '';

			echo '<select name="filter_by" id="aiopod_filter_by_meta" class="postform">';	
			echo sprintf( '<option value="">%s</option>', esc_html__( 'Filter By', 'aio-podcast-studio' ) );

			$options = array(
				'explicit'  => __( 'Explicit Podcasts', 'aio-podcast-studio' ),
				'completed' => __( 'Completed Podcasts', 'aio-podcast-studio' )
			);
			
			foreach ( $options as $key => $value ) {
				echo sprintf( 
					'<option value="%s"%s>%s</option>', 
					esc_attr( $key ),
					selected( $key, $filter_by, false ), 
					esc_html( $value )
				);
			}
			
			echo '</select>';
    	}	
	}
	
	/**
	 * Parse a query string and filter podcasts accordingly.
	 *
	 * @since 1.0.0
	 * @param WP_Query $query WordPress Query object.
	 */
	public function parse_query( $query ) {	
		global $pagenow, $post_type;
		
		if ( ! $query->is_main_query() ) {
			return;
		}
		
    	if ( 'edit.php' === $pagenow && 'aiopod_podcasts' === $post_type ) {
			// Filter by category
			if ( isset( $query->query_vars['aiopod_categories'] ) && ctype_digit( $query->query_vars['aiopod_categories'] ) && 0 !== (int) $query->query_vars['aiopod_categories'] ) {		
        		$term = get_term_by( 'id', $query->query_vars['aiopod_categories'], 'aiopod_categories' );
        		$query->query_vars['aiopod_categories'] = $term->slug;			
			}

			// Filter by participant
			if ( isset( $query->query_vars['aiopod_participants'] ) && ctype_digit( $query->query_vars['aiopod_participants'] ) && 0 !== (int) $query->query_vars['aiopod_participants'] ) {		
        		$term = get_term_by( 'id', $query->query_vars['aiopod_participants'], 'aiopod_participants' );
        		$query->query_vars['aiopod_participants'] = $term->slug;			
			}

			// Filter by explicit, completed, etc
			$filter_by  = isset( $_GET['filter_by'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_by'] ) ) : '';
			$meta_query = array();

			switch ( $filter_by ) {
				case 'explicit':
					$meta_query[] = array(
						'key'     => 'is_explicit',
						'value'   => 1,
						'compare' => '='
					);
					break;

				case 'completed':
					$meta_query[] = array(
						'key'     => 'is_completed',
						'value'   => 1,
						'compare' => '='
					);
					break;
			}

			if ( ! empty( $meta_query ) ) {
				$query->set( 'meta_query', $meta_query );
			}

			// Sort by total downloads + plays.
			if ( 'statistics' === $query->get( 'orderby' ) ) {
				$query->set( 'meta_key', 'total_downloads_plays' );
				$query->set( 'orderby', 'meta_value_num' );
			}
		}
	}

	/**
	 * Filters the array of row action links.
	 *
	 * @since  1.0.0
	 * @param  array   $actions An array of row action links.
	 * @param  WP_Post $post    The post object.
	 * @return array            Filtered array of row action links.
	 */
	public function row_actions( $actions, $post ) {
		if ( $post->post_type == 'aiopod_podcasts' ) {
			// Copy URL
			$copy_shortcode = sprintf( 
				'<a class="aiopod-copy-url" href="javascript: void(0);" data-url="%s">%s</a>',
				get_permalink( $post->ID ),
				esc_html__( 'Copy URL', 'aio-podcast-studio' )
			);

			$actions['copy-url'] = $copy_shortcode;

			// Copy Shortcode
			$copy_shortcode = sprintf( 
				'<a class="aiopod-copy-shortcode" href="javascript: void(0);" data-shortcode="%s">%s</a>',
				esc_attr( '[aiopod_episodes podcast="' . $post->ID . '"]' ),
				esc_html__( 'Copy Shortcode', 'aio-podcast-studio' )
			);

			$actions['copy-shortcode'] = $copy_shortcode;
		}

		return $actions;
	}
	
	/**
	 * Retrieve the table columns.
	 *
	 * @since  1.0.0
	 * @param  array $columns Array of default table columns.
	 * @return array          Filtered columns array.
	 */
	public function get_columns( $columns ) {
		unset( $columns['taxonomy-aiopod_categories'] );
		unset( $columns['author'] );

		$columns = aiopod_insert_array_after( 'cb', $columns, array( 
			'image' => ''
		));

		$columns = aiopod_insert_array_after( 'title', $columns, array(
			'taxonomy-aiopod_categories' => __( 'Categories', 'aio-podcast-studio' )
		));

		$columns = aiopod_insert_array_after( 'taxonomy-aiopod_participants', $columns, array(
			'episodes'   => __( 'Episodes', 'aio-podcast-studio' ),
			'metadata'   => __( 'Metadata', 'aio-podcast-studio' ),
			'statistics' => __( 'Stats', 'aio-podcast-studio' ),
			'post_id'    => __( 'ID', 'aio-podcast-studio' )
		));
		
		return $columns;		
	}

	/**
	 * Retrieve the sortable table columns.
	 *
	 * @since  1.0.0
	 * @param  array $columns Array of default sortable columns.
	 * @return array          Filtered sortable columns array.
	 */
	public function sortable_columns( $columns ) {
		$columns['post_id']    = 'post_id';
		$columns['statistics'] = 'statistics';
		return $columns;
	}
	
	/**
	 * This function renders the custom columns in the list table.
	 *
	 * @since 1.0.0
	 * @param string $column  The name of the column.
	 * @param string $post_id Post ID.
	 */
	public function custom_column_content( $column, $post_id ) {	
		switch ( $column ) {
			case 'image':
				aiopod_the_image( array( 
					'post_id'     => $post_id,
					'size'        => 'thumbnail',
					'width'       => '75px',
					'alt'         => '',
					'placeholder' => AIOPOD_PLUGIN_PLACEHOLDER_IMAGE_URL
				) );
				break;

			case 'episodes':
				echo aiopod_get_podcast_episodes_count( $post_id );
				break;

			case 'metadata':
				$meta = array();

				// Explicit
				$is_explicit = get_post_meta( $post_id, 'is_explicit', true );

				$meta[] = sprintf( 
					'<span class="aiopod-meta-label">%s:</span> <span class="aiopod-meta-value">%s</span>',
					esc_html__( 'Explicit', 'aio-podcast-studio' ), 
					! empty( $is_explicit ) ? esc_html__( 'Yes', 'aio-podcast-studio' ) : esc_html__( 'No', 'aio-podcast-studio' ) 
				);

				// Completed
				$is_completed = get_post_meta( $post_id, 'is_completed', true );

				$meta[] = sprintf( 
					'<span class="aiopod-meta-label">%s:</span> <span class="aiopod-meta-value">%s</span>', 
					esc_html__( 'Completed', 'aio-podcast-studio' ), 
					! empty( $is_completed ) ? esc_html__( 'Yes', 'aio-podcast-studio' ) : esc_html__( 'No', 'aio-podcast-studio' ) 
				);

				// Print metadata
				echo '<ul class="aiopod-unstyled-list">';
				echo wp_kses_post( '<li>' . implode( '</li><li>', $meta ) . '</li>' );
				echo '</ul>';
				break;

			case 'statistics':
				$downloads = (int) get_post_meta( $post_id, 'total_downloads', true );
				$plays     = (int) get_post_meta( $post_id, 'total_plays', true );

				$meta = array();

				$meta[] = sprintf(
					'<span class="aiopod-meta-label">%s:</span> <span class="aiopod-meta-value">%s</span>',
					esc_html__( 'Downloads', 'aio-podcast-studio' ),
					esc_html( aiopod_format_number( $downloads ) )
				);

				$meta[] = sprintf(
					'<span class="aiopod-meta-label">%s:</span> <span class="aiopod-meta-value">%s</span>',
					esc_html__( 'Plays', 'aio-podcast-studio' ),
					esc_html( aiopod_format_number( $plays ) )
				);

				echo '<ul class="aiopod-unstyled-list">';
				echo '<li>' . implode( '</li><li>', $meta ) . '</li>';
				echo '</ul>';
				break;

			case 'post_id':
				echo absint( $post_id );
				break;
		}
	}
	
	/**
	 * Disable Gutenberg on our custom post type "aiopod_podcasts".
	 *
	 * @since  1.0.0
	 * @param  bool   $use_block_editor Default status.
	 * @param  string $post_type        The post type being checked.
	 * @return bool   $use_block_editor Filtered editor status.
	 */
	public function disable_gutenberg( $use_block_editor, $post_type ) {
		if ( 'aiopod_podcasts' === $post_type ) return false;
		return $use_block_editor;
	}
	
	/**
	 * Delete podcast attachments.
	 *
	 * @since 1.0.0
	 * @param int   $post_id Post ID.
	 */
	public function before_delete_post( $post_id ) {		
		if ( 'aiopod_podcasts' !== get_post_type( $post_id ) ) {
			return;
		}

		$cleanup_settings    = aiopod_get_option( 'aiopod_cleanup_settings' );
		$can_delete_episodes = ! empty( $cleanup_settings['delete_episodes_with_podcast'] );

		if ( $can_delete_episodes ) {
			$episodes = get_children( array(
				'post_parent' => $post_id,
				'post_type'   => 'aiopod_episodes',
				'numberposts' => -1,
				'post_status' => 'any'
			) );

			if ( ! empty( $episodes ) ) {
				// Signal child-episode hooks to skip per-episode work that will be
				// handled in bulk by delete_podcast_stats and delete_podcast_attachments.
				if ( ! defined( 'AIOPOD_DELETING_PODCAST' ) ) {
					define( 'AIOPOD_DELETING_PODCAST', true );
				}

				foreach ( $episodes as $episode ) {
					wp_delete_post( $episode->ID, true );
				}

				// Clear season caches once here rather than N times inside each episode deletion.
				aiopod_clear_season_cache( $post_id );
			}
		}
		  
		aiopod_delete_podcast_attachments( $post_id );	
	}

}
