<?php
/**
 * Meta Box for all post types.
 *
 * @package Dennis_SEO
 */

defined( 'ABSPATH' ) || exit;

class Dennis_SEO_Meta_Box {

	/**
	 * All meta keys and their types.
	 */
	const FIELDS = array(
		'_dennis_seo_title'           => 'text',
		'_dennis_seo_description'     => 'textarea',
		'_dennis_seo_keyphrase'       => 'text',
		'_dennis_seo_canonical'       => 'url',
		'_dennis_seo_robots_noindex'  => 'checkbox',
		'_dennis_seo_robots_nofollow' => 'checkbox',
		'_dennis_seo_og_title'        => 'text',
		'_dennis_seo_og_description'  => 'textarea',
		'_dennis_seo_og_image'        => 'url',
		'_dennis_seo_schema_type'     => 'select',
		'_dennis_seo_llms_include'    => 'select',
		'_dennis_seo_llms_description' => 'textarea',
	);

	/**
	 * Yoast fallback keys.
	 */
	const YOAST_FALLBACKS = array(
		'_dennis_seo_title'           => '_yoast_wpseo_title',
		'_dennis_seo_description'     => '_yoast_wpseo_metadesc',
		'_dennis_seo_canonical'       => '_yoast_wpseo_canonical',
		'_dennis_seo_robots_noindex'  => '_yoast_wpseo_meta-robots-noindex',
		'_dennis_seo_keyphrase'       => '_yoast_wpseo_focuskw',
		'_dennis_seo_og_title'        => '_yoast_wpseo_opengraph-title',
		'_dennis_seo_og_description'  => '_yoast_wpseo_opengraph-description',
		'_dennis_seo_og_image'        => '_yoast_wpseo_opengraph-image',
	);

	public function __construct() {
		add_action( 'add_meta_boxes', array( $this, 'register' ) );
		add_action( 'save_post', array( $this, 'save' ), 10, 2 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	public function enqueue_assets( string $hook ): void {
		if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
			return;
		}
		wp_enqueue_style( 'dseo-metabox', DENNIS_SEO_URL . 'assets/css/admin-metabox.css', array(), DENNIS_SEO_VERSION );
		wp_enqueue_script( 'dseo-metabox', DENNIS_SEO_URL . 'assets/js/admin-metabox.js', array(), DENNIS_SEO_VERSION, true );
		wp_localize_script( 'dseo-metabox', 'dseoMetaBox', array(
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'dennis_seo_generate_key' ),
			'homeUrl' => home_url(),
			'statusNonce' => wp_create_nonce( 'dennis_seo_check_status' ),
			'i18n'    => array(
				'generatingKey'  => __( 'Generating key...', 'dennis-geo' ),
				'checkoutOpened' => __( 'Checkout opened in a new tab', 'dennis-geo' ),
				'dennisWorking'  => __( "Once payment goes through, Dennis gets to work — reading your site and filling in every SEO field. Give him a minute or two. It normally doesn't take long, he's really efficient.", 'dennis-geo' ),
				'notifyWhenDone' => __( "We'll let you know here when he's finished. Feel free to close this and come back later.", 'dennis-geo' ),
				'close'          => __( 'Close', 'dennis-geo' ),
				'errorTryAgain'  => __( 'Error — try again', 'dennis-geo' ),
				'populated'      => __( 'Your site has been populated!', 'dennis-geo' ),
				'reloadResults'  => __( 'All SEO & GEO fields are now filled. Reload the page to see the results.', 'dennis-geo' ),
				'reloadPage'     => __( 'Reload page', 'dennis-geo' ),
				'selectImage'    => __( 'Select Image', 'dennis-geo' ),
				'useImage'       => __( 'Use this image', 'dennis-geo' ),
			),
		) );
	}

