<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link    https://aiopodcasting.com
 * @since   1.0.0
 *
 * @package AiO_Podcast_Studio
 */

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

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

	/**
	 * Insert missing plugin options.
	 *
	 * aiopod_get_option() falls back to the defaults only when the whole option
	 * is absent, so a key introduced in a later version never reaches an install
	 * that has already saved its settings. Backfill those keys here.
	 *
	 * @since 1.0.4
	 */
	public function insert_missing_options() {
		// Insert the missing player settings
		$player_settings = get_option( 'aiopod_player_settings' );

		if ( ! is_array( $player_settings ) || empty( $player_settings ) ) {
			$defaults        = aiopod_get_default_settings();
			$player_settings = $defaults['aiopod_player_settings'];

			update_option( 'aiopod_player_settings', $player_settings );
		}

		$missing_player_settings = array();

		if ( ! array_key_exists( 'excerpt_length', $player_settings ) ) {
			$missing_player_settings['excerpt_length'] = 100;
		}

		if ( ! empty( $missing_player_settings ) ) {
			update_option( 'aiopod_player_settings', array_merge( $player_settings, $missing_player_settings ) );
		}

		// Insert the taxonomies settings.
		$taxonomies_settings = get_option( 'aiopod_taxonomies_settings' );

		if ( ! is_array( $taxonomies_settings ) || empty( $taxonomies_settings ) ) {
			$defaults = aiopod_get_default_settings();

			update_option( 'aiopod_taxonomies_settings', $defaults['aiopod_taxonomies_settings'] );
		}
	}
	
	/**
	 * Add plugin's main menu and "Dashboard" menu.
	 *
	 * @since 1.0.0
	 */
	public function admin_menu() {	
		add_menu_page(
            __( 'AiO Podcast Studio', 'aio-podcast-studio' ),
            __( 'Podcasts', 'aio-podcast-studio' ),
            'manage_aiopod_options',
            'aio-podcast-studio',
            array( $this, 'display_page_content' ),
            'dashicons-microphone',
            30
		);	
		
		add_submenu_page(
			'aio-podcast-studio',
			__( 'AiO Podcast Studio - Dashboard', 'aio-podcast-studio' ),
			__( 'Dashboard', 'aio-podcast-studio' ),
			'manage_aiopod_options',
			'aio-podcast-studio',
			array( $this, 'display_page_content' )
		);
	}

	/**
	 * Display page content.
	 *
	 * @since 1.0.0
	 */
	public function display_page_content() {
		require_once AIOPOD_PLUGIN_DIR . 'admin/partials/dashboard/dashboard.php';	
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since 1.0.0
	 * @param string $hook The current admin page.
	 */
	public function enqueue_styles( $hook ) {
		wp_enqueue_style( 'wp-color-picker' );

		wp_enqueue_style(
			AIOPOD_PLUGIN_SLUG . '-admin',
			AIOPOD_PLUGIN_URL . 'admin/assets/css/admin.min.css',
			array(),
			AIOPOD_PLUGIN_VERSION,
			'all'
		);
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since 1.0.0
	 * @param string $hook The current admin page.
	 */
	public function enqueue_scripts( $hook ) {
		global $post_type;

		if ( 
			( in_array( $hook, array( 'post-new.php', 'post.php' ) ) && in_array( $post_type, array( 'aiopod_podcasts', 'aiopod_episodes' ) ) ) || 
			( isset( $_GET['taxonomy'] ) && in_array( sanitize_key( wp_unslash( $_GET['taxonomy'] ) ), array( 'aiopod_categories', 'aiopod_participants' ), true ) )
		) {
			wp_enqueue_media();
		}
		
        wp_enqueue_script( 'wp-color-picker' );

		wp_enqueue_script(
			AIOPOD_PLUGIN_SLUG . '-admin', 
			AIOPOD_PLUGIN_URL . 'admin/assets/js/admin.min.js', 
			array( 'jquery' ), 
			AIOPOD_PLUGIN_VERSION, 
			array( 'strategy' => 'defer' ) 
		);

		wp_localize_script(
			AIOPOD_PLUGIN_SLUG . '-admin',
			'aiopod_admin',
			array(
				'plugin_url' => AIOPOD_PLUGIN_URL,
				'ajax_nonce' => wp_create_nonce( 'aiopod_ajax_nonce' ),
				'site_url'   => get_site_url(),
				'i18n'       => array(
					'feed_required' => __( 'Please enter an RSS feed URL.', 'aio-podcast-studio' ),
					'feed_invalid'  => __( 'The RSS feed URL format seems invalid. Please check and try again.', 'aio-podcast-studio' ),
					'import_status' => __( 'We\'re importing your podcast. This may take a moment. Please stay on this page.', 'aio-podcast-studio' ),
					'import_failed' => __( 'Import failed. The connection to the server was lost. Please try again.', 'aio-podcast-studio' ),
					'copied'        => __( 'Copied!', 'aio-podcast-studio' )
				)
			)
		);
	}

	/**
	 * Recount core taxonomy terms when the WordPress taxonomies setting changes.
	 *
	 * The work itself is `aiopod_update_core_term_counts()`, in the helpers, because it is a
	 * data-integrity concern rather than an admin one — the activator and the deactivator call
	 * it too. This method exists only so the hook can be registered through the loader, which
	 * binds `array( $component, $callback )` and cannot take a plain function.
	 *
	 * @since 1.0.4
	 * @param mixed $old_value Value before the save.
	 * @param mixed $value     Value just saved.
	 */
	public function update_core_term_counts( $old_value, $value ) {
		aiopod_update_core_term_counts( $old_value, $value );
	}
	
	/**
     * Flags rewrite rules for flushing on the next request when the assigned pages change.
     *
     * Registered on `update_option_aiopod_pages_settings`, so reaching this method already means
     * that option changed — there is nothing left to check. It previously listened on the generic
     * `updated_option` and compared the name itself, which ran on every option write on the site,
     * transients included, to answer "not mine" almost every time.
     *
     * @since 1.0.0
     */
    public function force_rewrite_rules_on_settings_update() {
        // Force rewrite rules flush on next load
        delete_option( 'aiopod_rewrite_rules_flushed' );
    }

	/**
     * Flags rewrite rules for flushing when an assigned AIOPOD page
     * or its translation is updated.
     *
     * @since 1.0.0
     * @param int     $post_id Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post update.
     */
    public function force_rewrite_rules_on_page_update( $post_id, $post, $update ) {
        // Avoid autosaves & revisions
        if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
            return;
        }

        // Only act on updates (not new pages)
        if ( ! $update ) {
            return;
        }

        // Defensive capability check
        if ( ! current_user_can( 'edit_page', $post_id ) ) {
            return;
        }

        $pages_settings = aiopod_get_option( 'aiopod_pages_settings' );

        if ( empty( $pages_settings ) ) {
            return;
        }

        // Normalize assigned page IDs
        $assigned_pages = array_map( 'intval', $pages_settings );

        // Direct Match (Fast Path)
        if ( in_array( (int) $post_id, $assigned_pages, true ) ) {
            delete_option( 'aiopod_rewrite_rules_flushed' );
            return;
        }

        // Check for Polylang translations
        if ( function_exists( 'pll_get_post_translations' ) ) {
            foreach ( $assigned_pages as $assigned_id ) {
                $translations = pll_get_post_translations( $assigned_id );

                if ( empty( $translations ) ) {
                    continue;
                }

                if ( in_array( (int) $post_id, array_map( 'intval', $translations ), true ) ) {
                    delete_option( 'aiopod_rewrite_rules_flushed' );
                    return;
                }
            }
        }

        // Check for WPML translations (TRID-based)
        if ( defined( 'ICL_SITEPRESS_VERSION' ) ) {
            $element_type = apply_filters( 'wpml_element_type', 'page' );
            $current_trid = apply_filters( 'wpml_element_trid', null, $post_id, $element_type );

            if ( ! empty( $current_trid ) ) {
                foreach ( $assigned_pages as $assigned_id ) {
                    $assigned_trid = apply_filters( 'wpml_element_trid', null, $assigned_id, $element_type );

                    if ( (int) $current_trid === (int) $assigned_trid ) {
                        delete_option( 'aiopod_rewrite_rules_flushed' );
                        return;
                    }
                }
            }
        }
    }

	/**
	 * Add a post display state for special AIOPOD pages in the page list table.
	 *
	 * @since 1.0.0
	 * @param array   $post_states An array of post display states.
	 * @param WP_Post $post        The current post object.
	 */
	public function add_display_post_states( $post_states, $post ) {
		$pages_settings = aiopod_get_option( 'aiopod_pages_settings' );
		
		if ( isset( $pages_settings['category'] ) && $pages_settings['category'] == $post->ID ) {
			$post_states['aiopod_page_for_category'] = __( 'Podcast Category Page', 'aio-podcast-studio' );
		}

		if ( isset( $pages_settings['tag'] ) && $pages_settings['tag'] == $post->ID ) {
			$post_states['aiopod_page_for_tag'] = __( 'Episode Tag Page', 'aio-podcast-studio' );
		}

		if ( isset( $pages_settings['participant'] ) && $pages_settings['participant'] == $post->ID ) {
			$post_states['aiopod_page_for_participant'] = __( 'Participant Page', 'aio-podcast-studio' );
		}

		return $post_states;
	}

	/**
	 * Add a settings link on the plugin listing page.
	 *
	 * @since  1.0.0
	 * @param  array  $links An array of plugin action links.
	 * @return string $links Array of filtered plugin action links.
	 */
	public function plugin_action_links( $links ) {
		$settings_link = sprintf( 
			'<a href="%s">%s</a>', 
			esc_url( admin_url( 'admin.php?page=aiopod_settings' ) ), 
			__( 'Settings', 'aio-podcast-studio' ) 
		);

        array_unshift( $links, $settings_link );
		
    	return $links;
	}

}
