<?php
/**
 * Service provider for Voicexpress
 *
 * @category Voicexpress
 * @package  Voicexpress
 * @author   ER Soluções Web LTDA <contato@ersolucoesweb.com.br>
 * @license  MIT  https://ersolucoesweb.com.br
 * @link     https://ersolucoesweb.com.br
 */

namespace Voicexpress;

/**
 * Voicexpress service provider
 *
 * @category Voicexpress
 * @package  Voicexpress
 * @author   ER Soluções Web LTDA <contato@ersolucoesweb.com.br>
 * @license  MIT  https://ersolucoesweb.com.br
 * @link     https://ersolucoesweb.com.br
 */
class ServiceProvider {

	/**
	 * Voicexpress app url
	 *
	 * @var string
	 */
	
	public $affiliate_link;

	public $app_url = 'https://voicexpress.app';

	/**
	 * Initialize class
	 */
	public function __construct() {
		$app_url = getenv( 'VOICEXPRESS_APP_URL' );
		if ( $app_url ) {
			$this->app_url = $app_url;
		}
		$this->affiliate_link = $this->app_url . '/ref/' . get_option( '_voicexpress_affiliate_code', get_home_url( ) );
	}

	/**
	 * Start plugin
	 *
	 * @return void
	 */
	public function boot() {
		load_plugin_textdomain(
			'voicexpress',
			false,
			dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/languages/'
		);
		add_action( 'voicexpress_send_post', array( $this, 'voicexpress_send_post' ), 10, 2 );

		add_filter(
			'bulk_actions-edit-post',
			function ( $bulk_actions ) {
				$bulk_actions['voicexpress_update_audio'] = 'Atualizar áudios';
				return $bulk_actions;
			}
		);

		add_filter(
			'handle_bulk_actions-edit-post',
			function ( $redirect_to, $doaction, $post_ids ) {
				if ( 'voicexpress_update_audio' !== $doaction ) {
					return $redirect_to;
				}

				$voicexpress_crontab = get_option( 'voicexpress_crontab', 0 );
				
				foreach ( $post_ids as $post_id ) {
					if ( $voicexpress_crontab == 1 ) {
						wp_schedule_single_event( time( ) + 5, 'voicexpress_send_post', array( $post_id, true ) );
						continue;
					}
					$this->voicexpress_send_post( $post_id, true );
				}

				$redirect_to = add_query_arg( 'bulk_voicexpress_update_audio', count( $post_ids ), $redirect_to );
				return $redirect_to;
			},
			10,
			3
		);

		add_action(
			'admin_notices',
			function () {
				if ( isset( $_REQUEST['bulk_voicexpress_update_audio'] ) && ! empty( $_REQUEST['bulk_voicexpress_update_audio'] ) ) {
					$processed_count = intval( $_REQUEST['bulk_voicexpress_update_audio'] );
					echo wp_kses_post(
						sprintf(
							'<div id="message" class="updated fade"><p>' .
							// translators: %s: numeros de áudios a gerar.
							_n(
								'%s áudio está  sendo atualizado.',
								'%s áudios estão  sendo atualizados.',
								$processed_count,
								'text-domain'
							) . '</p></div>',
							$processed_count
						)
					);
				}
			}
		);

		add_action( 'wp_ajax_voicexpress_notification', array( $this, 'voicexpress_notification' ) );
		add_action( 'wp_ajax_nopriv_voicexpress_notification', array( $this, 'voicexpress_notification' ) );

		add_action( 'wp_ajax_voicexpress_connected', array( $this, 'voicexpress_connected' ) );
		add_action( 'wp_ajax_nopriv_voicexpress_connected', array( $this, 'voicexpress_connected' ) );

		add_action( 'wp_ajax_voicexpress_disconnected', array( $this, 'voicexpress_disconnected' ) );
		add_action( 'wp_ajax_nopriv_voicexpress_disconnected', array( $this, 'voicexpress_disconnected' ) );

		add_action(
			'wp_ajax_voicexpress_get_post',
			function () {
				if ( ! isset( $_GET['nonce'] ) ) {
					die( 'nonce not is set' );
				}
				$nonce = sanitize_text_field( wp_unslash( $_GET['nonce'] ) );
				if ( ! wp_verify_nonce( $nonce, 'voicexpress' ) ) {
					die( 'invalid nonce' );
				}
				if ( ! isset( $_GET['post_id'] ) ) {
					return;
				}
				$post_id = wp_unslash( (int) $_GET['post_id'] );
				$version = get_post_meta( $post_id, '_voicexpress_audio', true );
				$url     = 'https://cdn.voicexpress.app/audios/' . $version . '.mp3';
				$credits = $this->get_credits();
				wp_send_json_success(
					array(
						'url'     => $url,
						'credits' => $credits,
					)
				);
			}
		);

		add_action(
			'wp_ajax_voicexpress_resend_post',
			function () {
				if ( ! isset( $_GET['nonce'] ) ) {
					die( 'nonce not is set' );
				}
				$nonce = sanitize_text_field( wp_unslash( $_GET['nonce'] ) );
				if ( ! wp_verify_nonce( $nonce, 'voicexpress' ) ) {
					die( 'invalid nonce' );
				}
				if ( ! isset( $_GET['post_id'] ) ) {
					return;
				}
				$post_id = wp_unslash( (int) $_GET['post_id'] );
				$cron = get_option( 'voicexpress_crontab', 0 );
				if ( $cron == 1 ) {
					wp_schedule_single_event( time( ) + 5, 'voicexpress_send_post', array( $post_id, true ) );
					wp_redirect( admin_url('edit.php?bulk_voicexpress_update_audio=1') );
					exit;
				}
				$this->voicexpress_send_post( $post_id, true );
				wp_redirect( admin_url('edit.php?bulk_voicexpress_update_audio=1') );
				exit;
			}
		);

		add_action(
			'wp_enqueue_scripts',
			function () {
				// Enqueue frontend styles
				wp_enqueue_style( 'voicexpress-player', VOICEXPRESS_ASSETS_URL . '/voicexpress.css', array( ), time( ) );
				
				// Se player personalizado estiver ativado, carregar Vue.js e VoiceXpress Players
				$personalizado = get_option( 'voicexpress_player', 0 );
				if ( $personalizado ) {
					wp_enqueue_script( 'vue', 'https://unpkg.com/vue@3.4.21/dist/vue.global.prod.js', array(), '3.4.21', true );
					wp_enqueue_script( 'voicexpress', 'https://voicexpress.app/themes/voicexpress-player.js', array( ), time( ), true );
					wp_enqueue_style( 'voicexpress', 'https://voicexpress.app/themes/voicexpress-player.css', array( ), time( ) );
				} else {
					wp_enqueue_script( 'voicexpress', $this->app_url . '/app.js', array( 'jquery' ), time( ), true );
				}
				
				wp_localize_script(
					'voicexpress',
					'voicexpress',
					array(
						'url'   => admin_url( 'admin-ajax.php' ),
						'nonce' => wp_create_nonce( 'voicexpress' ),
						'theme' => get_option('voicexpress_theme' ),
						'affiliate_link' => $this->affiliate_link,
						'hide_download' => intval(get_option('voicexpress_hide_download' )),
						'hide_text' => intval(get_option('voicexpress_hide_text' )),
					)
				);
			}
		);

		add_action(
			'admin_enqueue_scripts',
			function () {
				// Enqueue admin styles

				wp_enqueue_style( 'voicexpress-player', VOICEXPRESS_ASSETS_URL . '/voicexpress.css', array( ), time( ) );
				wp_enqueue_script( 'voicexpress-vue', 'https://unpkg.com/vue@3.4.21/dist/vue.global.prod.js', array( ), time( ), true );
				wp_enqueue_script( 'voicexpress', 'https://voicexpress.app/themes/voicexpress-player.js', array( ), time( ), true );
				wp_enqueue_style( 'voicexpress', 'https://voicexpress.app/themes/voicexpress-player.css', array( ), time( ) );
				wp_localize_script(
					'voicexpress',
					'voicexpress',
					array(
						'url'   => admin_url( 'admin-ajax.php' ),
						'nonce' => wp_create_nonce( 'voicexpress' ),
						'theme' => get_option('voicexpress_theme' ),
						'affiliate_link' => $this->affiliate_link,
						'hide_download' => intval(get_option('voicexpress_hide_download' )),
						'hide_text' => intval(get_option('voicexpress_hide_text' )),
					)
				);
			}
		);

		// Adicionar Schema.org JSON-LD para podcasts
		add_action( 'wp_head', array( $this, 'add_podcast_schema' ) );

		add_filter(
			'the_content',
			function ( $content ) {
				global $post;
				if ( is_single( ) && 'post' == $post->post_type ) {
					$post_id       = get_the_ID( );
					$personalizado = get_option( 'voicexpress_player', 0 );
					if ( get_option( 'voicexpress_single_start' ) == 1 ) {
						$content = do_shortcode( "[voicexpress class='voicexpress-single-start " . ( $personalizado ? 'voicexpress-custom' : 'voicexpress-default' ) . "' post_id='{$post_id}']" ) . $content;

					}
					if ( get_option( 'voicexpress_single_end' ) == 1 ) {
						$content = $content . do_shortcode( "[voicexpress class='voicexpress-single-end " . ( $personalizado ? 'voicexpress-custom' : 'voicexpress-default' ) . "' post_id='{$post_id}']" );

					}
				}
				return $content;
			}
		);

		add_shortcode(
			'voicexpress',
			function ( $atts ) {
				if ( ! isset( $atts['post_id'] ) ) {
					$atts['post_id'] = get_the_ID( );
				}
				if ( empty( $atts['post_id'] ) ) {
					return;
				}
				$class   = $atts['class'];
				$version = get_post_meta( $atts['post_id'], '_voicexpress_audio', true );
				if ( empty( $version ) ) {
					return;
				}
				$post_url      = get_permalink( $atts['post_id'] );

				if ( empty( $version ) || 'Compre mais créditos' == $version ) {
					return '<div data-voicexpress class="voicexpress ' . esc_attr( $class ) . '" data-preload style="display:none;"><audio controls><source src="https://voicexpress.app/a/' . esc_url( $post_url ) . '" type="audio/mpeg"></audio><a class="voicexpress-copyright" href="' . $this->affiliate_link . '" target="_blank" title="Voicexpress">audio by <strong>Voicexpress</strong></a></div>';
				}
				
				$audio = 'https://cdn.voicexpress.app/audios/' . $version . '.mp3';
				
				return '<div data-voicexpress class="voicexpress ' . esc_attr( $class ) . '"><audio controls><source src="' . esc_url( $audio ) . '" type="audio/mpeg"></audio><a class="voicexpress-copyright" href="' . $this->app_url . '" target="_blank" title="Voicexpress">audio by <strong>Voicexpress</strong></a></div>';
			}
		);

		add_filter(
			'post_row_actions',
			function ( $actions, $post ) {
				if ( $post->post_type === 'post' ) {
					$url = admin_url( 'admin-ajax.php?action=voicexpress_resend_post&nonce=' . wp_create_nonce( 'voicexpress' ) . '&post_id=' . $post->ID );
					$actions['voicexpress_generate_audio'] = '<a href="' . esc_url( $url ) . '" class="voicexpress-generate-audio" title="Gerar áudio" >Gerar áudio</a>';
				}
				return $actions;
			},
			10,
			2
		);

		add_action(
			'save_post',
			function ( $post_id ) {

				$nonce = isset( $_POST['voicexpress_metabox_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['voicexpress_metabox_nonce'] ) ) : false;

				// Verificar se é uma requisição REST API
				$is_rest = wp_is_serving_rest_request();
				
				// Se não é REST API, verificar nonce (comportamento normal do admin)
				if ( ! $is_rest && ( ! $nonce || ! wp_verify_nonce( $nonce, 'voicexpress_save_metabox' ) ) ) {
					return;
				}

				if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
					return;
				}
				// Verificar se o post existe e é do tipo 'post' com status 'publish'
				$post = get_post( $post_id );
				if ( ! $post || !in_array($post->post_type, array( 'post' ), true ) || in_array( $post->post_status, array( 'auto-draft', 'draft', 'pending', 'trash' ), true ) ) {
					return;
				}

				// Para REST API, verificar se o post é do tipo 'post' e tem status 'publish'
				if ( $is_rest ) {					
					// Para REST API, usar a configuração automática se não foi especificado
					$gerar_audio = get_post_meta( $post_id, '_voicexpress_gerar_audio', true );
					if ( ! metadata_exists( 'post', $post_id, '_voicexpress_gerar_audio' ) ) {
						$gerar_audio = get_option( 'voicexpress_auto', 1 );
					}
				} else {
					// Comportamento normal do admin
					if ( ! current_user_can( 'edit_post', $post_id ) ) {
						return;
					}
					
					$gerar_audio = isset( $_POST['_voicexpress_gerar_audio'] ) && 1 == $_POST['_voicexpress_gerar_audio'];
				}

				if ( $gerar_audio ) {
					update_post_meta( $post_id, '_voicexpress_gerar_audio', 1 );
				} else {
					update_post_meta( $post_id, '_voicexpress_gerar_audio', 0 );
				}

				if ( ! $gerar_audio && get_option('voicexpress_auto', 1) == 0 ) {
					return;
				}

				$voicexpress_crontab = get_option( 'voicexpress_crontab', 0 );
				if ( $voicexpress_crontab ) {
					wp_schedule_single_event( time( ) + 5, 'voicexpress_send_post', array( $post_id, $gerar_audio ) );
					return;
				}
				$this->voicexpress_send_post( $post_id, $gerar_audio );
			}
		);

		// Hook para posts agendados que foram publicados
		add_action(
			'transition_post_status',
			function ( $new_status, $old_status, $post ) {
				// Verifica se é uma transição de 'future' (agendado) para 'publish'
				if ( $old_status === 'future' && $new_status === 'publish' && $post->post_type === 'post' ) {
					// Verifica se deve gerar áudio
					if ( get_post_meta( $post->ID, '_voicexpress_gerar_audio', true ) == 1 ) {
						$voicexpress_crontab = get_option( 'voicexpress_crontab', 0 );
						if ( $voicexpress_crontab ) {
							wp_schedule_single_event( time( ) + 5, 'voicexpress_send_post', array( $post->ID, 1 ) );
						} else {
							$this->voicexpress_send_post( $post->ID );
						}
						error_log( 'Post agendado publicado: ' . $post->ID );
					} else {
						if(get_option('voicexpress_auto', 1) == 1) {
							$voicexpress_crontab = get_option( 'voicexpress_crontab', 0 );
							if ( $voicexpress_crontab ) {
								wp_schedule_single_event( time( ) + 5, 'voicexpress_send_post', array( $post->ID, 1 ) );
							} else {
								$this->voicexpress_send_post( $post->ID );
							}
							error_log( 'Post agendado publicado (auto): ' . $post->ID );
						}
					}
				}
			},
			10,
			3
		);

		add_action(
			'add_meta_boxes',
			function () {
				add_meta_box(
					'voicexpress',
					'Voicexpress',
					function ( $post ) {
						$voicexpress_css               = trim( get_option( 'voicexpress_css', file_get_contents( VOICEXPRESS_ASSETS_PATH . 'skins/green-audio-player/css/green-audio-player.css' ) ) );
						$voicexpress_player = get_option( 'voicexpress_player', 0 );
						$gerar_audio                   = get_post_meta( $post->ID, '_voicexpress_gerar_audio', true );
						if ( ! metadata_exists( 'post', $post->ID, '_voicexpress_gerar_audio' ) ) {
							$gerar_audio = get_option( 'voicexpress_auto', 1 );
						}
						$credits = get_option( 'voicexpress_credits', 0 );
						$post_id = (int) $post->ID;
						wp_nonce_field( 'voicexpress_save_metabox', 'voicexpress_metabox_nonce' );
						echo esc_html__( 'Créditos', 'voicexpress' ) . ': <span id="voicexpress-credits">' . esc_html( $credits ? $credits : 0 ) . '</span><br/><br/>';
						echo 'Shortcode: <input readonly style="border:none;height:30px;padding:0 15px 0 15px;border-radius:5px;width:100%;" value=\'[voicexpress post_id="' . esc_html( $post_id ) . '"]\' /><br/><br/>';
						echo '<label style="display:block;margin-bottom:15px;"><input ' . checked( 1, $gerar_audio, false ) . ' type="checkbox" name="_voicexpress_gerar_audio" value="1" /> Gerar áudio</label>';
						echo do_shortcode( "[voicexpress post_id='" . esc_html( $post_id ) . "']" );
						echo '<a class="button button-large button-primary" style="width:100%;background:#111;text-align:center;border:none;" href="' . esc_html( $this->app_url ) . '?source=' . esc_html( get_home_url( ) ) . '" target="_blank">' . esc_html__( 'Adicionar créditos', 'voicexpress' ) . '</a>';

						// Player já é inicializado pelos scripts do frontend se personalizado estiver ativado
					},
					'post',
					'side',
					'default'
				);
			}
		);

		add_action(
			'admin_head',
			function () {
				if ( empty( get_option( 'voicexpress_secret_key', '' ) ) ) {
					$this->voicexpress_install( );
				}
				?>
				<style>
					/* Limitar tamanho do ícone do menu VoiceXpress */
					#adminmenu .wp-menu-image img[src*="voicexpress.app/favicon.png"] {
						width: 20px !important;
						height: 20px !important;
						max-width: 20px !important;
						max-height: 20px !important;
					}
					
					/* Ajustar posicionamento do ícone no menu */
					#adminmenu .menu-icon-generic img[src*="voicexpress.app/favicon.png"] {
						width: 20px !important;
						height: 20px !important;
						max-width: 20px !important;
						max-height: 20px !important;
						object-fit: contain;
					}
				</style>
				<?php
			}
		);

