<?php
/**
 * Sitemap Admin UI
 *
 * Handles the Sitemap vertical tab in the General settings page.
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Sitemap;

use SEOvaultSEO\Core\Options;

/**
 * Admin UI for the sitemap module
 */
class Admin {

	/**
	 * Render the standalone Sitemap admin page.
	 */
	public static function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( isset( $_POST['seovaultseo_sitemap_nonce'] ) ) {
			$nonce = sanitize_text_field( wp_unslash( $_POST['seovaultseo_sitemap_nonce'] ) );
			if ( wp_verify_nonce( $nonce, 'seovaultseo_sitemap_save' ) ) {
				if ( isset( $_POST['seovaultseo_sitemap_purge'] ) ) {
					self::purge_cache();
				} else {
					self::save_settings();
				}
			}
		}

		?>
		<div class="wrap seovaultseo-settings-page">
			<div class="seovaultseo-page-header">
				<h1><?php esc_html_e( 'Sitemap', 'seovault-ai' ); ?></h1>
			</div>
			<?php settings_errors( 'seovaultseo_sitemap_settings' ); ?>
			<form method="post">
				<?php wp_nonce_field( 'seovaultseo_sitemap_save', 'seovaultseo_sitemap_nonce' ); ?>
				<?php self::render_tab(); ?>
				<p class="submit">
					<button type="submit" name="seovaultseo_sitemap_submit" class="button button-primary"><?php esc_html_e( 'Save Sitemap Settings', 'seovault-ai' ); ?></button>
					<button type="submit" name="seovaultseo_sitemap_purge" class="button button-secondary"><?php esc_html_e( 'Purge Sitemap Cache', 'seovault-ai' ); ?></button>
				</p>
			</form>
		</div>
		<?php
	}

	/**
	 * Render the sitemap settings fields (no form wrapper).
	 * Called from both the standalone page and the General settings tab.
	 */
	public static function render_tab() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$post_types     = Query::get_public_post_types();
		$taxonomies     = Query::get_public_taxonomies();
		$enabled        = Options::is_sitemap_enabled();
		$users          = Options::is_sitemap_users_enabled();
		$images         = Options::is_sitemap_images_enabled();
		$news           = Options::is_sitemap_news_enabled();
		$per_page       = Options::get_sitemap_entries_per_page();
		$frequency      = Options::get_sitemap_cron_frequency();
		$status         = Manager::get_status();
		$selected_types = Options::get_sitemap_post_types();
		$selected_tax   = Options::get_sitemap_taxonomies();
		?>
			<h2><?php esc_html_e( 'Sitemap', 'seovault-ai' ); ?></h2>

			<?php
			\SEOvaultSEO\Admin\CacheCompatibilityNotice::render( false );
			settings_errors( 'seovaultseo_sitemap_settings' );
			?>

			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Sitemap Status', 'seovault-ai' ); ?></th>
					<td>
						<p>
							<?php if ( $status['cached'] ) : ?>
								<span class="seovaultseo-badge seovaultseo-badge-success"><?php esc_html_e( 'Cached', 'seovault-ai' ); ?></span>
							<?php else : ?>
								<span class="seovaultseo-badge seovaultseo-badge-warning"><?php esc_html_e( 'Not Cached', 'seovault-ai' ); ?></span>
							<?php endif; ?>
						</p>
						<p class="description">
							<?php esc_html_e( 'Sitemap URL:', 'seovault-ai' ); ?>
							<a href="<?php echo esc_url( $status['url'] ); ?>" target="_blank" rel="noopener"><?php echo esc_html( $status['url'] ); ?></a>
						</p>
						<?php if ( $status['last_generated'] ) : ?>
							<p class="description">
								<?php esc_html_e( 'Last generated:', 'seovault-ai' ); ?>
								<?php echo esc_html( $status['last_generated'] ); ?> UTC
							</p>
						<?php endif; ?>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Enable Sitemap', 'seovault-ai' ); ?></th>
					<td>
						<?php self::render_toggle( 'seovaultseo_sitemap_enabled', __( 'Enable the SEOvault AI custom XML sitemap', 'seovault-ai' ), $enabled ); ?>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Post Types', 'seovault-ai' ); ?></th>
					<td>
						<?php foreach ( $post_types as $post_type ) : ?>
							<?php \SEOvaultSEO\Admin\Dashboard::render_checkbox( 'seovaultseo_sitemap_post_types[]', $post_type, $post_type, in_array( $post_type, $selected_types, true ) ); ?>
						<?php endforeach; ?>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Taxonomies', 'seovault-ai' ); ?></th>
					<td>
						<?php foreach ( $taxonomies as $taxonomy ) : ?>
							<?php \SEOvaultSEO\Admin\Dashboard::render_checkbox( 'seovaultseo_sitemap_taxonomies[]', $taxonomy, $taxonomy, in_array( $taxonomy, $selected_tax, true ) ); ?>
						<?php endforeach; ?>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Users', 'seovault-ai' ); ?></th>
					<td>
						<?php self::render_toggle( 'seovaultseo_sitemap_users', __( 'Include author archive sitemap', 'seovault-ai' ), $users ); ?>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Images', 'seovault-ai' ); ?></th>
					<td>
						<?php self::render_toggle( 'seovaultseo_sitemap_images', __( 'Include image sitemap tags', 'seovault-ai' ), $images ); ?>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'News', 'seovault-ai' ); ?></th>
					<td>
						<?php self::render_toggle( 'seovaultseo_sitemap_news', __( 'Enable news sitemap tags for posts', 'seovault-ai' ), $news ); ?>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="seovaultseo_sitemap_entries_per_page"><?php esc_html_e( 'Entries per Page', 'seovault-ai' ); ?></label>
					</th>
					<td>
						<input type="number" name="seovaultseo_sitemap_entries_per_page" id="seovaultseo_sitemap_entries_per_page" value="<?php echo esc_attr( $per_page ); ?>" min="100" max="50000" step="1" />
						<p class="description"><?php esc_html_e( 'Number of URLs per sitemap file (100 - 50000).', 'seovault-ai' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="seovaultseo_sitemap_cron_frequency"><?php esc_html_e( 'Cron Frequency', 'seovault-ai' ); ?></label>
					</th>
					<td>
						<select name="seovaultseo_sitemap_cron_frequency" id="seovaultseo_sitemap_cron_frequency" class="seovaultseo-select">
							<option value="hourly" <?php selected( $frequency, 'hourly' ); ?>><?php esc_html_e( 'Hourly', 'seovault-ai' ); ?></option>
							<option value="twicedaily" <?php selected( $frequency, 'twicedaily' ); ?>><?php esc_html_e( 'Twice Daily', 'seovault-ai' ); ?></option>
							<option value="daily" <?php selected( $frequency, 'daily' ); ?>><?php esc_html_e( 'Daily', 'seovault-ai' ); ?></option>
							<option value="every_six_hours" <?php selected( $frequency, 'every_six_hours' ); ?>><?php esc_html_e( 'Every 6 Hours', 'seovault-ai' ); ?></option>
						</select>
					</td>
				</tr>
			</table>

			<p style="margin-top:10px;">
				<a href="<?php echo esc_url( self::get_purge_cache_url() ); ?>" class="button button-secondary"><?php esc_html_e( 'Purge Sitemap Cache', 'seovault-ai' ); ?></a>
			</p>
		<?php
	}

	/**
	 * Save sitemap settings.
	 */
	private static function save_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		check_admin_referer( 'seovaultseo_sitemap_save', 'seovaultseo_sitemap_nonce' );

		$was_enabled = Options::is_sitemap_enabled();

		Options::set_sitemap_enabled( isset( $_POST['seovaultseo_sitemap_enabled'] ) );
		Options::set_sitemap_users_enabled( isset( $_POST['seovaultseo_sitemap_users'] ) );
		Options::set_sitemap_images_enabled( isset( $_POST['seovaultseo_sitemap_images'] ) );
		Options::set_sitemap_news_enabled( isset( $_POST['seovaultseo_sitemap_news'] ) );
		Options::set_sitemap_entries_per_page( isset( $_POST['seovaultseo_sitemap_entries_per_page'] ) ? absint( wp_unslash( $_POST['seovaultseo_sitemap_entries_per_page'] ) ) : 1000 );
		Options::set_sitemap_cron_frequency( isset( $_POST['seovaultseo_sitemap_cron_frequency'] ) ? sanitize_text_field( wp_unslash( $_POST['seovaultseo_sitemap_cron_frequency'] ) ) : 'every_six_hours' );

		$post_types = isset( $_POST['seovaultseo_sitemap_post_types'] ) ? array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['seovaultseo_sitemap_post_types'] ) ) : array();
		$taxonomies = isset( $_POST['seovaultseo_sitemap_taxonomies'] ) ? array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['seovaultseo_sitemap_taxonomies'] ) ) : array();
		Options::set_sitemap_post_types( $post_types );
		Options::set_sitemap_taxonomies( $taxonomies );

		$now_enabled = Options::is_sitemap_enabled();
		if ( $was_enabled !== $now_enabled || $now_enabled ) {
			self::flush_sitemap_rules();
		}

		do_action( 'seovaultseo_save_settings' );
		add_settings_error( 'seovaultseo_sitemap_settings', 'settings_saved', __( 'Sitemap settings saved.', 'seovault-ai' ), 'success' );
	}

	/**
	 * Save sitemap settings from POST data (for unified Save All Settings handler).
	 * Reads the same field names but does not add settings errors.
	 * Called from SettingsPage::handle_admin_actions().
	 */
	public static function save_sitemap_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		check_admin_referer( 'seovaultseo_save_all_settings_action' );

		$was_enabled = Options::is_sitemap_enabled();

		Options::set_sitemap_enabled( isset( $_POST['seovaultseo_sitemap_enabled'] ) );
		Options::set_sitemap_users_enabled( isset( $_POST['seovaultseo_sitemap_users'] ) );
		Options::set_sitemap_images_enabled( isset( $_POST['seovaultseo_sitemap_images'] ) );
		Options::set_sitemap_news_enabled( isset( $_POST['seovaultseo_sitemap_news'] ) );
		Options::set_sitemap_entries_per_page( isset( $_POST['seovaultseo_sitemap_entries_per_page'] ) ? absint( wp_unslash( $_POST['seovaultseo_sitemap_entries_per_page'] ) ) : 1000 );
		Options::set_sitemap_cron_frequency( isset( $_POST['seovaultseo_sitemap_cron_frequency'] ) ? sanitize_text_field( wp_unslash( $_POST['seovaultseo_sitemap_cron_frequency'] ) ) : 'every_six_hours' );

		$post_types = isset( $_POST['seovaultseo_sitemap_post_types'] ) ? array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['seovaultseo_sitemap_post_types'] ) ) : array();
		$taxonomies = isset( $_POST['seovaultseo_sitemap_taxonomies'] ) ? array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['seovaultseo_sitemap_taxonomies'] ) ) : array();
		Options::set_sitemap_post_types( $post_types );
		Options::set_sitemap_taxonomies( $taxonomies );

		$now_enabled = Options::is_sitemap_enabled();
		if ( $was_enabled !== $now_enabled || $now_enabled ) {
			self::flush_sitemap_rules();
		}

		do_action( 'seovaultseo_save_settings' );
	}

	/**
	 * Ensure sitemap rewrite rules are registered then flush.
	 * On the save request, init fires before admin_init, but setup()
	 * skips Router::register() because the option isn't set yet.
	 * So we must manually register rules before flushing.
	 */
	private static function flush_sitemap_rules() {
		Router::register();
		Manager::clear_rewrite_heal_flag();
		flush_rewrite_rules();
	}

	/**
	 * Purge the sitemap cache and trigger a rebuild.
	 */
	public static function purge_cache() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		Cache::clear_all();
		Builder::rebuild( true );
		add_settings_error( 'seovaultseo_sitemap_settings', 'cache_purged', __( 'Sitemap cache purged and rebuild started.', 'seovault-ai' ), 'success' );
	}

	/**
	 * Get the General page purge-cache URL for the sitemap tab.
	 *
	 * @return string
	 */
	public static function get_purge_cache_url() {
		return wp_nonce_url(
			admin_url( 'admin.php?page=seovault-ai-general&action=purge_sitemap_cache#vtab-sitemap' ),
			'seovaultseo_sitemap_purge_action'
		);
	}

	/**
	 * Render an animated toggle switch.
	 *
	 * @param string $name    The input name attribute.
	 * @param string $label   The visible label text.
	 * @param bool   $checked Whether the toggle is on.
	 * @param string $id      Optional. The input id attribute (defaults to $name).
	 */
	private static function render_toggle( $name, $label, $checked, $id = '' ) {
		if ( empty( $id ) ) {
			$id = $name;
		}
		?>
		<div class="seovaultseo-toggle-row">
			<label class="seovaultseo-switch">
				<input type="checkbox" name="<?php echo esc_attr( $name ); ?>" id="<?php echo esc_attr( $id ); ?>" value="1" <?php checked( $checked ); ?> />
				<span class="seovaultseo-slider"></span>
			</label>
			<label for="<?php echo esc_attr( $id ); ?>" class="seovaultseo-toggle-label"><?php echo esc_html( $label ); ?></label>
		</div>
		<?php
	}
}
