<?php

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

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

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

	/**
	 * Register the gettext filter only when managing the participants taxonomy.
	 *
	 * @since 1.0.0
	 */
	public function admin_init() {	
		if ( isset( $_GET['taxonomy'] ) && 'aiopod_participants' === sanitize_key( wp_unslash( $_GET['taxonomy'] ) ) ) {
			add_filter( 'gettext', array( $this, 'change_default_description_label' ), 10, 3 );
		}
	}

	/**
	 * Add "Participants" menu.
	 *
	 * @since 1.0.0
	 */
	public function admin_menu() {	
		add_submenu_page(
			'aio-podcast-studio',
			__( 'AiO Podcast Studio - Participants', 'aio-podcast-studio' ),
			__( 'Participants', 'aio-podcast-studio' ),
			'manage_aiopod_options',
			'edit-tags.php?taxonomy=aiopod_participants'
		);
		
		add_submenu_page(
            'aio-podcast-studio',
            '',
            '<span class="aiopod-menu-separator"></span>',
            'manage_aiopod_options',
            'aio-podcast-studio-separator-2',
            '__return_null'
        );
	}

	/**
	 * Move "Participants" 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_participants' === $current_screen->taxonomy ) {
			$parent_file  = 'aio-podcast-studio';
			$submenu_file = 'edit-tags.php?taxonomy=aiopod_participants';
		}

		return $parent_file;
	}
	
	/**
	 * Register the custom taxonomy "aiopod_participants".
	 *
	 * @since 1.0.0
	 */
	public function register_taxonomy() {	
		$labels = array(
			'name'                       => _x( 'Participants', 'Taxonomy General Name', 'aio-podcast-studio' ),
			'singular_name'              => _x( 'Participant', 'Taxonomy Singular Name', 'aio-podcast-studio' ),
			'menu_name'                  => __( 'Participants', 'aio-podcast-studio' ),
			'all_items'                  => __( 'All Participants', 'aio-podcast-studio' ),
			'parent_item'                => null,
			'parent_item_colon'          => null,
			'desc_field_description'     => __( 'Write a short biography of the participant. This will be displayed on podcast and episode pages.', 'aio-podcast-studio' ),
			'new_item_name'              => __( 'New Participant Name', 'aio-podcast-studio' ),
			'add_new_item'               => __( 'Add New Participant', 'aio-podcast-studio' ),
			'edit_item'                  => __( 'Edit Participant', 'aio-podcast-studio' ),
			'update_item'                => __( 'Update Participant', 'aio-podcast-studio' ),
			'view_item'                  => __( 'View Participant', 'aio-podcast-studio' ),
			'back_to_items'              => __( '← Back to participants', 'aio-podcast-studio' ),
			'separate_items_with_commas' => __( 'Separate participants with commas', 'aio-podcast-studio' ),
			'add_or_remove_items'        => __( 'Add or remove participants', 'aio-podcast-studio' ),
			'choose_from_most_used'      => __( 'Choose from the most used', 'aio-podcast-studio' ),
			'popular_items'              => __( 'Popular Participants', 'aio-podcast-studio' ),
			'search_items'               => __( 'Search Participants', 'aio-podcast-studio' ),
			'not_found'                  => __( 'No participants found.', 'aio-podcast-studio' ),
			'no_terms'                   => __( 'No participants', 'aio-podcast-studio' ),
			'items_list'                 => __( 'Participants list', 'aio-podcast-studio' ),
			'items_list_navigation'      => __( 'Participants list navigation', 'aio-podcast-studio' ),
		);
		
		$args = array(
			'labels'                     => $labels,
			'hierarchical'               => false,
			'public'                     => true,
			'show_ui'                    => true,
			'show_admin_column'          => true,
			'show_in_nav_menus'          => true,
			'show_in_rest'               => true,
			'show_tagcloud'              => true,
			'meta_box_cb'                => false,
			'capabilities'               => array(
				'manage_terms' => 'manage_aiopod_options',
				'edit_terms'   => 'manage_aiopod_options',				
				'delete_terms' => 'manage_aiopod_options',
				'assign_terms' => 'edit_aiopod_podcasts'
			)
		);
		
		register_taxonomy( 'aiopod_participants', array( 'aiopod_podcasts', 'aiopod_episodes' ), $args );	
	}

	/**
	 * Modifies the default "Description" label specifically for the Participant taxonomy screens.
	 *
	 * @since  1.0.0
	 * @param  string $translated The translated text.
	 * @param  string $original   The original text being translated.
	 * @param  string $domain     The text domain.
	 * @return string             The modified or original translated text.
	 */
	public function change_default_description_label( $translated, $original, $domain ) {
		if ( 'Description' !== $original || 'default' !== $domain ) {
			return $translated;
		}

		return __( 'Biography', 'aio-podcast-studio' );
	}

	/**
	 * Add custom form fields.
	 *
	 * @since 1.0.0
	 */
	public function add_form_fields() {	
		$form = 'add';		
		require_once AIOPOD_PLUGIN_DIR . 'admin/partials/participants/custom-fields.php';	
	}
	
	/**
	 * Edit custom form fields.
	 *
	 * @since 1.0.0
	 * @param object $term Taxonomy term object.
	 */
	public function edit_form_fields( $term ) {	
		$form = 'edit';
		$term_meta = get_term_meta( $term->term_id );

		require_once AIOPOD_PLUGIN_DIR . 'admin/partials/participants/custom-fields.php';	
	}
	
	/**
	 * Save custom form fields.
	 *
	 * @since 1.0.0
	 * @param int   $term_id Term ID.
	 */
	public function save_form_fields( $term_id ) {	
		// Check if "aiopod_participant_fields_nonce" nonce is set
    	if ( isset( $_POST['aiopod_participant_fields_nonce'] ) ) {		
			// Verify that the nonce is valid
    		if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aiopod_participant_fields_nonce'] ) ), 'aiopod_save_participant_fields' ) ) {			
				// OK to save meta data
				$job_title = isset( $_POST['job_title'] ) ? sanitize_text_field( wp_unslash( $_POST['job_title'] ) ) : '';
				update_term_meta( $term_id, 'job_title', $job_title );

				$company_name = isset( $_POST['company_name'] ) ? sanitize_text_field( wp_unslash( $_POST['company_name'] ) ) : '';
				update_term_meta( $term_id, 'company_name', $company_name );

				$website_url = isset( $_POST['website_url'] ) ? aiopod_sanitize_url( wp_unslash( $_POST['website_url'] ) ) : '';
				update_term_meta( $term_id, 'website_url', $website_url );

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

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

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

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

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

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

				// Keep the attachment ID in sync with the image URL (corrects stale/missing IDs).
				$image_id = ! empty( $image ) ? (int) attachment_url_to_postid( $image ) : 0;
				update_term_meta( $term_id, 'image_id', $image_id );
			}		
		}   
	}
	
	/**
	 * Retrieve the table columns.
	 *
	 * @since  1.0.0
	 * @param  array $columns Array of default table columns.
	 * @return array $columns Updated list of table columns.
	 */
	public function get_columns( $columns ) {
		unset( $columns['description'] );

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

		$columns = aiopod_insert_array_after( 'slug', $columns, array( 
			'tax_id' => __( 'ID', 'aio-podcast-studio' )
		));

    	return $columns;		
	}
	
	/**
	 * This function renders the custom columns in the list table.
	 *
	 * @since 1.0.0
	 * @param string $content Content of the column.
	 * @param string $column  Name of the column.
	 * @param string $term_id Term ID.
	 */
	public function custom_column_content( $content, $column, $term_id ) {
		switch ( $column ) {
			case 'image':
				$content = aiopod_the_image( array( 
					'term_id'     => $term_id,
					'size'        => 'thumbnail',
					'width'       => '75px',
					'alt'         => '',
					'placeholder' => AIOPOD_PLUGIN_PLACEHOLDER_AVATAR_URL,
					'echo'        => false
				) );
				break;

			case 'tax_id':
				$content = $term_id;
				break;
		}	
		
		return $content;	
	}
	
	/**
	 * Delete attachments.
	 *
	 * @since 1.0.0
	 * @param int    $term_id  Term ID.
	 * @param string $taxonomy Taxonomy Name.
	 */
	public function pre_delete_term( $term_id, $taxonomy ) {		
		if ( 'aiopod_participants' !== $taxonomy ) {
			return;
		}
		  
		aiopod_delete_term_attachments( $term_id );
	}

}
