<?php
/**
 * Calendar Entry Panel Renderer — renders the HTML form for editing a calendar entry.
 *
 * Extracted from Editorial_Calendar to isolate all entry-panel rendering concerns
 * in a dedicated class: building the edit form HTML, populating all fields from
 * the entry payload, and locating related WordPress content by keyword.
 *
 * @package Wisewand
 * @since 2.8.2
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Admin;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Wisewand\Utils\Options;
use Wisewand\Logging\Logger;
use Wisewand\Admin\Traits\AJAX_Security;

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log -- error_log() only used within WP_DEBUG conditionals

/**
 * Calendar Entry Panel Renderer.
 *
 * Responsible for generating the HTML markup for the calendar entry side-panel
 * edit form. Renders all entry fields, status indicators, WordPress settings
 * inputs, and related-content lookups.
 *
 * @package Wisewand
 * @since 2.8.2
 */
class Calendar_Panel_Renderer {

	use AJAX_Security;

	/**
	 * Options wrapper instance.
	 *
	 * @var Options
	 */
	private $options;

	/**
	 * Logger instance.
	 *
	 * @var Logger
	 */
	private $logger;

	/**
	 * Constructor.
	 *
	 * @since 2.8.2
	 *
	 * @param Options $options Options wrapper instance.
	 * @param Logger  $logger  Logger instance.
	 */
	public function __construct( Options $options, Logger $logger ) {
		$this->options = $options;
		$this->logger  = $logger;
	}

