<?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 {
	
	/**
	 * 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' )
				)
			)
		);
	}

	/**
     * Flags rewrite rules for flushing on the next request when relevant options change.
     *
     * @since 1.0.0
     * @param string $option Option name being updated.
     * @param mixed  $old    Previous option value.
     * @param mixed  $value  Updated option value.
     */
    public function force_rewrite_rules_on_settings_update( $option, $old, $value ) {
        if ( 'aiopod_pages_settings' === $option ) {
            // 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;
	}

}