		add_action( 'admin_menu', array( $this, 'voicexpress_admin_menu' ) );

		add_action( 'admin_init', array( $this, 'voicexpress_register_settings' ) );

		// Hook para deletar áudio quando post for excluído
		add_action( 'before_delete_post', array( $this, 'voicexpress_delete_audio_on_post_delete' ) );

		// Hook para adicionar RSS do podcast no head
		add_action( 'wp_head', array( $this, 'voicexpress_add_podcast_rss_head' ) );
	}

	/**
	 * Settings
	 *
	 * @return void
	 */
	public function voicexpress_register_settings() {
		register_setting( 'voicexpress-settings', 'voicexpress_crontab' );
		register_setting( 'voicexpress-settings', 'voicexpress_auto' );
		register_setting( 'voicexpress-settings', 'voicexpress_player' );
		register_setting( 'voicexpress-settings', 'voicexpress_theme' );
		register_setting( 'voicexpress-settings', 'voicexpress_hide_text' );
		register_setting( 'voicexpress-settings', 'voicexpress_hide_download' );
		register_setting( 'voicexpress-settings', 'voicexpress_single_start' );
		register_setting( 'voicexpress-settings', 'voicexpress_single_end' );
		register_setting( 'voicexpress-settings', 'voicexpress_podcast_rss' );
		register_setting( 'voicexpress-settings', 'voicexpress_podcast_title' );
		register_setting( 'voicexpress-settings', 'voicexpress_podcast_description' );
		register_setting( 'voicexpress-settings', 'voicexpress_promo_code' );
		register_setting( 'voicexpress-settings', 'voicexpress_promo_code_used' );

		// Configurações de cache para cada plugin detectado
		$cache_plugins = $this->get_detected_cache_plugins();
		foreach ( $cache_plugins as $plugin_key => $plugin_data ) {
			register_setting( 'voicexpress-settings', 'voicexpress_cache_' . $plugin_key );
		}

		add_settings_section(
			'voicexpress_general_settings',
			'Configurações Gerais',
			array( $this, 'voicexpress_general_settings_callback' ),
			'voicexpress-settings'
		);

		add_settings_field(
			'voicexpress_position',
			'Posição do player',
			array( $this, 'voicexpress_position_callback' ),
			'voicexpress-settings',
			'voicexpress_general_settings'
		);

		add_settings_field(
			'voicexpress_css',
			'Personalizar player',
			array( $this, 'voicexpress_player_callback' ),
			'voicexpress-settings',
			'voicexpress_general_settings'
		);

		add_settings_field(
			'voicexpress_auto',
			'Gerar áudio automaticamente',
			array( $this, 'voicexpress_auto_callback' ),
			'voicexpress-settings',
			'voicexpress_general_settings'
		);

		add_settings_field(
			'voicexpress_crontab',
			'Usar cron para gerar áudios',
			array( $this, 'voicexpress_crontab_callback' ),
			'voicexpress-settings',
			'voicexpress_general_settings'
		);

		add_settings_field(
			'voicexpress_podcast_rss',
			'RSS Feed do Podcast',
			array( $this, 'voicexpress_podcast_rss_callback' ),
			'voicexpress-settings',
			'voicexpress_general_settings'
		);

		add_settings_field(
			'voicexpress_podcast_title',
			'Título do Podcast',
			array( $this, 'voicexpress_podcast_title_callback' ),
			'voicexpress-settings',
			'voicexpress_general_settings'
		);

		add_settings_field(
			'voicexpress_podcast_description',
			'Descrição do Podcast',
			array( $this, 'voicexpress_podcast_description_callback' ),
			'voicexpress-settings',
			'voicexpress_general_settings'
		);

		add_settings_field(
			'voicexpress_promo_code',
			'Código Promocional',
			array( $this, 'voicexpress_promo_code_callback' ),
			'voicexpress-settings',
			'voicexpress_general_settings'
		);

		// Seção de configurações de cache
		$cache_plugins = $this->get_detected_cache_plugins();
		if ( ! empty( $cache_plugins ) ) {
			add_settings_section(
				'voicexpress_cache_settings',
				'Configurações de Limpeza de Cache',
				array( $this, 'voicexpress_cache_settings_callback' ),
				'voicexpress-settings'
			);

			foreach ( $cache_plugins as $plugin_key => $plugin_data ) {
				add_settings_field(
					'voicexpress_cache_' . $plugin_key,
					$plugin_data['name'],
					array( $this, 'voicexpress_cache_plugin_callback' ),
					'voicexpress-settings',
					'voicexpress_cache_settings',
					array( 'plugin_key' => $plugin_key, 'plugin_data' => $plugin_data )
				);
			}
		}
	}

	/**
	 * Admin menu
	 *
	 * @return void
	 */
	public function voicexpress_admin_menu() {
		// Adicionar menu principal
		add_menu_page(
			'VoiceXpress',
			'VoiceXpress',
			'manage_options',
			'voicexpress',
			array( $this, 'voicexpress_render_main_page' ),
			'https://voicexpress.app/favicon.png',
			30
		);

		// Submenu: Configurações
		add_submenu_page(
			'voicexpress',
			'Configurações - VoiceXpress',
			'Configurações',
			'manage_options',
			'voicexpress-settings',
			array( $this, 'voicexpress_render_settings_page' )
		);

		// Submenu: Áudios
		add_submenu_page(
			'voicexpress',
			'Áudios - VoiceXpress',
			'Áudios',
			'manage_options',
			'voicexpress-audios',
			array( $this, 'voicexpress_render_audios_page' )
		);

		// Submenu: Recarga
		add_submenu_page(
			'voicexpress',
			'Recarga - VoiceXpress',
			'Recarga',
			'manage_options',
			'voicexpress-recarga',
			array( $this, 'voicexpress_render_recarga_page' )
		);

		// Remover o primeiro submenu duplicado (WordPress adiciona automaticamente)
		remove_submenu_page( 'voicexpress', 'voicexpress' );
	}

	/**
	 * Render main page
	 *
	 * @return void
	 */
	public function voicexpress_render_main_page() {
		?>
		<div class="wrap">
			<h1><img src="https://voicexpress.app/favicon.png" style="width: 24px; height: 24px; vertical-align: middle; margin-right: 8px;" />VoiceXpress</h1>
			<p>Bem-vindo ao painel administrativo do VoiceXpress! Use o menu ao lado para navegar pelas funcionalidades.</p>
			
			<div class="dashboard-widgets-wrap">
				<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 20px;">
					<div class="postbox">
						<h2 class="hndle">📊 Estatísticas</h2>
						<div class="inside">
							<?php
							$total_posts = wp_count_posts('post')->publish;
							$posts_with_audio = get_posts(array(
								'post_type' => 'post',
								'meta_query' => array(
									array(
										'key' => '_voicexpress_audio',
										'compare' => 'EXISTS'
									)
								),
								'fields' => 'ids',
								'numberposts' => -1
							));
							$audio_count = count($posts_with_audio);
							$credits = $this->get_credits();
							?>
							<p><strong>Total de Posts:</strong> <?php echo $total_posts; ?></p>
							<p><strong>Posts com Áudio:</strong> <?php echo $audio_count; ?></p>
							<p><strong>Créditos Disponíveis:</strong> <?php echo $credits; ?></p>
							<p><strong>Taxa de Conversão:</strong> <?php echo $total_posts > 0 ? round(($audio_count / $total_posts) * 100, 1) : 0; ?>%</p>
						</div>
					</div>
					
					<div class="postbox">
						<h2 class="hndle">🔗 Links Úteis</h2>
						<div class="inside">
							<p><a href="<?php echo admin_url('admin.php?page=voicexpress-settings'); ?>" class="button">⚙️ Configurações</a></p>
							<p><a href="<?php echo admin_url('admin.php?page=voicexpress-audios'); ?>" class="button">🎵 Gerenciar Áudios</a></p>
							<p><a href="<?php echo admin_url('admin.php?page=voicexpress-recarga'); ?>" class="button">💳 Recarga de Créditos</a></p>
							<p><a href="https://voicexpress.app" target="_blank" class="button button-primary">🌐 Acessar VoiceXpress</a></p>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Settings page render
	 *
	 * @return void
	 */
	public function voicexpress_render_settings_page() {
		if(!get_option('_voicexpress_affiliate_code')) {
			$site_key = get_option('voicexpress_secret_key');
			$req = wp_remote_get("{$this->app_url}/site/{$site_key}/affiliate-code");
			if(!is_wp_error($req) && wp_remote_retrieve_response_code($req) == 200) {
				$affiliate_code = trim(wp_remote_retrieve_body($req));
				if($affiliate_code && strlen($affiliate_code) == 10) {
					update_option('_voicexpress_affiliate_code', $affiliate_code);
					$this->affiliate_link = "{$this->app_url}?aff={$affiliate_code}";
				}
			}
		}
		?>
		<div class="wrap">
			<h1><img src="https://voicexpress.app/favicon.png" style="width: 24px; height: 24px; vertical-align: middle; margin-right: 8px;" /><?php echo esc_html__( 'Configurações do VoiceXpress', 'voicexpress' ); ?></h1>
			<form method="post" action="options.php">
				<?php
				settings_fields( 'voicexpress-settings' );
				do_settings_sections( 'voicexpress-settings' );
				submit_button( );
				?>
			</form>
		</div>
		<?php
	}

	/**
	 * Audios page render
	 *
	 * @return void
	 */
	public function voicexpress_render_audios_page() {
		// Processar ações
		if (isset($_POST['action']) && $_POST['action'] === 'delete_audio' && isset($_POST['post_id'])) {
			$this->voicexpress_delete_audio($_POST['post_id']);
		}

		?>
		<div class="wrap">
			<h1><img src="https://voicexpress.app/favicon.png" style="width: 24px; height: 24px; vertical-align: middle; margin-right: 8px;" />Gerenciar Áudios</h1>
			
			<!-- Formulário de busca -->
			<div style="margin: 20px 0;">
				<form method="get" style="display: flex; gap: 10px; align-items: center;">
					<input type="hidden" name="page" value="voicexpress-audios" />
					<input type="text" name="search" placeholder="Buscar por título..." value="<?php echo esc_attr($_GET['search'] ?? ''); ?>" style="width: 300px;" />
					<input type="submit" class="button" value="Buscar" />
					<?php if (!empty($_GET['search'])): ?>
						<a href="<?php echo admin_url('admin.php?page=voicexpress-audios'); ?>" class="button">Limpar</a>
					<?php endif; ?>
				</form>
			</div>

			<?php
			// Buscar posts com áudio
			$search = $_GET['search'] ?? '';
			$paged = $_GET['paged'] ?? 1;
			
			$args = array(
				'post_type' => 'post',
				'posts_per_page' => 20,
				'paged' => $paged,
				'meta_query' => array(
					array(
						'key' => '_voicexpress_audio',
						'compare' => 'EXISTS'
					)
				)
			);

			if (!empty($search)) {
				$args['s'] = $search;
			}

			$posts = get_posts($args);
			$total_posts = wp_count_posts('post')->publish;
			?>

			<div class="tablenav top">
				<div class="alignleft actions">
					<span class="displaying-num"><?php echo count($posts); ?> itens</span>
				</div>
			</div>

			<table class="wp-list-table widefat fixed striped posts">
				<thead>
					<tr>
						<th scope="col">Título</th>
						<th scope="col">Data</th>
						<th scope="col">Status do Áudio</th>
						<th scope="col">Ações</th>
					</tr>
				</thead>
				<tbody>
					<?php if (empty($posts)): ?>
						<tr>
							<td colspan="4" style="text-align: center; padding: 20px;">
								<?php if (!empty($search)): ?>
									Nenhum áudio encontrado para "<?php echo esc_html($search); ?>".
								<?php else: ?>
									Nenhum post com áudio encontrado.
								<?php endif; ?>
							</td>
						</tr>
					<?php else: ?>
						<?php foreach ($posts as $post): ?>
							<?php
							$audio_version = get_post_meta($post->ID, '_voicexpress_audio', true);
							$audio_url = !empty($audio_version) ? 'https://cdn.voicexpress.app/audios/' . $audio_version . '.mp3' : '';
							?>
							<tr>
								<td>
									<strong><a href="<?php echo get_edit_post_link($post->ID); ?>"><?php echo esc_html($post->post_title); ?></a></strong>
									<div style="margin-top: 5px; font-size: 12px; color: #666;">
										ID: <?php echo $post->ID; ?> | 
										<a href="<?php echo get_permalink($post->ID); ?>" target="_blank">Ver Post</a>
									</div>
								</td>
								<td><?php echo get_the_date('d/m/Y H:i', $post->ID); ?></td>
								<td>
									<?php if (!empty($audio_version) && $audio_version !== 'Compre mais créditos'): ?>
										<span style="color: green;">✓ Áudio Gerado</span>
										<br><small><?php echo esc_html($audio_version); ?></small>
									<?php else: ?>
										<span style="color: red;">✗ Sem Áudio</span>
									<?php endif; ?>
								</td>
								<td>
									<?php if (!empty($audio_version) && $audio_version !== 'Compre mais créditos'): ?>
										<a href="<?php echo $audio_url; ?>" target="_blank" class="button button-small">🎵 Ouvir</a>
										<a href="<?php echo $audio_url; ?>" download class="button button-small">📥 Download</a>
										<form method="post" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja deletar este áudio?');">
											<input type="hidden" name="action" value="delete_audio" />
											<input type="hidden" name="post_id" value="<?php echo $post->ID; ?>" />
											<input type="submit" class="button button-small" value="🗑️ Deletar" style="color: red;" />
										</form>
									<?php else: ?>
										<a href="<?php echo admin_url('post.php?post=' . $post->ID . '&action=edit'); ?>" class="button button-small">📝 Editar Post</a>
									<?php endif; ?>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php endif; ?>
				</tbody>
			</table>

			<?php
			// Paginação simples
			$total_pages = ceil($total_posts / 20);
			if ($total_pages > 1):
			?>
			<div class="tablenav bottom">
				<div class="tablenav-pages">
					<?php for ($i = 1; $i <= min($total_pages, 10); $i++): ?>
						<?php if ($i == $paged): ?>
							<span class="page-numbers current"><?php echo $i; ?></span>
						<?php else: ?>
							<a class="page-numbers" href="<?php echo add_query_arg('paged', $i); ?>"><?php echo $i; ?></a>
						<?php endif; ?>
					<?php endfor; ?>
				</div>
			</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Recarga page render
	 *
	 * @return void
	 */
	public function voicexpress_render_recarga_page() {
		$credits = $this->get_credits();
		?>
		<div class="wrap">
			<h1><img src="https://voicexpress.app/favicon.png" style="width: 24px; height: 24px; vertical-align: middle; margin-right: 8px;" />Recarga de Créditos</h1>
			
			<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 20px;">
				<div class="postbox">
					<h2 class="hndle">💰 Seus Créditos</h2>
					<div class="inside">
						<p style="font-size: 24px; margin: 10px 0;"><strong><?php echo $credits; ?> créditos disponíveis</strong></p>
						<p>Cada conversão de texto para áudio custa 1 crédito.</p>
						<hr>
						<p><strong>Preço por crédito:</strong> R$ 1,00</p>
						<p><strong>Pacotes sugeridos:</strong></p>
						<ul>
							<li>100 créditos = R$ 100,00</li>
							<li>1.000 créditos = R$ 1.000,00</li>
							<li>10.000 créditos = R$ 10.000,00</li>
						</ul>
					</div>
				</div>

				<div class="postbox">
					<h2 class="hndle">🛒 Como Recarregar</h2>
					<div class="inside">
						<p><strong>1. Acesse o VoiceXpress:</strong></p>
						<p><a href="https://voicexpress.app/recarga" target="_blank" class="button button-primary">🌐 Fazer Recarga Online</a></p>
						
						<hr>
						
						<p><strong>2. Entre na sua conta:</strong></p>
						<p>Use as mesmas credenciais do seu site WordPress.</p>
						
						<hr>
						
						<p><strong>3. Escolha o valor:</strong></p>
						<p>Selecione a quantidade de créditos desejada e efetue o pagamento.</p>
						
						<hr>
						
						<p><strong>4. Pronto!</strong></p>
						<p>Os créditos serão adicionados automaticamente à sua conta.</p>
					</div>
				</div>
			</div>

			<div class="postbox" style="margin-top: 20px;">
				<h2 class="hndle">📊 Histórico de Uso</h2>
				<div class="inside">
					<?php
					// Buscar posts com áudio para mostrar estatísticas
					$posts_with_audio = get_posts(array(
						'post_type' => 'post',
						'meta_query' => array(
							array(
								'key' => '_voicexpress_audio',
								'compare' => 'EXISTS'
							)
						),
						'fields' => 'ids',
						'numberposts' => -1
					));
					$audio_count = count($posts_with_audio);
					$total_posts = wp_count_posts('post')->publish;
					?>
					<p><strong>Total de áudios gerados:</strong> <?php echo $audio_count; ?></p>
					<p><strong>Total de posts:</strong> <?php echo $total_posts; ?></p>
					<p><strong>Taxa de conversão:</strong> <?php echo $total_posts > 0 ? round(($audio_count / $total_posts) * 100, 1) : 0; ?>%</p>
					
					<?php if ($audio_count > 0): ?>
						<p><em>Você já economizou tempo convertendo <?php echo $audio_count; ?> posts em áudio!</em></p>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Delete audio function
	 *
	 * @param int $post_id
	 * @return void
	 */
	private function voicexpress_delete_audio($post_id) {
		$audio_version = get_post_meta($post_id, '_voicexpress_audio', true);
		
		if (empty($audio_version)) {
			add_action('admin_notices', function() {
				echo '<div class="notice notice-error"><p>Erro: Post não possui áudio para deletar.</p></div>';
			});
			return;
		}

		// Chamar API para deletar o áudio
		$domain = str_replace(array('http://', 'https://', 'www.'), '', home_url());
		$domain = rtrim($domain, '/');
		$site_key = get_option('voicexpress_secret_key', '');
		
		$response = wp_remote_post($this->app_url . '/api/delete-audio', array(
			'body' => array(
				'domain' => $domain,
				'audio_version' => $audio_version,
				'post_id' => $post_id,
				'site_key' => $site_key
			),
			'timeout' => 30
		));

		if (is_wp_error($response)) {
			add_action('admin_notices', function() use ($response) {
				echo '<div class="notice notice-error"><p>Erro ao conectar com a API: ' . $response->get_error_message() . '</p></div>';
			});
			return;
		}

		$body = wp_remote_retrieve_body($response);
		$data = json_decode($body, true);

		if (isset($data['success']) && $data['success']) {
			// Remover meta do post
			delete_post_meta($post_id, '_voicexpress_audio');
			
			add_action('admin_notices', function() {
				echo '<div class="notice notice-success"><p>Áudio deletado com sucesso!</p></div>';
			});
		} else {
			$error_message = isset($data['message']) ? $data['message'] : 'Erro desconhecido';
			add_action('admin_notices', function() use ($error_message) {
				echo '<div class="notice notice-error"><p>Erro ao deletar áudio: ' . esc_html($error_message) . '</p></div>';
			});
		}
	}

	/**
	 * Delete audio when post is deleted
	 *
	 * @param int $post_id
	 * @return void
	 */
	public function voicexpress_delete_audio_on_post_delete($post_id) {
		// Verificar se é um post (não página, attachment, etc.)
		if (get_post_type($post_id) !== 'post') {
			return;
		}

		// Verificar se o post tem áudio
		$audio_version = get_post_meta($post_id, '_voicexpress_audio', true);
		
		if (empty($audio_version) || $audio_version === 'Compre mais créditos') {
			return; // Post não tem áudio válido
		}

		// Chamar a função de deletar áudio silenciosamente (sem admin notices)
		$domain = str_replace(array('http://', 'https://', 'www.'), '', home_url());
		$domain = rtrim($domain, '/');
		$site_key = get_option('voicexpress_secret_key', '');
		
		// Fazer requisição para API de forma assíncrona para não atrasar a exclusão do post
		wp_remote_post($this->app_url . '/api/delete-audio', array(
			'body' => array(
				'domain' => $domain,
				'audio_version' => $audio_version,
				'post_id' => $post_id,
				'site_key' => $site_key
			),
			'timeout' => 5, // Timeout reduzido para não atrasar
			'blocking' => false // Requisição assíncrona
		));

		// Remover meta do post independente da resposta da API
		delete_post_meta($post_id, '_voicexpress_audio');
	}

	/**
	 * Helptext
	 *
	 * @return void
	 */
	public function voicexpress_general_settings_callback( ) {
		echo '<p>' . esc_html__( 'Configure as opções gerais do Voicexpress', 'voicexpress' ) . '</p>';
		echo '<p>Shortcode: [voicexpress post_id="123"]</p><br/>';
		$key = get_option( 'voicexpress_secret_key', '' );
		if ( ! get_option( 'voicexpress_account_connected' ) ) {
			echo '<a class="button button-success" target="_blank" href="https://voicexpress.app/sites/' . esc_attr( $key ) . '/connect?vx_return_url=' . urlencode( admin_url( 'admin-ajax.php?action=voicexpress_connected&key=' . $key ) ) . '">conectar site a sua conta</a><br/>';
		} else {
			echo '<strong style="color: green;">Site conectado! Clique aqui para mudar a conta conectada</strong><br/>';
			echo '<br/>';
			echo '<a class="button button-success" target="_blank" href="https://voicexpress.app/sites/' . esc_attr( $key ) . '/connect?vx_return_url=' . urlencode( admin_url( 'admin-ajax.php?action=voicexpress_connected&key=' . $key ) ) . '">conectar site em outra conta</a><br/>';
		}
	}

	/**
	 * Save options
	 *
	 * @return void
	 */
	public function voicexpress_position_callback( ) {
		$voicexpress_single_start   = get_option( 'voicexpress_single_start', 1 );
		$voicexpress_single_end     = get_option( 'voicexpress_single_end', 0 );
		?>
		<label>
			<input type="checkbox" name="voicexpress_single_start" value="1" <?php checked( $voicexpress_single_start, 1 ); ?> />
			<?php echo esc_html__( 'Antes do texto', 'voicexpress' ); ?>
		</label><br/>
		<label>
			<input type="checkbox" name="voicexpress_single_end" value="1" <?php checked( $voicexpress_single_end, 1 ); ?> />
			<?php echo esc_html__( 'Depois do texto', 'voicexpress' ); ?>
		</label>
		<?php
	}

	public function get_audio_url( ) {
		return VOICEXPRESS_PLUGIN_URL . 'example-1.mp3';
	}

	public function voicexpress_resetar_css( ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'Acesso negado' );
		}
		update_option( 'voicexpress_css', file_get_contents( VOICEXPRESS_ASSETS_PATH . 'skins/green-audio-player/css/green-audio-player.css' ) );
		wp_redirect( admin_url( 'options-general.php?page=voicexpress-settings' ) );
		exit;
	}

	public function voicexpress_player_callback( ) {
		$voicexpress_player = get_option( 'voicexpress_player', 0 );
		$voicexpress_theme = get_option( 'voicexpress_theme', 'light' );
		$hide_download = get_option( 'voicexpress_hide_download', 0 );
		$hide_text = get_option( 'voicexpress_hide_text', 0 );
		?>
		<label>
			<input onchange="document.querySelector('#customplayer').style.display = this.checked ? 'block' : 'none'" type="checkbox" name="voicexpress_player" value="1" <?php checked( $voicexpress_player, 1 ); ?> /> Usar player customizado VoiceXpress
		</label><br/><br/>
		<div id="customplayer" style="display: <?php echo $voicexpress_player ? 'block' : 'none'; ?>;">
			<h4>Tema do Player:</h4>
			<select onchange="VoicexpressPlayers[0].setTheme(this.value)" name="voicexpress_theme" onchange="updatePlayerPreview(this.value)">
				<option value="light" <?php selected( $voicexpress_theme, 'light' ); ?>>Light - Claro</option>
				<option value="dark" <?php selected( $voicexpress_theme, 'dark' ); ?>>Dark - Escuro</option>
				<option value="gray" <?php selected( $voicexpress_theme, 'gray' ); ?>>Gray - Cinza</option>
				<option value="red" <?php selected( $voicexpress_theme, 'red' ); ?>>Red - Vermelho</option>
				<option value="green" <?php selected( $voicexpress_theme, 'green' ); ?>>Green - Verde</option>
				<option value="blue" <?php selected( $voicexpress_theme, 'blue' ); ?>>Blue - Azul</option>
			</select>
			<br/><br/>
		<label>
			<input type="checkbox" onchange="VoicexpressPlayers[0].setShowDownload(!this.checked)" name="voicexpress_hide_download" value="1" <?php checked( $hide_download, 1 ); ?> /> Ocultar botão de download
		</label>
			<br/><br/>
		<label>
			<input type="checkbox" name="voicexpress_hide_text" onchange="VoicexpressPlayers[0].setShowRead(!this.checked)" value="1" <?php checked( $hide_text, 1 ); ?> /> Ocultar texto "Ouça o texto"
		</label>
			<br/><br/>
			
			<h4>Pré-visualização:</h4>
			<div data-voicexpress data-theme="gray" class="voicexpress voicexpress-single-start voicexpress-default"><audio controls><source src="https://cdn.voicexpress.app/audios/2486bd848f11d6136538ac497d115da0-462382741759690698.mp3" type="audio/mpeg"></audio><a class="voicexpress-copyright" href="https://voicexpress.app" target="_blank" title="Voicexpress">audio by <strong>Voicexpress</strong></a></div>
		</div>
		<?php
	}

	/**
	 * Autogenerate audios
	 *
	 * @return void
	 */
	public function voicexpress_crontab_callback( ) {
		$cron = get_option( 'voicexpress_crontab', 1 );
		?>
		<label>
			<input type="checkbox" name="voicexpress_crontab" value="1" <?php checked( $cron, 1 ); ?> />
		</label>
		<?php
	}

	/**
	 * Autogenerate audios
	 *
	 * @return void
	 */
	public function voicexpress_auto_callback() {
		$auto = get_option( 'voicexpress_auto', 1 );
		?>
		<label>
			<input type="checkbox" name="voicexpress_auto" value="1" <?php checked( $auto, 1 ); ?> />
		</label>
		<?php
	}

	/**
	 * RSS Feed do Podcast
	 *
	 * @return void
	 */
	public function voicexpress_podcast_rss_callback() {
		$rss_enabled = get_option( 'voicexpress_podcast_rss', 0 );
		$domain = str_replace( array( 'http://', 'https://', 'www.' ), '', home_url() );
		$domain = rtrim( $domain, '/' );
		?>
		<label>
			<input type="checkbox" name="voicexpress_podcast_rss" value="1" <?php checked( $rss_enabled, 1 ); ?> />
			<?php echo esc_html__( 'Adicionar link RSS do podcast no head do site', 'voicexpress' ); ?>
		</label>
		<p class="description">
			<?php echo esc_html__( 'Quando habilitado, adiciona automaticamente o link para o RSS feed do podcast no cabeçalho do site.', 'voicexpress' ); ?><br/>
			<strong>URL do RSS:</strong> <code>https://voicexpress.app/podcast/<?php echo esc_html( $domain ); ?>/rss</code>
		</p>
		<?php
	}

	/**
	 * Callback para o campo título do podcast
	 *
	 * @return void
	 */
	public function voicexpress_podcast_title_callback() {
		$podcast_title = get_option( 'voicexpress_podcast_title', '' );
		$site_name = get_bloginfo( 'name' );
		$placeholder = ! empty( $site_name ) ? $site_name : 'Nome do seu podcast';
		?>
		<input type="text" 
			   name="voicexpress_podcast_title" 
			   value="<?php echo esc_attr( $podcast_title ); ?>" 
			   placeholder="<?php echo esc_attr( $placeholder ); ?>"
			   class="regular-text" />
		<p class="description">
			<?php echo esc_html__( 'Título personalizado para o podcast. Se deixar em branco, será usado o nome do site.', 'voicexpress' ); ?>
		</p>
		<?php
	}

	/**
	 * Callback para o campo descrição do podcast
	 *
	 * @return void
	 */
	public function voicexpress_podcast_description_callback() {
		$podcast_description = get_option( 'voicexpress_podcast_description', '' );
		$site_description = get_bloginfo( 'description' );
		$placeholder = ! empty( $site_description ) ? $site_description : 'Descrição do seu podcast';
		?>
		<textarea name="voicexpress_podcast_description" 
				  placeholder="<?php echo esc_attr( $placeholder ); ?>"
				  class="large-text" 
				  rows="3"><?php echo esc_textarea( $podcast_description ); ?></textarea>
		<p class="description">
			<?php echo esc_html__( 'Descrição personalizada para o podcast. Se deixar em branco, será usada a descrição do site.', 'voicexpress' ); ?>
		</p>
		<?php
	}

	/**
	 * Adiciona o link RSS do podcast no head do site
	 */
	public function voicexpress_add_podcast_rss_head() {
		// Verifica se a opção está habilitada
		if ( ! get_option( 'voicexpress_podcast_rss' ) ) {
			return;
		}

		// Obtém o domínio do site
		$domain = str_replace( array( 'http://', 'https://', 'www.' ), '', home_url() );
		$domain = rtrim( $domain, '/' );
		
		if ( $domain ) {
			$rss_url = 'https://voicexpress.app/podcast/' . $domain . '/rss';
			echo '<link rel="alternate" type="application/rss+xml" title="Podcast RSS Feed" href="' . esc_url( $rss_url ) . '" />' . "\n";
		}
	}

	/**
	 * Install sitein API
	 *
	 * @return void
	 */
	public function voicexpress_install( ) {
		$req = wp_remote_request(
			$this->app_url . '/install/',
			array(
				'sslverify' => false,
				'timeout'   => 10,
				'method'    => 'POST',
				'body'      => wp_json_encode( array( 'url' => home_url( ) ) ),
				'headers'   => array(
					'Content-Type' => 'application/json',
				),
			)
		);
		$res = wp_remote_retrieve_body( $req );

		if ( is_wp_error( $req ) ) {
			return;
		}

		$status_code = wp_remote_retrieve_response_code( $req );

		if ( $status_code < 200 || $status_code >= 300 ) {
			return;
		}

		update_option( 'voicexpress_secret_key', $res );
		$this->get_credits( );
	}

	/**
	 * Send post data to API
	 *
	 * @param  int  $post_id ID do post.
	 * @param  bool $force Forçar atualização mesmo que o conteúdo não tenha sido alterado.
	 * @return void
	 */
	public function voicexpress_send_post( $post_id, $force = false ) {
		$post = get_post( $post_id );
		if( $force == false ) {
			if ( 'publish' != $post->post_status ) {
				return;
			}
			if ( get_post_meta( $post_id, '_voicexpress_gerar_audio', true )) {
				return;
			}
		}
		$voicexpress_url      = $this->app_url . '/insert/';
		$content              = get_post_field( 'post_content', $post_id );
		$content_without_html = trim( strip_shortcodes( wp_strip_all_tags( html_entity_decode( $content ), true ) ) );

		if ( empty( $content_without_html ) ) {
			return;
		}
		$credits = get_option( 'voicexpress_credits' );

		if ( empty( $credits ) || 0 == $credits ) {
			$this->get_credits( );
			$credits = get_option( 'voicexpress_credits' );
			if ( empty( $credits ) || 0 == $credits ) {
				return;
			}
		}

		$secret_key = get_option( 'voicexpress_secret_key', '' );
		$data       = array(
			'notification_url' => admin_url( "admin-ajax.php?action=voicexpress_notification&post_id={$post_id}&key={$secret_key}" ),
			'post_id'          => $post_id,
			'url'              => get_permalink( $post_id ),
			'title'            => get_the_title( $post_id ),
			'content'          => $content_without_html,
			'image'            => get_the_post_thumbnail_url( $post_id ),
			'categories'       => array_map(
				function ( $cat ) {
					return $cat->name;
				},
				get_the_category( $post_id )
			),
		);

		$hash = get_post_meta( $post_id, 'voicexpress_hash', 1 );

		$content_hashed = preg_replace( "/[\s\r\n\t ]+/", '', html_entity_decode( $data['content'] ) );

		if ( md5( $content_hashed ) == $hash && ! $force ) {
			return;
		}

		update_post_meta( $post_id, 'voicexpress_hash', md5( $content_hashed ) );

		$req = wp_remote_request(
			$voicexpress_url,
			array(
				'sslverify' => false,
				'timeout'   => 10,
				'method'    => 'POST',
				'body'      => wp_json_encode( $data ),
				'headers'   => array(
					'Content-Type' => 'application/json',
					'X-Api-Key'    => $secret_key,
				),
			)
		);
		$res = wp_remote_retrieve_body( $req );

		if ( is_wp_error( $req ) ) {
			return;
		}

		$status_code = wp_remote_retrieve_response_code( $req );

		if ( $status_code < 200 || $status_code >= 300 ) {
			return;
		}

		update_post_meta( $post_id, '_voicexpress_audio', $res );
		update_post_meta( $post_id, 'voicexpress_sent', 1 );
		$this->get_credits( );
	}

	/**
	 * Recebe notificações da API
	 *
	 * @return void
	 */
	public function voicexpress_notification( ) {
		if ( ! isset( $_GET['key'] ) || get_option( 'voicexpress_secret_key', '' ) != $_GET['key'] ) {
			wp_send_json_error( );
		}

		$audio_key = isset( $_GET['audio_key'] ) ? sanitize_text_field( wp_unslash( $_GET['audio_key'] ) ) : '';
		$post_id   = isset( $_GET['post_id'] ) ? intval( $_GET['post_id'] ) : 0;

		if ( ! $audio_key || ! $post_id ) {
			wp_send_json_error([ 'message' => 'Invalid audio key or post ID' ] );
		}

		update_post_meta( $post_id, '_voicexpress_audio', $audio_key );
		
		// Limpar cache do WP Rocket quando áudio for atualizado
		$this->clear_wp_rocket_cache( $post_id );
		
		wp_send_json_success( );
	}

	/**
	 * Get detected cache plugins and their information
	 *
	 * @return array
	 */
	public function get_detected_cache_plugins() {
		$cache_plugins = array();

		// WP Rocket
		if ( function_exists( 'rocket_clean_post' ) || defined( 'WP_ROCKET_VERSION' ) ) {
			$cache_plugins['wp_rocket'] = array(
				'name' => 'WP Rocket',
				'description' => 'Plugin de cache premium com funcionalidades avançadas',
				'functions' => array( 'rocket_clean_post', 'rocket_clean_files', 'rocket_clean_minify' )
			);
		}

		// W3 Total Cache
		if ( function_exists( 'w3tc_flush_post' ) || defined( 'W3TC_VERSION' ) ) {
			$cache_plugins['w3tc'] = array(
				'name' => 'W3 Total Cache',
				'description' => 'Plugin gratuito de cache com múltiplas funcionalidades',
				'functions' => array( 'w3tc_flush_post' )
			);
		}

		// WP Super Cache
		if ( function_exists( 'wp_cache_post_change' ) || defined( 'WPCACHEHOME' ) ) {
			$cache_plugins['wp_super_cache'] = array(
				'name' => 'WP Super Cache',
				'description' => 'Plugin simples e eficiente de cache estático',
				'functions' => array( 'wp_cache_post_change' )
			);
		}

		// LiteSpeed Cache
		if ( class_exists( 'LiteSpeed\Purge' ) || defined( 'LSCWP_V' ) ) {
			$cache_plugins['litespeed'] = array(
				'name' => 'LiteSpeed Cache',
				'description' => 'Cache otimizado para servidores LiteSpeed',
				'functions' => array( 'litespeed_purge_post' )
			);
		}

		// WP Fastest Cache
		if ( class_exists( 'WpFastestCache' ) ) {
			$cache_plugins['wp_fastest_cache'] = array(
				'name' => 'WP Fastest Cache',
				'description' => 'Plugin rápido e fácil de usar',
				'functions' => array( 'WpFastestCache::singleDeleteCache' )
			);
		}

		// Autoptimize
		if ( function_exists( 'autoptimize_flush_cache' ) || defined( 'AUTOPTIMIZE_PLUGIN_VERSION' ) ) {
			$cache_plugins['autoptimize'] = array(
				'name' => 'Autoptimize',
				'description' => 'Otimização de CSS, JS e HTML',
				'functions' => array( 'autoptimize_flush_cache' )
			);
		}

		// Cache Enabler
		if ( class_exists( 'Cache_Enabler' ) ) {
			$cache_plugins['cache_enabler'] = array(
				'name' => 'Cache Enabler',
				'description' => 'Plugin leve de cache estático',
				'functions' => array( 'Cache_Enabler::clear_page_cache_by_post_id' )
			);
		}

		// Hummingbird
		if ( class_exists( 'Hummingbird\WP_Hummingbird' ) ) {
			$cache_plugins['hummingbird'] = array(
				'name' => 'Hummingbird',
				'description' => 'Otimização de performance da WPMU DEV',
				'functions' => array( 'wphb_clear_page_cache' )
			);
		}

		// SG Optimizer
		if ( function_exists( 'sg_cachepress_purge_cache' ) ) {
			$cache_plugins['sg_optimizer'] = array(
				'name' => 'SG Optimizer',
				'description' => 'Plugin de cache da SiteGround',
				'functions' => array( 'sg_cachepress_purge_cache' )
			);
		}

		// Breeze
		if ( class_exists( 'Breeze_PurgeCache' ) ) {
			$cache_plugins['breeze'] = array(
				'name' => 'Breeze',
				'description' => 'Plugin de cache da Cloudways',
				'functions' => array( 'Breeze_PurgeCache::breeze_cache_flush_post' )
			);
		}

		return $cache_plugins;
	}

	/**
	 * Check if cache clearing is enabled for a specific plugin
	 *
	 * @param string $plugin_key
	 * @return bool
	 */
	private function is_cache_clearing_enabled( $plugin_key ) {
		return get_option( 'voicexpress_cache_' . $plugin_key, '1' ) === '1';
	}

	/**
	 * Clear cache from popular caching plugins when audio is updated
	 *
	 * @param int $post_id
	 * @return void
	 */
	private function clear_wp_rocket_cache( $post_id ) {
		$post_url = get_permalink( $post_id );
		$cleared_caches = array();

		// WP Rocket
		if ( $this->is_cache_clearing_enabled( 'wp_rocket' ) && function_exists( 'rocket_clean_post' ) ) {
			rocket_clean_post( $post_id );
			$cleared_caches[] = 'WP Rocket (post)';
		}

		if ( $this->is_cache_clearing_enabled( 'wp_rocket' ) && function_exists( 'rocket_clean_files' ) && $post_url ) {
			rocket_clean_files( array( $post_url ) );
			$cleared_caches[] = 'WP Rocket (files)';
		}

		// W3 Total Cache
		if ( $this->is_cache_clearing_enabled( 'w3tc' ) && function_exists( 'w3tc_flush_post' ) ) {
			w3tc_flush_post( $post_id );
			$cleared_caches[] = 'W3 Total Cache';
		}

		// WP Super Cache
		if ( $this->is_cache_clearing_enabled( 'wp_super_cache' ) && function_exists( 'wp_cache_post_change' ) ) {
			wp_cache_post_change( $post_id );
			$cleared_caches[] = 'WP Super Cache';
		}

		// LiteSpeed Cache
		if ( $this->is_cache_clearing_enabled( 'litespeed' ) && class_exists( 'LiteSpeed\Purge' ) ) {
			do_action( 'litespeed_purge_post', $post_id );
			$cleared_caches[] = 'LiteSpeed Cache';
		}

		// WP Fastest Cache
		if ( $this->is_cache_clearing_enabled( 'wp_fastest_cache' ) && class_exists( 'WpFastestCache' ) && method_exists( 'WpFastestCache', 'singleDeleteCache' ) ) {
			$wpfc = new \WpFastestCache();
			$wpfc->singleDeleteCache( false, $post_id );
			$cleared_caches[] = 'WP Fastest Cache';
		}

		// Cache Enabler
		if ( $this->is_cache_clearing_enabled( 'cache_enabler' ) && class_exists( 'Cache_Enabler' ) && method_exists( 'Cache_Enabler', 'clear_page_cache_by_post_id' ) ) {
			\Cache_Enabler::clear_page_cache_by_post( $post_id );
			$cleared_caches[] = 'Cache Enabler';
		}

		// Hummingbird
		if ( $this->is_cache_clearing_enabled( 'hummingbird' ) && class_exists( 'Hummingbird\WP_Hummingbird' ) ) {
			do_action( 'wphb_clear_page_cache', $post_id );
			$cleared_caches[] = 'Hummingbird';
		}

		// Breeze
		if ( $this->is_cache_clearing_enabled( 'breeze' ) && class_exists( 'Breeze_PurgeCache' ) && method_exists( 'Breeze_PurgeCache', 'breeze_cache_flush' ) ) {
			\Breeze_PurgeCache::breeze_cache_flush(true, true, true);
			$cleared_caches[] = 'Breeze';
		}

		// Log quais caches foram limpos (apenas em modo debug)
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG && ! empty( $cleared_caches ) ) {
			error_log( 'VoiceXpress: Cache cleared for post ' . $post_id . ' using: ' . implode( ', ', $cleared_caches ) );
		}

		// Hook personalizado para outros plugins
		do_action( 'voicexpress_cache_cleared', $post_id, $cleared_caches );
	}

	/**
	 * Recebe conexao da API
	 *
	 * @return void
	 */
	public function voicexpress_connected( ) {
		if ( ! isset( $_GET['key'] ) || get_option( 'voicexpress_secret_key', '' ) != $_GET['key'] ) {
			wp_send_json_error( );
		}

		update_option( 'voicexpress_account_connected', time( ) );

		wp_redirect( admin_url( 'options-general.php?page=voicexpress-settings&voicexpress_connected=1' ) );

		exit;
	}

	/**
	 * Recebe conexao da API
	 *
	 * @return void
	 */
	public function voicexpress_disconnected( ) {
		if ( ! isset( $_GET['key'] ) || get_option( 'voicexpress_secret_key', '' ) != $_GET['key'] ) {
			wp_send_json_error( );
		}

		delete_option( 'voicexpress_account_connected' );

		wp_redirect( admin_url( 'options-general.php?page=voicexpress-settings&voicexpress_connected=0' ) );

		exit;
	}

	/**
	 * Get credits for site
	 *
	 * @return int $credits Créditos disponíveis
	 */
	public function get_credits( ) {
		$url = $this->app_url . '/creditos/' . get_option( 'voicexpress_secret_key', '' );
		$req = wp_remote_request(
			$url,
			array(
				'sslverify' => false,
				'timeout'   => 10,
				'method'    => 'GET',
				'headers'   => array(
					'Content-Type' => 'application/json',
					'X-Api-Key'    => get_option( 'voicexpress_secret_key', '' ),
				),
			)
		);

		$credits = wp_remote_retrieve_body( $req );

		if ( is_wp_error( $req ) ) {
			return get_option( 'voicexpress_credits', true );
		}

		$status_code = wp_remote_retrieve_response_code( $req );

		if ( $status_code < 200 || $status_code >= 300 ) {
			return get_option( 'voicexpress_credits', true );
		}

		update_option( 'voicexpress_credits', intval( $credits ) );
		return (int) $credits;
	}

	/**
	 * Callback para campo de código promocional
	 *
	 * @return void
	 */
	public function voicexpress_promo_code_callback() {
		$promo_code = get_option('voicexpress_promo_code', '');
		$promo_used = get_option('voicexpress_promo_code_used', 0);
		
		if ($promo_used) {
			echo '<p style="color: green; font-weight: bold;">✓ Código promocional já foi aplicado com sucesso!</p>';
			echo '<p><small>Você já recebeu os créditos bônus por usar um código promocional.</small></p>';
		} else {
			?>
			<div>
				<input type="text" 
					   name="voicexpress_promo_code" 
					   value="<?php echo esc_attr($promo_code); ?>" 
					   placeholder="Digite o código promocional"
					   maxlength="20"
					   style="width: 300px;" />
				<button type="button" 
						id="validate-promo-code" 
						class="button"
						style="margin-left: 10px;">
					Validar Código
				</button>
				<button type="button" 
						id="test-api-connection" 
						class="button"
						style="margin-left: 10px;">
					Testar API
				</button>
				<div id="promo-code-result" style="margin-top: 10px;"></div>
				
				<p class="description">
					<strong>🎁 Ganhe 5 créditos grátis!</strong><br>
					Insira um código promocional válido e ganhe 5 créditos para você e 5 créditos para quem te indicou.
				</p>
			</div>
			
			<script>
			jQuery(document).ready(function($) {
				// Testar conectividade primeiro
				console.log('Testando conectividade com API...');
				$.get('<?php echo str_replace("http://", "https://", $this->app_url); ?>/api/debug')
					.done(function(data) {
						console.log('API conectada:', data);
					})
					.fail(function(xhr, status, error) {
						console.error('Erro de conectividade:', status, error);
					});
				
				// Botão de teste de API
				$('#test-api-connection').on('click', function() {
					var button = $(this);
					var resultDiv = $('#promo-code-result');
					
					button.prop('disabled', true).text('Testando...');
					resultDiv.empty();
					
					$.ajax({
						url: '<?php echo str_replace("http://", "https://", $this->app_url); ?>/api/debug',
						method: 'GET',
						timeout: 10000,
						success: function(response) {
							resultDiv.html('<p style="color: green;">✓ API funcionando: ' + response.message + '</p>');
						},
						error: function(xhr, status, error) {
							resultDiv.html('<p style="color: red;">✗ Erro na API: ' + status + ' - ' + error + '</p>');
						},
						complete: function() {
							button.prop('disabled', false).text('Testar API');
						}
					});
				});
				
				$('#validate-promo-code').on('click', function() {
					var button = $(this);
					var resultDiv = $('#promo-code-result');
					var promoCode = $('input[name="voicexpress_promo_code"]').val();
					
					if (!promoCode) {
						resultDiv.html('<p style="color: red;">Por favor, digite um código promocional.</p>');
						return;
					}
					
					button.prop('disabled', true).text('Validando...');
					resultDiv.empty();
					
					$.ajax({
						url: '<?php echo str_replace("http://", "https://", $this->app_url); ?>/api/validate-promo-code',
						method: 'POST',
						data: JSON.stringify({
							promo_code: promoCode
						}),
						contentType: 'application/json',
						timeout: 10000,
						success: function(response) {
							console.log('Validation response:', response);
							if (response.valid) {
								resultDiv.html('<p style="color: green;">✓ ' + response.message + '</p>');
								// Aplicar o código automaticamente
								applyPromoCode(promoCode);
							} else {
								resultDiv.html('<p style="color: red;">✗ ' + response.message + '</p>');
							}
						},
						error: function(xhr, status, error) {
							console.error('Validation error:', xhr, status, error);
							resultDiv.html('<p style="color: red;">Erro ao validar código: ' + status + ' - ' + error + '</p>');
						},
						complete: function() {
							button.prop('disabled', false).text('Validar Código');
						}
					});
				});
				
				function applyPromoCode(promoCode) {
					var siteKey = '<?php echo get_option("voicexpress_secret_key", ""); ?>';
					
					$.ajax({
						url: '<?php echo str_replace("http://", "https://", $this->app_url); ?>/api/apply-promo-code',
						method: 'POST',
						data: JSON.stringify({
							promo_code: promoCode,
							site_key: siteKey
						}),
						contentType: 'application/json',
						timeout: 10000,
						success: function(response) {
							console.log('Apply response:', response);
							if (response.success) {
								$('#promo-code-result').append('<p style="color: green; font-weight: bold;">🎉 ' + response.message + '</p>');
								// Marcar como usado
								$('<input>').attr({
									type: 'hidden',
									name: 'voicexpress_promo_code_used',
									value: '1'
								}).appendTo('form');
								
								// Recarregar a página após 2 segundos para mostrar o novo estado
								setTimeout(function() {
									location.reload();
								}, 2000);
							} else {
								$('#promo-code-result').append('<p style="color: red;">✗ ' + response.message + '</p>');
							}
						},
						error: function(xhr, status, error) {
							console.error('Apply error:', xhr, status, error);
							$('#promo-code-result').append('<p style="color: red;">Erro ao aplicar código: ' + status + ' - ' + error + '</p>');
						}
					});
				}
			});
			</script>
			<?php
		}
	}

	/**
	 * Callback for cache settings section
	 *
	 * @return void
	 */
	public function voicexpress_cache_settings_callback() {
		echo '<p>Configure quais plugins de cache devem ter suas caches limpas automaticamente quando um áudio for atualizado. Isso garante que o novo áudio apareça imediatamente no site.</p>';
		
		$cache_plugins = $this->get_detected_cache_plugins();
		if ( empty( $cache_plugins ) ) {
			echo '<p><em>Nenhum plugin de cache foi detectado no seu site.</em></p>';
		} else {
			echo '<p style="color: #0073aa;"><strong>Plugins de cache detectados:</strong> ' . implode( ', ', array_column( $cache_plugins, 'name' ) ) . '</p>';
		}
	}

	/**
	 * Callback for individual cache plugin settings
	 *
	 * @param array $args
	 * @return void
	 */
	public function voicexpress_cache_plugin_callback( $args ) {
		$plugin_key = $args['plugin_key'];
		$plugin_data = $args['plugin_data'];
		$option_name = 'voicexpress_cache_' . $plugin_key;
		$value = get_option( $option_name, '1' );
		
		?>
		<div style="display: flex; align-items: center; gap: 10px;">
			<label>
				<input type="checkbox" 
					   name="<?php echo esc_attr( $option_name ); ?>" 
					   value="1" 
					   <?php checked( $value, '1' ); ?> />
				<span style="color: <?php echo $value === '1' ? '#0073aa' : '#666'; ?>; font-weight: <?php echo $value === '1' ? 'bold' : 'normal'; ?>;">
					<?php echo $value === '1' ? 'Ativado' : 'Desativado'; ?>
				</span>
			</label>
			<div style="flex: 1;">
				<p style="margin: 0; color: #666; font-size: 13px;">
					<?php echo esc_html( $plugin_data['description'] ); ?>
				</p>
				<?php if ( ! empty( $plugin_data['functions'] ) ): ?>
					<details style="margin-top: 5px;">
						<summary style="font-size: 12px; color: #999; cursor: pointer;">Detalhes técnicos</summary>
						<p style="font-size: 11px; color: #999; margin: 5px 0 0 20px;">
							<strong>Funções utilizadas:</strong><br>
							<?php echo implode( '<br>', array_map( 'esc_html', $plugin_data['functions'] ) ); ?>
						</p>
					</details>
				<?php endif; ?>
			</div>
		</div>
		<hr style="margin: 15px 0; border: none; border-top: 1px solid #f0f0f0;">
		<?php
	}

	/**
	 * Adiciona Schema.org JSON-LD para podcasts
	 *
	 * @return void
	 */
	public function add_podcast_schema() {
		global $post;

		// Verificar se está em uma página de podcast ou episódio
		if ( $this->is_podcast_page() ) {
			$this->output_podcast_series_schema();
		} elseif ( $this->is_podcast_episode() ) {
			$this->output_podcast_episode_schema();
		}
	}

	/**
	 * Verifica se a página atual é uma página de podcast
	 *
	 * @return bool
	 */
	private function is_podcast_page() {
		return is_front_page() || is_home();
	}

	/**
	 * Verifica se a página atual é um episódio de podcast
	 *
	 * @return bool
	 */
	private function is_podcast_episode() {
		global $post;
		
		// Verificar se é uma página single de post com áudio
		if ( is_single() && $post && $post->post_type === 'post' ) {
			$version = get_post_meta( $post->ID, '_voicexpress_audio', true );
			if ( ! empty( $version ) && $version !== 'Compre mais créditos' ) {
				return true;
			}
		}
		
		return false;
	}

	/**
	 * Gera o Schema.org para a série do podcast
	 *
	 * @return void
	 */
	private function output_podcast_series_schema() {

		// Buscar informações do site/blog
		$site_name = get_bloginfo( 'name' );
		$site_description = get_bloginfo( 'description' );
		$site_url = get_bloginfo( 'url' );
		$domain = parse_url( $site_url, PHP_URL_HOST );
		$domain = str_replace( 'www.', '', $domain );
		// Usar valores personalizados se configurados
		$custom_title = get_option( 'voicexpress_podcast_title', '' );
		$custom_description = get_option( 'voicexpress_podcast_description', '' );
		
		if ( ! empty( $custom_title ) ) {
			$site_name = $custom_title;
		} elseif ( empty( $site_name ) ) {
			$site_name = 'Podcast ' . ucfirst( str_replace( '.', ' ', $domain ) );
		}
		
		if ( ! empty( $custom_description ) ) {
			$site_description = $custom_description;
		} elseif ( empty( $site_description ) ) {
			$site_description = 'Podcast com conteúdo convertido em áudio do site ' . $domain;
		}

		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => 'PodcastSeries',
			'name' => $site_name,
			'url' => "https://voicexpress.app/podcasts/{$domain}",
			'description' => $site_description,
			'inLanguage' => 'pt-BR',
			'publisher' => array(
				'@type' => 'Organization',
				'name' => 'VoiceXpress',
				'url' => $this->app_url
			)
		);

		echo '<script type="application/ld+json">' . wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . '</script>' . "\n";
	}

	/**
	 * Gera o Schema.org para episódio do podcast
	 *
	 * @return void
	 */
	private function output_podcast_episode_schema() {
		global $post;
		
		if ( ! $post ) {
			return;
		}

		$version = get_post_meta( $post->ID, '_voicexpress_audio', true );
		if ( empty( $version ) || $version === 'Compre mais créditos' ) {
			return;
		}

		// URLs
		$audio_url = 'https://cdn.voicexpress.app/audios/' . $version . '.mp3';
		$episode_url = get_permalink( $post->ID );
		// $post_permalink = get_post_field( 'post_name', $post->ID );
		$voicexpress_episode_url = $this->app_url . '/epr/' . $episode_url;
		
		// Informações do podcast/site
		$site_name = get_bloginfo( 'name' );
		$site_url = get_bloginfo( 'url' );
		$domain = parse_url( $site_url, PHP_URL_HOST );
		$domain = str_replace( 'www.', '', $domain );
		
		// URL da série do podcast
		$podcast_series_url = $this->app_url . '/podcasts/' . $domain;
		
		// Usar valores personalizados se configurados
		$custom_title = get_option( 'voicexpress_podcast_title', '' );
		
		if ( ! empty( $custom_title ) ) {
			$site_name = $custom_title;
		} elseif ( empty( $site_name ) ) {
			$site_name = 'Podcast ' . ucfirst( str_replace( '.', ' ', $domain ) );
		}

		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => 'PodcastEpisode',
			'name' => get_the_title( $post->ID ),
			'url' => $voicexpress_episode_url,
			'datePublished' => get_the_date( 'c', $post->ID ),
			'description' => $this->get_post_excerpt( $post->ID ),
			'associatedMedia' => array(
				'@type' => 'MediaObject',
				'contentUrl' => $audio_url,
				'encodingFormat' => 'audio/mpeg'
			),
			'partOfSeries' => array(
				'@type' => 'PodcastSeries',
				'name' => $site_name,
				'url' => $podcast_series_url
			)
		);

		echo '<script type="application/ld+json">' . wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . '</script>' . "\n";
	}

	/**
	 * Obtém o excerpt do post para usar como descrição
	 *
	 * @param int $post_id ID do post
	 * @return string
	 */
	private function get_post_excerpt( $post_id ) {
		$post = get_post( $post_id );
		if ( ! $post ) {
			return '';
		}

		// Se tem excerpt personalizado, usar ele
		if ( ! empty( $post->post_excerpt ) ) {
			return wp_strip_all_tags( $post->post_excerpt );
		}

		// Senão, criar um excerpt do conteúdo
		$content = wp_strip_all_tags( $post->post_content );
		if ( strlen( $content ) > 160 ) {
			$content = substr( $content, 0, 160 ) . '...';
		}

		return $content;
	}
}