	/**
	 * Get meta value with Yoast fallback.
	 */
	public static function get_meta( int $post_id, string $key ): string {
		$value = get_post_meta( $post_id, $key, true );
		if ( '' !== $value && false !== $value ) {
			return (string) $value;
		}
		// Try Yoast fallback — but only if Dennis has NEVER saved this field.
		// metadata_exists returns true once the key has been written (even as empty string).
		// This prevents Yoast values from reappearing after a user clears a Dennis field.
		if ( isset( self::YOAST_FALLBACKS[ $key ] ) && ! metadata_exists( 'post', $post_id, $key ) ) {
			$yoast_val = get_post_meta( $post_id, self::YOAST_FALLBACKS[ $key ], true );
			if ( '' !== $yoast_val && false !== $yoast_val ) {
				return (string) $yoast_val;
			}
		}
		return '';
	}

	public function register(): void {
		$post_types = get_post_types( array( 'public' => true ) );
		foreach ( $post_types as $pt ) {
			add_meta_box(
				'dennis-seo-meta-box',
				__( 'Dennis GEO – AI Visibility for WordPress', 'dennis-geo' ),
				array( $this, 'render' ),
				$pt,
				'normal',
				'low'
			);
		}
	}

	public function render( $post ): void {
		wp_nonce_field( 'dennis_seo_save', 'dennis_seo_nonce' );

		$title       = self::get_meta( $post->ID, '_dennis_seo_title' );
		$description = self::get_meta( $post->ID, '_dennis_seo_description' );
		$keyphrase   = self::get_meta( $post->ID, '_dennis_seo_keyphrase' );
		$canonical   = self::get_meta( $post->ID, '_dennis_seo_canonical' );
		$noindex     = self::get_meta( $post->ID, '_dennis_seo_robots_noindex' );
		$nofollow    = self::get_meta( $post->ID, '_dennis_seo_robots_nofollow' );
		$og_title    = self::get_meta( $post->ID, '_dennis_seo_og_title' );
		$og_desc     = self::get_meta( $post->ID, '_dennis_seo_og_description' );
		$og_image    = self::get_meta( $post->ID, '_dennis_seo_og_image' );
		$schema_type = self::get_meta( $post->ID, '_dennis_seo_schema_type' );
		$llms_inc    = get_post_meta( $post->ID, '_dennis_seo_llms_include', true );
		$llms_desc   = get_post_meta( $post->ID, '_dennis_seo_llms_description', true );
		?>

		<div class="dseo-wrap">
			<!-- AI Modal -->
			<div class="dseo-ai-modal-overlay" id="dseo-ai-modal-mb">
				<div class="dseo-ai-modal">
					<div class="dseo-ai-modal-header" style="position:relative;"><img src="<?php echo esc_url( plugins_url( 'assets/dennis-white.png', dirname( __FILE__ ) ) ); ?>" alt="" class="dseo-modal-logo" style="position:absolute;top:16px;right:16px;width:75px;height:75px;opacity:0.7;">
						<h3><span class="dashicons dashicons-superhero-alt" style="margin-right:4px;"></span> <?php esc_html_e( 'Autopopulate All Fields with AI', 'dennis-geo' ); ?></h3>
						<p><?php esc_html_e( 'Fill every SEO & GEO field in one click.', 'dennis-geo' ); ?></p>
					</div>
					<div class="dseo-ai-modal-body">
						<p><?php esc_html_e( 'Our AI reads every page on your site and automatically fills all your SEO & GEO fields with keyword-optimized, professionally crafted content — in minutes, not hours.', 'dennis-geo' ); ?></p>
						<ul>
							<li><?php esc_html_e( 'SEO titles & meta descriptions optimized for search and AI', 'dennis-geo' ); ?></li>
							<li><?php esc_html_e( 'Unique focus keyphrases for every page — no cannibalization', 'dennis-geo' ); ?></li>
							<li><?php esc_html_e( 'Schema types selected for maximum rich result visibility', 'dennis-geo' ); ?></li>
							<li><?php esc_html_e( 'llms.txt descriptions and llms-full.txt content generated', 'dennis-geo' ); ?></li>
							<li><?php esc_html_e( 'Open Graph titles & descriptions for social sharing', 'dennis-geo' ); ?></li>
						</ul>
						<p><strong><?php esc_html_e( 'One-time payment of $19. All fields on all pages. No subscription.', 'dennis-geo' ); ?></strong></p>
					<p style="font-size:12px;color:#666;margin:8px 0 0;"><?php esc_html_e( 'Fields you\'ve already filled are left as they are. Want all fields rewritten?', 'dennis-geo' ); ?> <a href="<?php echo esc_url( admin_url( 'admin.php?page=dennis-seo#dseo-clear-fields' ) ); ?>" style="color:#7e5cef;"><?php esc_html_e( 'Clear Dennis GEO fields', 'dennis-geo' ); ?></a> <?php esc_html_e( 'first.', 'dennis-geo' ); ?></p>
					</div>
					<div class="dseo-ai-modal-footer">
						<button type="button" class="dseo-ai-modal-cta" id="dseo-populate-btn-mb">
							<?php esc_html_e( 'Checkout — $19', 'dennis-geo' ); ?> &rarr;
						</button>
						<button type="button" class="dseo-ai-modal-close" onclick="document.getElementById('dseo-ai-modal-mb').classList.remove('active');"><?php esc_html_e( 'Maybe later', 'dennis-geo' ); ?></button>
						<p style="font-size:10px;color:#999;margin-top:-5px;width:100%;"><?php esc_html_e( 'By using this service, your page content will be sent to dennisgeo.com for AI processing.', 'dennis-geo' ); ?></p>
					</div>
				</div>
			</div>

			<!-- Tab Navigation -->
			<div class="dseo-tabs">
				<div class="dseo-tab active" data-tab="seo">
					<span class="dseo-tab-icon dashicons dashicons-search"></span>
					<?php esc_html_e( 'SEO', 'dennis-geo' ); ?>
				</div>
				<div class="dseo-tab" data-tab="social">
					<span class="dseo-tab-icon dashicons dashicons-share"></span>
					<?php esc_html_e( 'Social', 'dennis-geo' ); ?>
				</div>
				<div class="dseo-tab" data-tab="schema">
					<span class="dseo-tab-icon dashicons dashicons-editor-code"></span>
					<?php esc_html_e( 'Schema', 'dennis-geo' ); ?>
				</div>
				<div class="dseo-tab" data-tab="llm">
					<span class="dseo-tab-icon dashicons dashicons-cloud"></span>
					<?php esc_html_e( 'LLM / AI', 'dennis-geo' ); ?>
				</div>
				<?php if ( Dennis_SEO_Audit::quick_score() < 80 ) : ?>
				<button type="button" class="dseo-ai-btn" style="margin-left:auto; margin-right:12px; align-self:center;" onclick="document.getElementById('dseo-ai-modal-mb').classList.add('active');">
					<span class="dashicons dashicons-superhero-alt"></span> <?php esc_html_e( 'Fill with AI', 'dennis-geo' ); ?>
				</button>
				<?php else : ?>
				<a href="https://dennisgeo.com/wordpress-ai-visibility-audit.html" target="_blank" class="dseo-ai-btn" style="margin-left:auto; margin-right:12px; align-self:center; background:linear-gradient(135deg,#00a32a,#007017); box-shadow:none;">
					<span class="dashicons dashicons-awards"></span> <?php esc_html_e( 'Complete GEO Audit?', 'dennis-geo' ); ?>
				</a>
				<?php endif; ?>
			</div>

			<!-- SEO Panel -->
			<div class="dseo-panel active" data-panel="seo">
				<?php if ( Dennis_SEO_Yoast_Compat::is_yoast_active() ) : ?>
				<div style="font-size:12px; color:#757575; margin-bottom:14px; line-height:1.5;">
					<?php esc_html_e( 'Fields you fill in here will be used instead of Yoast. Leave empty to keep Yoast\'s values.', 'dennis-geo' ); ?>
				</div>
				<?php endif; ?>
				<div class="dseo-row">
					<label class="dseo-label" for="dseo-title"><?php esc_html_e( 'SEO Title', 'dennis-geo' ); ?></label>
					<input type="text" id="dseo-title" name="_dennis_seo_title" value="<?php echo esc_attr( $title ); ?>" data-char-count="dseo-title-count" data-char-max="60" placeholder="<?php echo esc_attr( get_the_title( $post->ID ) ); ?>">
					<div class="dseo-char-bar">
						<div class="dseo-char-track"><div class="dseo-char-fill" id="dseo-title-fill"></div></div>
						<span class="dseo-char-text" id="dseo-title-count"></span>
					</div>
				</div>

				<div class="dseo-row">
					<label class="dseo-label" for="dseo-description"><?php esc_html_e( 'Meta Description', 'dennis-geo' ); ?></label>
					<textarea id="dseo-description" name="_dennis_seo_description" data-char-count="dseo-desc-count" data-char-max="160" placeholder="<?php esc_attr_e( 'Brief description of this page for search results...', 'dennis-geo' ); ?>"><?php echo esc_textarea( $description ); ?></textarea>
					<div class="dseo-char-bar">
						<div class="dseo-char-track"><div class="dseo-char-fill" id="dseo-desc-fill"></div></div>
						<span class="dseo-char-text" id="dseo-desc-count"></span>
					</div>
				</div>

				<div class="dseo-cols">
					<div class="dseo-row">
						<label class="dseo-label" for="dseo-keyphrase"><?php esc_html_e( 'Focus Keyphrase', 'dennis-geo' ); ?></label>
						<input type="text" id="dseo-keyphrase" name="_dennis_seo_keyphrase" value="<?php echo esc_attr( $keyphrase ); ?>" placeholder="<?php esc_attr_e( 'e.g. plumber stockholm', 'dennis-geo' ); ?>">
					</div>
					<div class="dseo-row">
						<label class="dseo-label" for="dseo-canonical"><?php esc_html_e( 'Canonical URL', 'dennis-geo' ); ?></label>
						<input type="url" id="dseo-canonical" name="_dennis_seo_canonical" value="<?php echo esc_attr( $canonical ); ?>" placeholder="<?php esc_attr_e( 'Leave blank for default', 'dennis-geo' ); ?>">
					</div>
				</div>

				<div class="dseo-row">
					<label class="dseo-label"><?php esc_html_e( 'Robots Directives', 'dennis-geo' ); ?></label>
					<div class="dseo-checks">
						<label><input type="checkbox" name="_dennis_seo_robots_noindex" value="1" <?php checked( $noindex, '1' ); ?>> noindex</label>
						<label><input type="checkbox" name="_dennis_seo_robots_nofollow" value="1" <?php checked( $nofollow, '1' ); ?>> nofollow</label>
					</div>
					<span class="dseo-hint"><?php esc_html_e( 'Check to prevent search engines from indexing or following links on this page.', 'dennis-geo' ); ?></span>
				</div>
			</div>

			<!-- Social Panel -->
			<div class="dseo-panel" data-panel="social">
				<span class="dseo-hint" style="margin-bottom:16px;"><?php esc_html_e( 'Customize how this page appears when shared on Facebook, LinkedIn, Twitter/X, etc. Leave blank to use the SEO title, meta description, and featured image.', 'dennis-geo' ); ?></span>

				<div class="dseo-row" style="margin-top:16px;">
					<label class="dseo-label" for="dseo-og-title"><?php esc_html_e( 'Social Title', 'dennis-geo' ); ?></label>
					<input type="text" id="dseo-og-title" name="_dennis_seo_og_title" value="<?php echo esc_attr( $og_title ); ?>" placeholder="<?php esc_attr_e( 'Defaults to SEO Title', 'dennis-geo' ); ?>">
				</div>

				<div class="dseo-row">
					<label class="dseo-label" for="dseo-og-desc"><?php esc_html_e( 'Social Description', 'dennis-geo' ); ?></label>
					<textarea id="dseo-og-desc" name="_dennis_seo_og_description" placeholder="<?php esc_attr_e( 'Defaults to Meta Description', 'dennis-geo' ); ?>"><?php echo esc_textarea( $og_desc ); ?></textarea>
				</div>

				<div class="dseo-row">
					<label class="dseo-label" for="dseo-og-image"><?php esc_html_e( 'Social Image', 'dennis-geo' ); ?></label>
					<div style="display:flex; gap:8px; align-items:flex-start;">
						<input type="url" id="dseo-og-image" name="_dennis_seo_og_image" value="<?php echo esc_attr( $og_image ); ?>" placeholder="<?php esc_attr_e( 'Defaults to Featured Image', 'dennis-geo' ); ?>">
						<button type="button" class="button dseo-mb-upload-btn" data-target="dseo-og-image"><?php esc_html_e( 'Select Image', 'dennis-geo' ); ?></button>
					</div>
					<?php if ( $og_image ) : ?>
						<div style="margin-top:8px;"><img src="<?php echo esc_url( $og_image ); ?>" style="max-width:200px; max-height:80px; border:1px solid #ddd; border-radius:4px; padding:2px;" class="dseo-mb-preview" data-for="dseo-og-image" /></div>
					<?php endif; ?>
					<span class="dseo-hint"><?php esc_html_e( 'Recommended: 1200x630 pixels. Used for Open Graph (Facebook, LinkedIn) and Twitter Cards.', 'dennis-geo' ); ?></span>
				</div>
			</div>

			<!-- Schema Panel -->
			<div class="dseo-panel" data-panel="schema">
				<div class="dseo-row">
					<label class="dseo-label" for="dseo-schema-type"><?php esc_html_e( 'Schema Type', 'dennis-geo' ); ?></label>
					<select id="dseo-schema-type" name="_dennis_seo_schema_type">
						<?php
						$schema_options = array(
							''               => __( 'Default (auto-detect from post type)', 'dennis-geo' ),
							'WebPage'        => 'WebPage',
							'Article'        => 'Article',
							'BlogPosting'    => 'BlogPosting',
							'FAQPage'        => 'FAQPage',
							'Service'        => 'Service',
							'AboutPage'      => 'AboutPage',
							'ContactPage'    => 'ContactPage',
							'CollectionPage' => 'CollectionPage',
						);
						foreach ( $schema_options as $val => $label ) {
							echo '<option value="' . esc_attr( $val ) . '"' . selected( $schema_type, $val, false ) . '>' . esc_html( $label ) . '</option>';
						}
						?>
					</select>
					<span class="dseo-hint"><?php esc_html_e( 'Controls the primary schema.org type in the JSON-LD output. "Default" uses Article for posts and WebPage for pages.', 'dennis-geo' ); ?></span>
				</div>

				<div class="dseo-section-title"><?php esc_html_e( 'Active Schema Output', 'dennis-geo' ); ?></div>
				<span class="dseo-hint"><?php esc_html_e( 'The following schema types are automatically generated based on global settings:', 'dennis-geo' ); ?></span>
				<div style="margin-top:8px; display:flex; flex-wrap:wrap; gap:6px;">
					<?php
					$active = array();
					if ( Dennis_SEO_Settings::get( 'schema_organization', true ) ) {
						$active[] = Dennis_SEO_Settings::get( 'site_type', 'Organization' );
					}
					if ( Dennis_SEO_Settings::get( 'schema_website', true ) ) {
						$active[] = 'WebSite';
					}
					$active[] = ! empty( $schema_type ) ? $schema_type : 'WebPage';
					if ( Dennis_SEO_Settings::get( 'schema_breadcrumbs', true ) ) {
						$active[] = 'BreadcrumbList';
					}
					foreach ( $active as $type ) {
						echo '<span style="display:inline-block; padding:4px 10px; background:#f0f6fc; color:#2271b1; border-radius:3px; font-size:12px; font-weight:500;">' . esc_html( $type ) . '</span>';
					}
					?>
				</div>
			</div>

			<!-- LLM / AI Panel -->
			<div class="dseo-panel" data-panel="llm">
				<div class="dseo-row">
					<label class="dseo-label"><?php esc_html_e( 'Include in llms.txt', 'dennis-geo' ); ?></label>
					<select name="_dennis_seo_llms_include">
						<option value="default" <?php selected( in_array( $llms_inc, array( 'default', '' ), true ), true ); ?>><?php esc_html_e( 'Use global default', 'dennis-geo' ); ?></option>
						<option value="yes" <?php selected( $llms_inc, 'yes' ); ?>><?php esc_html_e( 'Yes — include this page', 'dennis-geo' ); ?></option>
						<option value="no" <?php selected( $llms_inc, 'no' ); ?>><?php esc_html_e( 'No — exclude this page', 'dennis-geo' ); ?></option>
					</select>
					<span class="dseo-hint"><?php esc_html_e( 'llms.txt helps AI systems like ChatGPT, Claude, and Perplexity understand your site content.', 'dennis-geo' ); ?></span>
				</div>

				<div class="dseo-row">
					<label class="dseo-label" for="dseo-llms-desc"><?php esc_html_e( 'llms.txt Description', 'dennis-geo' ); ?></label>
					<textarea id="dseo-llms-desc" name="_dennis_seo_llms_description" data-char-count="dseo-llms-count" data-char-max="200" placeholder="<?php esc_attr_e( '1-2 sentences describing this page for AI systems...', 'dennis-geo' ); ?>"><?php echo esc_textarea( $llms_desc ); ?></textarea>
					<div class="dseo-char-bar">
						<div class="dseo-char-track"><div class="dseo-char-fill" id="dseo-llms-fill"></div></div>
						<span class="dseo-char-text" id="dseo-llms-count"></span>
					</div>
					<span class="dseo-hint"><?php esc_html_e( 'Falls back to meta description if left empty.', 'dennis-geo' ); ?></span>
				</div>
			</div>
		</div>

		<?php
	}