	/**
	 * Render the entry panel form HTML.
	 *
	 * Builds the complete HTML form for editing a calendar entry inside the
	 * side panel. Uses output buffering and returns the captured HTML string.
	 *
	 * @since 2.8.2
	 *
	 * @param array $entry Calendar entry data array including all fields and decoded payload.
	 * @return string HTML markup for the entry edit form.
	 */
	public function render_entry_panel_form( $entry ) {
		$payload       = $entry['wisewand_payload_decoded'] ?? array();
		$related_pages = $this->find_related_pages( $entry['keyword'] );

		ob_start();
		?>
		<div class="panel-form">
			<input type="hidden" id="entry-id" value="<?php echo esc_attr( $entry['id'] ); ?>">

			<?php if ( isset( $entry['keyword_source'] ) && $entry['keyword_source'] === 'rss' ) : ?>
				<!-- RSS Entry Warning Banner -->
				<div style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); border: 2px solid #10b981; border-radius: 12px; padding: 16px; margin-bottom: 16px; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);">
					<div style="display: flex; align-items: center; gap: 12px; color: white;">
						<div style="font-size: 32px;">📡</div>
						<div style="flex: 1;">
							<div style="font-size: 14px; font-weight: 600; margin-bottom: 4px;">
								<?php esc_html_e( 'RSS Feed Entry', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</div>
							<div style="font-size: 12px; opacity: 0.9; margin-bottom: 4px;">
								<?php
								if ( ! empty( $entry['source_metadata'] ) ) {
									$metadata = json_decode( $entry['source_metadata'], true );
									if ( isset( $metadata['feed_name'] ) ) {
										/* translators: %s: RSS feed name */
										echo esc_html( sprintf( __( 'Source: %s', 'wisewand-ai-content-writer-seo-content-generator' ), $metadata['feed_name'] ) );
									}
								}
								?>
							</div>
							<div style="font-size: 11px; opacity: 0.8; background: rgba(255,255,255,0.15); padding: 6px 10px; border-radius: 6px; margin-top: 6px;">
								ℹ️ <?php esc_html_e( 'Limited editing: Only publication date/time and WordPress settings can be modified.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</div>
						</div>
					</div>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $entry['wisewand_article_id'] ) ) : ?>
				<!-- Wisewand Article Link -->
				<div style="background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%); border: 2px solid #3b82f6; border-radius: 12px; padding: 16px; margin-bottom: 16px; box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);">
					<div style="display: flex; align-items: center; gap: 12px; color: white;">
						<div style="font-size: 32px;">
							<?php
							// Icon based on status
							if ( $entry['wisewand_status'] === 'ready' ) {
								echo esc_html( '✅' );
							} elseif ( in_array( $entry['wisewand_status'], array( 'creating', 'generating' ) ) ) {
								echo esc_html( '🔄' );
							} elseif ( $entry['wisewand_status'] === 'failed' ) {
								echo esc_html( '❌' );
							} else {
								echo esc_html( '🔗' );
							}
							?>
						</div>
						<div style="flex: 1;">
							<div style="font-size: 14px; font-weight: 600; margin-bottom: 4px;">
								Wisewand Article: <?php echo esc_html( $entry['wisewand_article_id'] ); ?>
							</div>
							<div style="font-size: 12px; opacity: 0.9; margin-bottom: 4px;">
								Status: <strong><?php echo esc_html( ucfirst( $entry['wisewand_status'] ) ); ?></strong>
							</div>
							<?php if ( $entry['wisewand_status'] === 'ready' ) : ?>
								<div style="font-size: 12px; opacity: 0.9; background: rgba(255,255,255,0.15); padding: 6px 10px; border-radius: 6px; margin-top: 6px;">
									<?php echo esc_html( '📅' ); ?> <strong>Scheduled Import:</strong><br>
									<?php echo esc_html( gmdate( 'F j, Y', strtotime( $entry['publication_date'] ) ) ); ?> at
									<?php
									$time_range  = $entry['publication_time_range'] ?? 'random';
									$time_labels = array(
										'random'    => '9 AM - 8 PM',
										'morning'   => '9 AM - 12 PM',
										'afternoon' => '12 PM - 5 PM',
										'evening'   => '5 PM - 8 PM',
									);
									echo esc_html( $time_labels[ $time_range ] ?? '9 AM - 8 PM' );
									?>
									<?php if ( ! empty( $entry['publication_time'] ) ) : ?>
										<?php // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- Intentional: displaying already-local times from database ?>
										<br><small>(Exact: <?php echo esc_html( date( 'g:i A', strtotime( $entry['publication_time'] ) ) ); ?>)</small>
									<?php endif; ?>
								</div>
							<?php endif; ?>
						</div>
						<a href="https://app.wisewand.ai/articles/<?php echo esc_attr( $entry['wisewand_article_id'] ); ?>" target="_blank" class="button" style="background: white; color: #3b82f6; border: none; font-weight: 600;">
							🔗 <?php esc_html_e( 'View on Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</a>
					</div>
					<?php if ( $entry['wisewand_status'] === 'ready' && empty( $entry['wordpress_post_id'] ) ) : ?>
						<!-- Import Now Button -->
						<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255,255,255,0.2);">
							<button type="button" id="import-now-btn" class="button" style="width: 100%; background: #10b981; color: white; border: none; font-weight: 600; padding: 10px; font-size: 14px; cursor: pointer;">
								📥 <?php esc_html_e( 'Import Now to WordPress', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</button>
						</div>
					<?php endif; ?>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $entry['wordpress_post_id'] ) && in_array( $entry['wordpress_status'], array( 'imported_draft', 'imported_published', 'imported_scheduled' ) ) ) : ?>
				<!-- Article Imported - WordPress Post Links -->
				<?php
				// Get actual post to check status
				$post        = get_post( $entry['wordpress_post_id'] );
				$post_status = $post ? $post->post_status : 'unknown';
				$post_exists = $post && $post->post_status !== 'trash';

				// Display appropriate message based on status
				if ( $entry['wordpress_status'] === 'imported_published' ) :
					$status_label = __( 'Published', 'wisewand-ai-content-writer-seo-content-generator' );
					$status_icon  = '🌐';
					$status_color = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
				elseif ( $entry['wordpress_status'] === 'imported_scheduled' ) :
					$status_label = __( 'Scheduled', 'wisewand-ai-content-writer-seo-content-generator' );
					$status_icon  = '📅';
					$status_color = 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)';
				else :
					$status_label = __( 'Imported (Draft)', 'wisewand-ai-content-writer-seo-content-generator' );
					$status_icon  = '📝';
					$status_color = 'linear-gradient(135deg, #6b7280 0%, #4b5563 100%)';
				endif;
				?>

				<div style="background: <?php echo esc_attr( $status_color ); ?>; border: 2px solid #10b981; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);">
					<?php if ( $post_exists ) : ?>
						<div style="display: flex; align-items: center; gap: 16px;">
							<div style="font-size: 48px;"><?php echo esc_html( $status_icon ); ?></div>
							<div style="flex: 1;">
								<div style="font-size: 18px; font-weight: 700; color: white; margin-bottom: 6px;">
									<?php esc_html_e( '✓ Imported to WordPress', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</div>
								<div style="font-size: 13px; color: rgba(255, 255, 255, 0.9); margin-bottom: 4px;">
									<?php
									/* translators: %s: WordPress post status (e.g., 'Published', 'Draft', 'Scheduled') */
									printf( esc_html__( 'Status: <strong>%s</strong>', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $status_label ) );
									?>
								</div>
								<div style="font-size: 12px; color: rgba(255, 255, 255, 0.8); margin-bottom: 12px;">
									<?php if ( ! empty( $entry['published_at'] ) ) : ?>
										<?php esc_html_e( 'Imported:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <strong><?php echo esc_html( gmdate( 'M j, Y g:i A', strtotime( $entry['published_at'] ) ) ); ?></strong>
									<?php endif; ?>
								</div>
								<div style="display: flex; gap: 8px; flex-wrap: wrap;">
									<?php if ( $post_status === 'publish' ) : ?>
										<a href="<?php echo esc_url( get_permalink( $entry['wordpress_post_id'] ) ); ?>" target="_blank" class="button button-primary" style="background: white; color: #10b981; border: none; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: transform 0.2s;">
											🌐 <?php esc_html_e( 'View Live Post', 'wisewand-ai-content-writer-seo-content-generator' ); ?> ↗
										</a>
									<?php endif; ?>
									<a href="<?php echo esc_url( get_edit_post_link( $entry['wordpress_post_id'] ) ); ?>" target="_blank" class="button button-secondary" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); font-weight: 600; transition: all 0.2s;">
										✏️ <?php esc_html_e( 'Edit in WordPress', 'wisewand-ai-content-writer-seo-content-generator' ); ?> →
									</a>
								</div>

								<!-- Post Metadata -->
								<div style="margin-top: 12px; padding: 10px; background: rgba(255, 255, 255, 0.15); border-left: 3px solid rgba(255, 255, 255, 0.4); border-radius: 4px;">
									<div style="font-size: 11px; color: rgba(255, 255, 255, 0.9); line-height: 1.6;">
										<strong><?php esc_html_e( 'Post ID:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php echo esc_html( $entry['wordpress_post_id'] ); ?><br>
										<strong><?php esc_html_e( 'WordPress Status:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php echo esc_html( ucfirst( $post_status ) ); ?>
									</div>
								</div>
							</div>
						</div>
					<?php else : ?>
						<!-- Post was deleted -->
						<div style="display: flex; align-items: center; gap: 16px;">
							<div style="font-size: 48px;">⚠️</div>
							<div style="flex: 1;">
								<div style="font-size: 18px; font-weight: 700; color: white; margin-bottom: 6px;">
									<?php esc_html_e( 'Post Not Found', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</div>
								<div style="font-size: 13px; color: rgba(255, 255, 255, 0.9);">
									<?php
									/* translators: %s: WordPress post ID (numeric identifier) */
									printf( esc_html__( 'The WordPress post (ID: %s) was deleted or moved.', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $entry['wordpress_post_id'] ) );
									?>
								</div>
							</div>
						</div>
					<?php endif; ?>
				</div>
			<?php endif; ?>

			<!-- SEO Insights -->
			<div class="panel-section insights-section">
				<h3>📊 <?php esc_html_e( 'Keyword Insights', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<div class="insights-grid">
					<div class="metric-card-small">
						<div class="metric-label"><?php esc_html_e( 'Keyword', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						<div class="metric-value-text"><?php echo esc_html( $entry['keyword'] ); ?></div>
					</div>
					<?php if ( $entry['search_volume'] ) : ?>
					<div class="metric-card-small">
						<div class="metric-label"><?php esc_html_e( 'Search Volume', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						<div class="metric-value"><?php echo esc_html( number_format( $entry['search_volume'] ) ); ?></div>
						<div class="metric-sublabel">/month</div>
					</div>
					<?php endif; ?>
					<?php if ( $entry['current_position'] ) : ?>
					<div class="metric-card-small">
						<div class="metric-label"><?php esc_html_e( 'Position', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						<div class="metric-value">#<?php echo esc_html( $entry['current_position'] ); ?></div>
					</div>
					<?php endif; ?>
					<div class="metric-card-small">
						<div class="metric-label"><?php esc_html_e( 'Intent', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						<div class="intent-badge-small"><?php echo esc_html( ucfirst( $entry['search_intent'] ) ); ?></div>
					</div>
				</div>
			</div>

			<?php if ( ! empty( $related_pages ) ) : ?>
			<!-- Related WordPress Content -->
			<div class="panel-section">
				<h3>🔗 <?php esc_html_e( 'Related WordPress Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<p class="section-description"><?php esc_html_e( 'Existing posts related to this keyword. Select one to update instead of creating new content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				<div class="related-pages">
					<?php foreach ( $related_pages as $page ) : ?>
					<label class="related-page-option">
						<input type="radio" name="existing_post_id" value="<?php echo esc_attr( $page->ID ); ?>" <?php checked( $entry['existing_post_id'], $page->ID ); ?>>
						<div class="page-info">
							<div class="page-title"><?php echo esc_html( $page->post_title ); ?></div>
							<div class="page-meta">
								<?php echo esc_html( $page->post_type ); ?> •
								Last updated: <?php echo esc_html( gmdate( 'M j, Y', strtotime( $page->post_modified ) ) ); ?>
							</div>
						</div>
					</label>
					<?php endforeach; ?>
					<label class="related-page-option">
						<input type="radio" name="existing_post_id" value="" <?php checked( empty( $entry['existing_post_id'] ) ); ?>>
						<div class="page-info">
							<div class="page-title">🆕 <?php esc_html_e( 'Create New Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
						</div>
					</label>
				</div>
			</div>
			<?php endif; ?>

			<!-- Article Configuration -->
			<div class="panel-section">
				<h3>✍️ <?php esc_html_e( 'Article Configuration', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<div class="form-row-two">
					<div class="form-col">
						<label><?php esc_html_e( 'Content Type', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="color: #ef4444;">*</span></label>
						<select name="content_type_selector" id="content-type-selector" class="panel-input" style="font-weight: 600;">
							<?php
							// Determine current endpoint and type from payload
							$current_type     = $payload['type'] ?? 'blog';
							$current_endpoint = 'articles'; // Default

							// Map old values to new endpoint structure
							if ( $current_type === 'categorypage' ) {
								$current_endpoint = 'categorypages';
								$current_type     = '';
							} elseif ( $current_type === 'productpage' ) {
								$current_endpoint = 'productpages';
								$current_type     = '';
							}

							$current_value = $current_endpoint . '|' . $current_type;
							?>
							<?php
							foreach ( \Wisewand\Config\Supported_Options::get_content_types() as $group ) {
								echo '<optgroup label="' . esc_attr( $group['icon'] . ' ' ) . esc_attr( $group['label'] ) . '">';
								foreach ( $group['items'] as $value => $label ) {
									echo '<option value="' . esc_attr( $value ) . '" ' . selected( $current_value, $value, false ) . '>' . esc_html( $label ) . '</option>';
								}
								echo '</optgroup>';
							}
							?>
						</select>
						<p class="field-help"><?php esc_html_e( 'Different content types use different API endpoints and have different available fields.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>

						<!-- Hidden fields for backend processing -->
						<input type="hidden" name="api_endpoint" id="api-endpoint" value="<?php echo esc_attr( $current_endpoint ); ?>">
						<input type="hidden" name="article_type" id="article-type" value="<?php echo esc_attr( $current_type ); ?>">
					</div>

					<div class="form-col">
						<label><?php esc_html_e( 'Article Length', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<input type="text" name="article_length" class="panel-input" value="<?php echo esc_attr( $payload['length'] ?? 'auto' ); ?>" placeholder="auto">
						<p class="field-help"><?php esc_html_e( '"auto" or a number between 1-5000 words', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
					</div>
				</div>

				<div class="form-row-two">
					<div class="form-col">
						<label><?php esc_html_e( 'Language', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="article_language" class="panel-input">
							<?php
							$current_lang = $payload['lang'] ?? 'en';
							foreach ( \Wisewand\Config\Supported_Options::get_languages() as $code => $lang ) {
								echo '<option value="' . esc_attr( $code ) . '" ' . selected( $current_lang, $code, false ) . '>' . esc_html( $lang['flag'] . ' ' . $lang['native'] ) . '</option>';
							}
							?>
						</select>
					</div>

					<div class="form-col">
						<label><?php esc_html_e( 'Country', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="article_country" class="panel-input">
							<?php
							$current_country = $payload['country'] ?? 'us';
							foreach ( \Wisewand\Config\Supported_Options::get_countries() as $code => $country ) {
								echo '<option value="' . esc_attr( $code ) . '" ' . selected( $current_country, $code, false ) . '>' . esc_html( $country['flag'] . ' ' . $country['name'] ) . '</option>';
							}
							?>
						</select>
					</div>
				</div>

				<label><?php esc_html_e( 'Title', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
				<input type="text" name="article_title" value="<?php echo esc_attr( $payload['title'] ?? $entry['keyword'] ); ?>" class="panel-input" placeholder="<?php esc_html_e( 'Auto-generated if empty', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">

				<!-- Keep Title - Articles Only -->
				<div class="articles-only-fields" style="<?php echo in_array( $current_endpoint, array( 'categorypages', 'productpages', 'discoverarticles' ) ) ? 'display:none;' : ''; ?>">
					<div class="form-checkbox">
						<label>
							<input type="checkbox" name="keep_title" value="1" <?php checked( ! empty( $payload['keep_title'] ), true ); ?>>
							<?php esc_html_e( 'Keep this exact title (don\'t let Wisewand modify it)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</label>
					</div>
				</div>

				<label><?php esc_html_e( 'Target Keyword', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
				<input type="text" name="target_keyword" value="<?php echo esc_attr( $payload['target_keyword'] ?? $entry['keyword'] ); ?>" class="panel-input">

				<!-- Secondary Keywords - Articles + Discover Only -->
				<div class="articles-discover-fields" style="<?php echo in_array( $current_endpoint, array( 'categorypages', 'productpages' ) ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Secondary Keywords', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<textarea name="keywords_secondary" rows="2" class="panel-input" placeholder="<?php esc_html_e( 'seo, référencement, erreurs seo courantes, positionnement web', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['keywords_secondary'] ?? '' ); ?></textarea>
				</div>

				<!-- Website URL - Category/Product/Discover Pages Only -->
				<div class="pages-only-fields" style="<?php echo ( $current_endpoint === 'articles' ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Website URL', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<input type="text" name="website" class="panel-input" value="<?php echo esc_url( $payload['website'] ?? home_url() ); ?>" placeholder="https://example.com">
					<p class="field-help"><?php esc_html_e( 'The website URL associated with this content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>

				<div class="form-row-two">
					<div class="form-col">
						<label><?php esc_html_e( 'Writing Style', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="writing_style_mode" id="writing-style-mode" class="panel-input">
							<option value="auto" <?php selected( $payload['writing_style_mode'] ?? 'auto', 'auto' ); ?>>🤖 <?php esc_html_e( 'Auto (Analyze Website)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							<option value="persona" <?php selected( $payload['writing_style_mode'] ?? '', 'persona' ); ?>>👤 <?php esc_html_e( 'Use Persona', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						</select>
					</div>

					<div class="form-col" id="persona-select-container" style="<?php echo ( $payload['writing_style_mode'] ?? 'auto' ) !== 'persona' ? 'display:none;' : ''; ?>">
						<label><?php esc_html_e( 'Persona', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<select name="persona_id" id="persona-select" class="panel-input" data-current-value="<?php echo esc_attr( $payload['persona_id'] ?? '' ); ?>">
							<option value=""><?php esc_html_e( 'Loading personas...', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
						</select>
					</div>
				</div>

				<label><?php esc_html_e( 'Project', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
				<select name="project_id" id="project-select" class="panel-input" data-current-value="<?php echo esc_attr( $payload['project_id'] ?? '' ); ?>">
					<option value=""><?php esc_html_e( 'Loading projects...', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
				</select>
				<p class="field-help"><?php esc_html_e( 'Links website URL and project default settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>

				<!-- Writing Style Description - Category/Product/Discover Pages Only -->
				<div class="pages-only-fields-2" style="<?php echo ( $current_endpoint === 'articles' ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Custom Writing Style', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<textarea name="writing_style" rows="2" class="panel-input" placeholder="<?php esc_html_e( 'e.g., Professional, conversational tone with expert insights and practical examples', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['writing_style'] ?? '' ); ?></textarea>
					<p class="field-help"><?php esc_html_e( 'Custom writing style description. Leave empty to use persona or auto-detect from website.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>
			</div>

			<!-- AI Instructions -->
			<div class="panel-section">
				<h3>🤖 <?php esc_html_e( 'AI Instructions', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<!-- Search Intention - Articles Only -->
				<div class="articles-only-fields-2" style="<?php echo ( $current_endpoint !== 'articles' ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Search Intention Answer', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<textarea name="search_intention_answer" rows="3" class="panel-input" placeholder="<?php esc_html_e( 'What should this article achieve for the reader?', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['search_intention_answer'] ?? '' ); ?></textarea>
				</div>

				<!-- Additional Instructions - All Types -->
				<label><?php esc_html_e( 'Additional Instructions', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
				<textarea name="additional_information" rows="3" class="panel-input" placeholder="<?php esc_html_e( 'Specific requirements, focus areas, or guidelines for the AI', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['additional_information'] ?? '' ); ?></textarea>

				<!-- Avoid Information - Articles Only -->
				<div class="articles-only-fields-3" style="<?php echo ( $current_endpoint !== 'articles' ) ? 'display:none;' : ''; ?>">
					<label><?php esc_html_e( 'Avoid Information', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<textarea name="avoid_information" rows="2" class="panel-input" placeholder="<?php esc_html_e( 'Topics or information to exclude from the article', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $payload['avoid_information'] ?? '' ); ?></textarea>
				</div>

				<!-- Generate Instructions Buttons -->
				<div style="display: flex; gap: 12px; margin-top: 16px; padding: 16px; background: rgba(59, 130, 246, 0.05); border-radius: 8px; border: 1px solid rgba(59, 130, 246, 0.2);">
					<button type="button" id="generate-instructions-template" class="button button-secondary" style="flex: 1;">
						📝 <?php esc_html_e( 'Quick Generate (Template)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</button>
					<?php if ( \Wisewand\Utils\OpenAI_Client::is_configured() ) : ?>
						<button type="button" id="generate-instructions-ai" class="button button-primary" style="flex: 1; background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%); border: none;">
							✨ <?php esc_html_e( 'AI Generate (ChatGPT)', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="font-size: 10px; opacity: 0.8;">~$0.0001</span>
						</button>
					<?php else : ?>
						<button type="button" class="button button-secondary" style="flex: 1; opacity: 0.5;" disabled title="<?php esc_html_e( 'Configure OpenAI API key in Settings to enable', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
							✨ <?php esc_html_e( 'AI Generate (ChatGPT)', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="font-size: 10px;">⚠️ No API Key</span>
						</button>
					<?php endif; ?>
				</div>
				<p class="field-help" style="margin-top: 8px; font-size: 11px; color: #64748b;">
					💡 <strong><?php esc_html_e( 'Quick Generate:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Uses smart templates (instant, free)', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br>
					<strong><?php esc_html_e( 'AI Generate:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Uses GPT-4o-mini for context-aware brief (better quality, small cost)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</p>
			</div>

			<!-- WordPress Settings -->
			<div class="panel-section">
				<h3>📰 <?php esc_html_e( 'WordPress Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>

				<div class="form-row-two">
					<div class="form-col">
						<label><?php esc_html_e( 'Publication Date', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<input type="date" name="publication_date" value="<?php echo esc_attr( $entry['publication_date'] ); ?>" class="panel-input">
					</div>

					<div class="form-col">
					<?php // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- Intentional: displaying already-local times from database ?>
						<label><?php esc_html_e( 'Exact Publication Time', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						<input type="time" name="publication_time"
								value="<?php echo ! empty( $entry['publication_time'] ) ? esc_attr( gmdate( 'H:i', strtotime( $entry['publication_time'] ) ) ) : ''; ?>"
								class="panel-input"
								placeholder="<?php esc_html_e( 'HH:MM', 'wisewand-ai-content-writer-seo-content-generator' ); ?>">
						<p class="field-help" style="font-size: 11px; margin-top: 4px;">
							<?php esc_html_e( 'CRON will import article at this exact time on publication date', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</p>
					</div>
				</div>

				<div class="form-row">
					<label><?php esc_html_e( 'Time Range (for reference)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
					<select name="publication_time_range" class="panel-input">
						<option value="random" <?php selected( $entry['publication_time_range'], 'random' ); ?>>🔀 Random (9 AM - 8 PM)</option>
						<option value="morning" <?php selected( $entry['publication_time_range'], 'morning' ); ?>>🌅 Morning (9 AM - 12 PM)</option>
						<option value="afternoon" <?php selected( $entry['publication_time_range'], 'afternoon' ); ?>>☀️ Afternoon (12 PM - 5 PM)</option>
						<option value="evening" <?php selected( $entry['publication_time_range'], 'evening' ); ?>>🌆 Evening (5 PM - 8 PM)</option>
					</select>
					<p class="field-help" style="font-size: 11px; margin-top: 4px;">
						<?php esc_html_e( 'Optional label - exact time above takes precedence', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</p>
				</div>

				<div class="form-row">
					<label><?php esc_html_e( 'Author', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'for WordPress import', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<?php
					// Get author from calendar entry (may come from AI matching or settings)
					$selected_author = $entry['target_author'] ?? get_current_user_id();

					// Get all authors (fixed: 'who' deprecated since WP 5.9)
					$all_authors = get_users(
						array(
							'capability' => 'edit_posts',
							'orderby'    => 'display_name',
							'order'      => 'ASC',
						)
					);
					?>
					<select name="target_author" class="panel-input">
						<?php foreach ( $all_authors as $author ) : ?>
							<option value="<?php echo esc_attr( $author->ID ); ?>" <?php selected( $selected_author, $author->ID ); ?>>
								<?php echo esc_html( $author->display_name ); ?>
							</option>
						<?php endforeach; ?>
					</select>
					<p class="field-help"><?php esc_html_e( 'This author will be set when importing to WordPress. If keyword was AI-matched to an author, that author is pre-selected.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>

				<div class="form-row">
					<label><?php esc_html_e( 'Categories', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'for WordPress import', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
					<?php
					// Get selected categories from entry metadata
					$selected_categories = array();
					$has_ai_categories   = false;
					if ( ! empty( $entry['wordpress_categories'] ) ) {
						if ( is_array( $entry['wordpress_categories'] ) ) {
							$selected_categories = $entry['wordpress_categories'];
						} else {
							$decoded             = json_decode( $entry['wordpress_categories'], true );
							$selected_categories = $decoded ?: array();
						}
						$has_ai_categories = ! empty( $selected_categories );
					}

					// Get all categories from ALL languages (WPML fix)
					$all_categories_map = array();

					if ( isset( $GLOBALS['sitepress'] ) ) {
						// WPML active - load from all languages
						global $sitepress;
						$active_languages = $sitepress->get_active_languages();

						if ( ! empty( $active_languages ) ) {
							foreach ( $active_languages as $lang_code => $lang_data ) {
								$sitepress->switch_lang( $lang_code );
								$lang_cats = get_categories(
									array(
										'orderby'    => 'name',
										'order'      => 'ASC',
										'hide_empty' => false,
									)
								);
								foreach ( $lang_cats as $cat ) {
									$all_categories_map[ $cat->term_id ] = $cat; // Store by ID
								}
							}
							$sitepress->switch_lang( $sitepress->get_current_language() );
						} else {
							$cats = get_categories(
								array(
									'orderby'    => 'name',
									'order'      => 'ASC',
									'hide_empty' => false,
								)
							);
							foreach ( $cats as $cat ) {
								$all_categories_map[ $cat->term_id ] = $cat;
							}
						}
					} else {
						// No WPML
						$cats = get_categories(
							array(
								'orderby'    => 'name',
								'order'      => 'ASC',
								'hide_empty' => false,
							)
						);
						foreach ( $cats as $cat ) {
							$all_categories_map[ $cat->term_id ] = $cat;
						}
					}

					$all_categories = array_values( $all_categories_map );
					?>
					<?php
					// ALWAYS show category info for debugging (will remove after verification)
					$selected_count = count( $selected_categories );
					?>
					<?php if ( $selected_count > 0 ) : ?>
						<div style="background: rgba(16, 185, 129, 0.15); border: 2px solid #10b981; padding: 12px 16px; margin-bottom: 12px; border-radius: 8px; font-size: 13px; box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2);">
							<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px;">
								<span style="font-size: 20px;">✅</span>
								<strong style="color: #10b981; font-size: 14px;">
									<?php echo esc_html( $selected_count ); ?> categor<?php echo esc_html( $selected_count > 1 ? 'ies' : 'y' ); ?> pre-selected
								</strong>
							</div>
							<div style="color: #64748b; font-size: 11px;">
								From AI matching • Category IDs: <?php echo esc_html( implode( ', ', array_slice( $selected_categories, 0, 5 ) ) ); ?><?php echo esc_html( count( $selected_categories ) > 5 ? '...' : '' ); ?>
							</div>
						</div>
					<?php else : ?>
						<div style="background: rgba(255, 193, 7, 0.1); border-left: 3px solid #ffc107; padding: 8px 12px; margin-bottom: 8px; border-radius: 4px; font-size: 12px;">
							ℹ️ <span style="color: #f59e0b;">No categories pre-selected.</span> Select categories below for WordPress import.
						</div>
					<?php endif; ?>
					<select name="wordpress_categories[]" multiple class="panel-input"
							style="height: 150px;
									font-size: 13px;
									<?php echo esc_attr( $selected_count > 0 ? 'border: 3px solid #10b981 !important; background: rgba(16, 185, 129, 0.08) !important; box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1) !important;' : 'border: 1px solid #d1d5db;' ); ?>">
						<?php foreach ( $all_categories as $category ) : ?>
							<option value="<?php echo esc_attr( $category->term_id ); ?>"
									<?php echo esc_attr( in_array( $category->term_id, $selected_categories ) ? 'selected' : '' ); ?>
									style="<?php echo esc_attr( in_array( $category->term_id, $selected_categories ) ? 'background: #10b981; color: white; font-weight: bold;' : '' ); ?>">
								<?php
								// Show parent > child hierarchy
								if ( $category->parent ) {
									$parent = get_category( $category->parent );
									if ( $parent ) {
										echo esc_html( $parent->name ) . ' > ';
									}
								}
								echo esc_html( $category->name );
								?>
							</option>
						<?php endforeach; ?>
					</select>
					<p class="field-help"><?php esc_html_e( 'Hold Ctrl/Cmd to select multiple. These categories will be applied when importing to WordPress.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				</div>

				<?php if ( $entry['publication_action'] === 'update' || ! empty( $entry['existing_post_id'] ) ) : ?>
				<label><?php esc_html_e( 'Content Update Strategy', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
				<select name="content_merge_strategy" class="panel-input">
					<option value="replace" <?php selected( $entry['content_merge_strategy'] ?? 'replace', 'replace' ); ?>>🔄 Replace Entire Content</option>
					<option value="append" <?php selected( $entry['content_merge_strategy'], 'append' ); ?>>➕ Append to End</option>
					<option value="prepend" <?php selected( $entry['content_merge_strategy'], 'prepend' ); ?>>⬆️ Prepend to Beginning</option>
				</select>
				<?php endif; ?>
			</div>

			<!-- Status & Progress -->
			<div class="panel-section status-section">
				<h3>🎯 <?php esc_html_e( 'Status & Progress', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<div class="status-timeline">
					<div class="status-step <?php echo esc_attr( $entry['wisewand_status'] === 'not_created' ? 'active' : 'completed' ); ?>">
						<div class="step-icon">📝</div>
						<div class="step-label"><?php esc_html_e( 'Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
					<div class="status-step <?php echo esc_attr( in_array( $entry['wisewand_status'], array( 'creating', 'generating' ) ) ? 'active' : ( $entry['wisewand_status'] === 'ready' ? 'completed' : '' ) ); ?>">
						<div class="step-icon">⚙️</div>
						<div class="step-label"><?php esc_html_e( 'Generating', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
					<div class="status-step <?php echo esc_attr( $entry['wisewand_status'] === 'ready' ? 'active' : ( in_array( $entry['wordpress_status'], array( 'draft', 'pending', 'published' ) ) ? 'completed' : '' ) ); ?>">
						<div class="step-icon">✅</div>
						<div class="step-label"><?php esc_html_e( 'Ready', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
					<div class="status-step <?php echo esc_attr( in_array( $entry['wordpress_status'], array( 'draft', 'pending', 'published' ) ) ? 'active' : '' ); ?>">
						<div class="step-icon">🚀</div>
						<div class="step-label"><?php esc_html_e( 'Published', 'wisewand-ai-content-writer-seo-content-generator' ); ?></div>
					</div>
				</div>

				<?php if ( $entry['wisewand_error'] || $entry['wordpress_error'] ) : ?>
				<div class="error-box">
					<strong>⚠️ <?php esc_html_e( 'Error:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
					<p><?php echo esc_html( $entry['wisewand_error'] ?? $entry['wordpress_error'] ); ?></p>
					<?php if ( $entry['wisewand_retry_count'] > 0 ) : ?>
					<small>
						<?php
						/* translators: %d: Current retry attempt number (1-3) */
						printf( esc_html__( 'Retry attempt: %d of 3', 'wisewand-ai-content-writer-seo-content-generator' ), absint( $entry['wisewand_retry_count'] ) );
						?>
						</small>
					<?php endif; ?>
				</div>
				<?php endif; ?>
			</div>

			<!-- Notes -->
			<div class="panel-section">
				<label><?php esc_html_e( 'Private Notes', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span class="optional">(<?php esc_html_e( 'optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></label>
				<textarea name="notes" rows="3" class="panel-input" placeholder="<?php esc_html_e( 'Add private notes about this publication...', 'wisewand-ai-content-writer-seo-content-generator' ); ?>"><?php echo esc_textarea( $entry['notes'] ?? '' ); ?></textarea>
			</div>

			<!-- Actions -->
			<div class="panel-actions">
				<button type="button" class="btn-save-entry btn-primary">💾 <?php esc_html_e( 'Save Changes', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
				<?php if ( $entry['wisewand_status'] === 'not_created' || $entry['wisewand_status'] === 'failed' ) : ?>
				<button type="button" class="btn-generate-now btn-secondary">⚡ <?php esc_html_e( 'Generate Now', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
				<?php endif; ?>
				<button type="button" class="btn-delete-entry btn-danger">🗑️ <?php esc_html_e( 'Delete', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
			</div>
		</div>

		<?php
		return ob_get_clean();
	}

	/**
	 * Find WordPress posts/pages related to a keyword.
	 *
	 * Searches post titles and content for the given keyword, returning up to
	 * five results ordered by title-match priority then modification date.
	 *
	 * @since 2.8.2
	 *
	 * @param string $keyword The keyword to search for.
	 * @return array Array of WP_Post-like stdClass objects with ID, post_title,
	 *               post_type, and post_modified fields.
	 */
	public function find_related_pages( $keyword ) {
		global $wpdb;

		$like_keyword = '%' . $wpdb->esc_like( $keyword ) . '%';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query more efficient than WP_Query for content search with CASE ordering
		$related = $wpdb->get_results(
			$wpdb->prepare(
				"
            SELECT ID, post_title, post_type, post_modified, post_content
            FROM {$wpdb->posts}
            WHERE (post_title LIKE %s OR post_content LIKE %s)
            AND post_status IN ('publish', 'draft', 'pending')
            AND post_type IN ('post', 'page', 'product')
            ORDER BY
                CASE
                    WHEN post_title LIKE %s THEN 1
                    ELSE 2
                END,
                post_modified DESC
            LIMIT 5
        ",
				$like_keyword,
				$like_keyword,
				$like_keyword
			)
		);

		return $related;
	}
}
