<?php

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

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

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

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

		add_submenu_page(
			'aio-podcast-studio',
			__( 'AiO Podcast Studio - Add New Episode', 'aio-podcast-studio' ),
			__( 'Add New Episode', 'aio-podcast-studio' ),
			'manage_aiopod_options',
			'post-new.php?post_type=aiopod_episodes'
		);

		add_submenu_page(
            'aio-podcast-studio',
            '',
            '<span class="aiopod-menu-separator"></span>',
            'manage_aiopod_options',
            'aio-podcast-studio-separator-1',
            '__return_null'
        );
	}

	/**
	 * Move "All Episodes" 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_episodes' === $current_screen->post_type ) {
			$parent_file = 'aio-podcast-studio';

			if ( 'post' === $current_screen->base && 'add' === $current_screen->action  ) {
				// Highlight "Add New Episode"
				$submenu_file = 'post-new.php?post_type=aiopod_episodes';
			} else {
				// Highlight "All Episodes"
				$submenu_file = 'edit.php?post_type=aiopod_episodes';
			}
		}

		return $parent_file;
	}

	/**
	 * Register the custom post type "aiopod_episodes".
	 *
	 * @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( 'Episodes', 'Post Type General Name', 'aio-podcast-studio' ),
			'singular_name'         => _x( 'Episode', 'Post Type Singular Name', 'aio-podcast-studio' ),
			'menu_name'             => __( 'Episodes', 'aio-podcast-studio' ),
			'name_admin_bar'        => __( 'Episode', 'aio-podcast-studio' ),
			'archives'              => __( 'Episode Archives', 'aio-podcast-studio' ),
			'attributes'            => __( 'Episode Attributes', 'aio-podcast-studio' ),
			'parent_item_colon'     => __( 'Parent Episode:', 'aio-podcast-studio' ),
			'all_items'             => __( 'All Episodes', 'aio-podcast-studio' ),
			'add_new_item'          => __( 'Add New Episode', 'aio-podcast-studio' ),
			'add_new'               => __( 'Add New', 'aio-podcast-studio' ),
			'new_item'              => __( 'New Episode', 'aio-podcast-studio' ),
			'edit_item'             => __( 'Edit Episode', 'aio-podcast-studio' ),
			'update_item'           => __( 'Update Episode', 'aio-podcast-studio' ),
			'view_item'             => __( 'View Episode', 'aio-podcast-studio' ),
			'view_items'            => __( 'View Episodes', 'aio-podcast-studio' ),
			'search_items'          => __( 'Search Episodes', 'aio-podcast-studio' ),
			'not_found'             => __( 'No episodes found.', 'aio-podcast-studio' ),
			'not_found_in_trash'    => __( 'No episodes 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 episode', 'aio-podcast-studio' ),
			'uploaded_to_this_item' => __( 'Uploaded to this episode', 'aio-podcast-studio' ),
			'items_list'            => __( 'Episodes list', 'aio-podcast-studio' ),
			'items_list_navigation' => __( 'Episodes list navigation', 'aio-podcast-studio' ),
			'filter_items_list'     => __( 'Filter episodes list', 'aio-podcast-studio' ),
		);
		
		$supports = array( 'title', 'editor', 'excerpt', 'comments' );			
		if ( ! empty( $appearance_settings['enable_featured_images'] ) ) {
			$supports[] = 'thumbnail';
		}
		
		$args = array(
			'label'                 => __( 'Episode', 'aio-podcast-studio' ),
			'description'           => __( 'Episode 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['episode_archive_page'] ) ) {
			$page_id = (int) $pages_settings['episode_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_episodes', $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_episodes' === $screen->post_type ) {
        	$text = __( 'Give your episode a 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_episodes' === $post_type ) {
			$post_id = $post->ID;
			require_once AIOPOD_PLUGIN_DIR . 'admin/partials/episodes/metabox-publish.php';
		}		
	}
	
	/**
	 * Register meta boxes.
	 *
	 * @since 1.0.0
	 */
	public function add_meta_boxes() {
		add_meta_box( 
			'aiopod-metabox-episode-info', 
			__( 'Episode Info', 'aio-podcast-studio' ), 
			array( $this, 'display_meta_box_episode_info' ), 
			'aiopod_episodes', 
			'normal', 
			'high' 
		);
	}

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

		require_once AIOPOD_PLUGIN_DIR . 'admin/partials/episodes/metabox-episode-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_episodes" custom post type
    	if ( ! $post || 'aiopod_episodes' !== $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_episode_submitbox_nonce" nonce is set
    	if ( isset( $_POST['aiopod_episode_submitbox_nonce'] ) ) {		
			// Verify that the nonce is valid
    		if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aiopod_episode_submitbox_nonce'] ) ), 'aiopod_save_episode_submitbox' ) ) {			
				// OK to save meta data.
				$is_featured = isset( $_POST['is_featured'] ) ? 1 : 0;
    			update_post_meta( $post_id, 'is_featured', $is_featured );				
			}			
		} else {
			$is_featured = (int) get_post_meta( $post_id, 'is_featured', true );
			update_post_meta( $post_id, 'is_featured', $is_featured );
		}

		// Check if "aiopod_episode_metabox_nonce" nonce is set
    	if ( isset( $_POST['aiopod_episode_metabox_nonce'] ) ) {		
			// Verify that the nonce is valid
    		if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aiopod_episode_metabox_nonce'] ) ), 'aiopod_save_episode_metabox' ) ) {			
				// OK to save meta data		
				$appearance_settings  = aiopod_get_option( 'aiopod_appearance_settings' );

				$old_podcast_id = isset( $_POST['old_parent'] ) ? (int) wp_unslash( $_POST['old_parent'] ) : 0;
				$new_podcast_id = isset( $_POST['post_parent'] ) ? (int) wp_unslash( $_POST['post_parent'] ) : 0;

				// Clear old and new podcast caches
				if ( $old_podcast_id && $old_podcast_id !== $new_podcast_id ) {
					aiopod_clear_season_cache( $old_podcast_id );
				}

				aiopod_clear_season_cache( $new_podcast_id );

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

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

				$episode_file_type = ! empty( $_POST['episode_file_type'] ) ? sanitize_text_field( wp_unslash( $_POST['episode_file_type'] ) ) : '';
				update_post_meta( $post_id, 'episode_file_type', $episode_file_type );

				$episode_file_size = ! empty( $_POST['episode_file_size'] ) ? aiopod_sanitize_int( wp_unslash( $_POST['episode_file_size'] ) ) : '';
				update_post_meta( $post_id, 'episode_file_size', $episode_file_size );

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

				$is_video = aiopod_is_video( $episode_file_type, $episode_file );
				update_post_meta( $post_id, 'is_video', $is_video ? 1 : 0 );

				$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 );

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

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

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

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

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

				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 );
					}
				}

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

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

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

				delete_post_meta( $post_id, 'chapters' );
				if ( ! empty( $_POST['chapter_time'] ) ) {
					$chapter_times  = wp_unslash( (array) $_POST['chapter_time'] );
					$chapter_labels = wp_unslash( (array) $_POST['chapter_label'] );

					foreach ( $chapter_times as $key => $value ) {
						$time  = sanitize_text_field( $value );
						$label = sanitize_text_field( $chapter_labels[ $key ] );

						if ( empty( $time ) || empty( $label ) ) continue;

						$chapter = array(
							'time'  => $time,
							'label' => $label
						);

						add_post_meta( $post_id, 'chapters', $chapter );
					}
				}

				$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_episodes' === $typenow ) {
			// Filter by podcast
			$post_parent = isset( $_GET['post_parent'] ) ? (int) wp_unslash( $_GET['post_parent'] ) : 0;

			echo '<select name="post_parent" id="aiopod_podcasts" class="postform">';	
			echo sprintf( '<option value="0">%s</option>', esc_html__( 'All Podcasts', 'aio-podcast-studio' ) );

			$posts = get_posts(	array(
				'post_type'              => 'aiopod_podcasts',
				'numberposts'            => -1,
				'orderby'                => 'title',
				'order'                  => 'ASC',
				'no_found_rows'          => true,
				'ignore_sticky_posts'    => true,
				'update_post_term_cache' => false,
				'update_post_meta_cache' => false,
				'suppress_filters'       => true
			) );

			if ( $posts ) {
				foreach ( $posts as $post ) {
					echo sprintf( 
						'<option value="%d"%s>%s</option>', 
						esc_attr( $post->ID ),
						selected( $post->ID, $post_parent, false ), 
						esc_html( $post->post_title )
					);
				}
			}
			
			echo '</select>';	

			// Filter by tag
        	wp_dropdown_categories( array(
            	'show_option_none'  => __( 'All Tags', 'aio-podcast-studio' ),
				'option_none_value' => 0,
            	'taxonomy'          => 'aiopod_tags',
            	'name'              => 'aiopod_tags',
            	'orderby'           => 'name',
            	'selected'          => isset( $wp_query->query['aiopod_tags'] ) ? $wp_query->query['aiopod_tags'] : '',
            	'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 episode type, explicit, featured, 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(
				'full'     => __( 'Full Episodes', 'aio-podcast-studio' ),
				'trailer'  => __( 'Trailer Episodes', 'aio-podcast-studio' ),
				'bonus'    => __( 'Bonus Episodes', 'aio-podcast-studio' ),
				'explicit' => __( 'Explicit Episodes', 'aio-podcast-studio' ),
				'featured' => __( 'Featured Episodes', 'aio-podcast-studio' ),
				'audio'    => __( 'Audio Episodes', 'aio-podcast-studio' ),
			);

			$options = apply_filters( 'aiopod_episode_filter_options', $options );
			
			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 episodes 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_episodes' === $post_type ) {
			// Filter by podcast
			$post_parent = isset( $_GET['post_parent'] ) ? (int) wp_unslash( $_GET['post_parent'] ) : 0;
			if ( $post_parent > 0 ) {		
        		$query->query_vars['post_parent'] = $post_parent;			
    		}

			// Filter by tag
			if ( isset( $query->query_vars['aiopod_tags'] ) && ctype_digit( $query->query_vars['aiopod_tags'] ) && 0 !== (int) $query->query_vars['aiopod_tags'] ) {		
        		$term = get_term_by( 'id', $query->query_vars['aiopod_tags'], 'aiopod_tags' );
        		$query->query_vars['aiopod_tags'] = $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 episode type, explicit, featured, etc.
			$filter_by  = isset( $_GET['filter_by'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_by'] ) ) : '';
			$meta_query = array();

			switch ( $filter_by ) {
				case 'full':
				case 'trailer':
				case 'bonus':
					$meta_query[] = array(
						'key'     => 'episode_type',
						'value'   => $filter_by,
						'compare' => '='
					);
					break;

				case 'audio':
					$meta_query[] = array(
						'key'     => 'is_video',
						'value'   => 0,
						'compare' => '='
					);
					break;

				case 'video':
					$meta_query[] = array(
						'key'     => 'is_video',
						'value'   => 1,
						'compare' => '='
					);
					break;

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

				case 'featured':
					$meta_query[] = array(
						'key'     => 'is_featured',
						'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_episodes' ) {
			// 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_episode id="' . $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_tags'] );
		unset( $columns['author'] );

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

		$columns = aiopod_insert_array_after( 'title', $columns, array(
			'podcast'              => __( 'Podcast', 'aio-podcast-studio' ),
			'taxonomy-aiopod_tags' => __( 'Tags', 'aio-podcast-studio' )
		));

		$columns = aiopod_insert_array_after( 'taxonomy-aiopod_participants', $columns, array(
			'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 'podcast':
				$parent_id = (int) get_post_field( 'post_parent', $post_id );

				if ( $parent_id > 0 ) {
					echo esc_html( get_the_title( $parent_id ) );
				} else {
					echo '&mdash;';
				}
				break;

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

				// Episode Type
				$episode_type = aiopod_get_episode_type( $post_id );

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

				// Media Type (Audio/Video)
				$is_video = get_post_meta( $post_id, 'is_video', true );

				$meta[] = sprintf( 
					'<span class="aiopod-meta-label">%s:</span> <span class="aiopod-meta-value">%s</span>',
					esc_html__( 'Media Type', 'aio-podcast-studio' ), 
					! empty( $is_video ) ? esc_html__( 'Video', 'aio-podcast-studio' ) : esc_html__( 'Audio', 'aio-podcast-studio' ) 
				);

				// Season Number
				$season_number = get_post_meta( $post_id, 'season_number', true );

				if ( ! empty( $season_number ) ) {
					$meta[] = sprintf( 
						'<span class="aiopod-meta-label">%s:</span> <span class="aiopod-meta-value">%s</span>',
						esc_html__( 'Season Number', 'aio-podcast-studio' ), 
						esc_html( $season_number ) 
					);
				}			
				
				// Episode Number
				$episode_number = get_post_meta( $post_id, 'episode_number', true );

				if ( ! empty( $episode_number ) ) {
					$meta[] = sprintf( 
						'<span class="aiopod-meta-label">%s:</span> <span class="aiopod-meta-value">%s</span>',
						esc_html__( 'Episode Number', 'aio-podcast-studio' ), 
						esc_html( $episode_number ) 
					);
				}

				// 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' ) 
				);

				// Featured
				$is_featured = get_post_meta( $post_id, 'is_featured', true );

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

				// Print metadata
				echo '<ul class="aiopod-unstyled-list">';
				echo '<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 $post_id;
				break;
		}
	}
	
	/**
	 * Disable Gutenberg on our custom post type "aiopod_episodes".
	 *
	 * @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_episodes' === $post_type ) return false;
		return $use_block_editor;
	}
	
	/**
	 * Fires after an episode is sent to the Trash.
	 *
	 * @since 1.0.0
	 * @param int   $post_id Post ID.
	 */
	public function trashed_post( $post_id ) {		
		if ( 'aiopod_episodes' != get_post_type( $post_id ) ) {
			return;
		}
		  
		$podcast_id = (int) get_post_field( 'post_parent', $post_id );
		aiopod_clear_season_cache( $podcast_id );	
	}

	/**
	 * Fires before an episode is deleted, at the start of wp_delete_post().
	 *
	 * @since 1.0.0
	 * @param int   $post_id Post ID.
	 */
	public function before_delete_post( $post_id ) {
		if ( 'aiopod_episodes' !== get_post_type( $post_id ) ) {
			return;
		}

		if ( ! defined( 'AIOPOD_DELETING_EPISODE' ) ) {
			define( 'AIOPOD_DELETING_EPISODE', true );
		}

		$podcast_id = (int) get_post_field( 'post_parent', $post_id );

		// Skip season cache clear when the parent podcast is also being deleted —
		// it would fire N times for the same podcast and the podcast is gone anyway.
		if ( ! ( defined( 'AIOPOD_DELETING_PODCAST' ) && AIOPOD_DELETING_PODCAST ) ) {
			aiopod_clear_season_cache( $podcast_id );
		}

		aiopod_delete_episode_attachments( $post_id );
	}

}