	public function save( int $post_id, $post ): void {
		// Verify nonce.
		if ( ! isset( $_POST['dennis_seo_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['dennis_seo_nonce'] ) ), 'dennis_seo_save' ) ) {
			return;
		}

		// Check autosave.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		// Check capabilities.
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// Save all non-checkbox fields using sanitize callbacks from DENNIS_SEO_META_KEYS.
		$checkbox_keys = array( '_dennis_seo_robots_noindex', '_dennis_seo_robots_nofollow' );
		foreach ( DENNIS_SEO_META_KEYS as $key => $sanitize_cb ) {
			if ( in_array( $key, $checkbox_keys, true ) ) {
				continue; // Checkboxes handled below.
			}
			$val = isset( $_POST[ $key ] ) ? call_user_func( $sanitize_cb, wp_unslash( $_POST[ $key ] ) ) : '';
			update_post_meta( $post_id, $key, $val );
		}

		// Checkboxes — delete meta when unchecked so Yoast fallback can still work.
		if ( isset( $_POST['_dennis_seo_robots_noindex'] ) ) {
			update_post_meta( $post_id, '_dennis_seo_robots_noindex', '1' );
		} else {
			delete_post_meta( $post_id, '_dennis_seo_robots_noindex' );
		}
		if ( isset( $_POST['_dennis_seo_robots_nofollow'] ) ) {
			update_post_meta( $post_id, '_dennis_seo_robots_nofollow', '1' );
		} else {
			delete_post_meta( $post_id, '_dennis_seo_robots_nofollow' );
		}

		// Bust caches.
		delete_transient( 'dennis_seo_sitemap_post' );
		delete_transient( 'dennis_seo_sitemap_page' );
		delete_transient( 'dennis_seo_llms_txt' );
	}
}
