<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-dashboard.php
 *
 * Dashboard Settings Tab (Tab 12)
 *
 * Options managed here:
 *   mbs_setting_dashboard_persona  — Solo | Publisher | House (ALL tiers)
 *   mbs_setting_brand_monitor_url  — Google Alerts RSS URL (PRO-gated)
 *
 * @package MyBookShowroom
 * @since   2.3.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// phpcs:disable WordPress.Security.NonceVerification -- nonce verified in parent class verify_save() / check_admin_referer() before $_POST access; PHPCS cannot trace cross-method nonce verification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- input sanitized at point of use (sanitize_text_field, absint, wp_kses_post, etc.); false positives from PHPCS not tracing sanitization helpers called before this method
class MBS_Tab_Dashboard {

	public function __construct() {
		add_action( 'admin_init', array( $this, 'save_settings' ) );
	}

	/**
	 * Enqueue Dashboard tab assets (license CSS + JS, loaded when Dashboard is active).
	 *
	 * @param string $current_tab The active tab slug.
	 */
	public function enqueue( string $current_tab ): void {
		if ( 'dashboard' !== $current_tab ) {
			return;
		}

		wp_enqueue_style(
			'mbs-admin-settings-license',
			plugins_url( 'assets/css/mbs-admin-settings-license.css', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-settings' ),
			MBS_VERSION
		);

		wp_enqueue_script(
			'mbs-admin-license',
			plugins_url( 'assets/js/adminjs/admin-license.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery' , 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-admin-license', 'my-book-showroom', MBS_DIR . 'languages' );

		wp_localize_script( 'mbs-admin-license', 'MBS_License_Ajax', array(
			'nonce'             => wp_create_nonce( 'mbs_license_ajax' ),
		) );
	}

	/** Handle form save submitted via admin_init. */
	public function save_settings(): void {
		if ( ! isset( $_POST['mbs_dashboard_nonce'] ) ) {
			return;
		}
		check_admin_referer( 'mbs_dashboard_save', 'mbs_dashboard_nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Persona — ALL tiers.
		$allowed_personas = array( 'solo', 'publisher', 'house' );
		$persona = sanitize_key( wp_unslash( $_POST['mbs_setting_dashboard_persona'] ?? 'solo' ) );
		if ( ! in_array( $persona, $allowed_personas, true ) ) {
			$persona = 'solo';
		}
		update_option( 'mbs_setting_dashboard_persona', $persona );

		// Default Author — ALL tiers.
		$new_author_name  = sanitize_text_field( wp_unslash( $_POST['mbs_default_author_new'] ?? '' ) );
		$selected_term_id = absint( wp_unslash( $_POST['mbs_setting_default_author_term'] ?? 0 ) );
		$default_author_id = 0;
		if ( '' !== $new_author_name ) {
			// Text field wins — create or locate existing term.
			$result = wp_insert_term( $new_author_name, MBS_TAX_AUTHOR );
			if ( is_wp_error( $result ) && 'term_exists' === $result->get_error_code() ) {
				$default_author_id = (int) $result->get_error_data( 'term_exists' );
			} elseif ( ! is_wp_error( $result ) ) {
				$default_author_id = (int) $result['term_id'];
			}
		} elseif ( $selected_term_id > 0 ) {
			// Dropdown selection — validate term still exists.
			$term = get_term( $selected_term_id, MBS_TAX_AUTHOR );
			if ( $term && ! is_wp_error( $term ) ) {
				$default_author_id = $selected_term_id;
			}
		}
		update_option( 'mbs_setting_default_author_term', $default_author_id );

		// Brand Monitor URL — PRO-gated.
		if ( mbs_is_pro() ) {
			$url = esc_url_raw( wp_unslash( $_POST['mbs_setting_brand_monitor_url'] ?? '' ) );
			update_option( 'mbs_setting_brand_monitor_url', $url );

			// DASH-2A: Multi-URL Brand Monitor repeater.
			$raw_urls = isset( $_POST['mbs_brand_feed_urls'] ) ? (array) wp_unslash( $_POST['mbs_brand_feed_urls'] ) : array();
			$feed_urls = array();
			foreach ( $raw_urls as $u ) { // RF-012: array_slice(0,5) cap removed -- DB has no structural limit.
				$cleaned = esc_url_raw( (string) $u );
				if ( '' !== $cleaned ) {
					$feed_urls[] = $cleaned;
				}
			}
			// Migrate legacy single URL if no new URLs have been set.
			if ( empty( $feed_urls ) && ! empty( $url ) ) {
				$feed_urls[] = $url;
			}
			MBS_Brand_Feed_URL_DAO::save_all( $feed_urls ); // RF-012.
		}

		// PRG redirect.
		wp_safe_redirect(
			add_query_arg(
				array( 'page' => 'my-book-showroom-settings', 'tab' => 'dashboard', 'updated' => '1' ),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	/** Render the tab. */
	public function render(): void {
		// Top save button — rendered above the license card so it is visible
		// without scrolling. Uses HTML5 form= attribute to submit the form below.
		echo '<div class="mbs-save-top">';
		submit_button( null, 'primary', 'submit', true, array( 'form' => 'mbs-dashboard-form' ) );
		echo '</div>';

		// License status card — always shown at the top of the Dashboard.
		MBS_Tab_License_Render::render();

		echo '<hr style="margin:24px 0 20px;">';

		$persona   = get_option( 'mbs_setting_dashboard_persona', 'solo' );
		$brand_url  = get_option( 'mbs_setting_brand_monitor_url', '' );
		$feed_urls = MBS_Brand_Feed_URL_DAO::get_all(); // RF-012.
		if ( empty( $feed_urls ) && ! empty( $brand_url ) ) {
			$feed_urls = array( $brand_url );
		}
		$is_pro            = mbs_is_pro();
		$default_author_id = (int) get_option( 'mbs_setting_default_author_term', 0 );
		$author_terms      = get_terms( array( 'taxonomy' => MBS_TAX_AUTHOR, 'hide_empty' => false ) );
		$author_terms      = ( ! is_wp_error( $author_terms ) ) ? $author_terms : array();
		?>
		<?php if ( isset( $_GET['updated'] ) ) : ?>
		<div class="notice notice-success is-dismissible">
			<p><?php esc_html_e( 'Dashboard settings saved.', 'my-book-showroom' ); ?></p>
		</div>
		<?php endif; ?>

		<form id="mbs-dashboard-form" method="post" action="">
			<?php wp_nonce_field( 'mbs_dashboard_save', 'mbs_dashboard_nonce' ); ?>

			<!-- ── Persona ────────────────────────────────────────────────── -->
			<h2><?php esc_html_e( 'Dashboard Persona', 'my-book-showroom' ); ?></h2>
			<p class="description">
				<?php esc_html_e( 'Choose a dashboard layout that matches how you use My Book Showroom.', 'my-book-showroom' ); ?>
			</p>
			<table class="form-table">
				<tr>
					<th scope="row">
						<label for="mbs_setting_dashboard_persona">
							<?php esc_html_e( 'Layout Mode', 'my-book-showroom' ); ?>
						</label>
					</th>
					<td>
						<select id="mbs_setting_dashboard_persona" name="mbs_setting_dashboard_persona">
							<option value="solo" <?php selected( $persona, 'solo' ); ?>>
								<?php esc_html_e( 'Solo Author', 'my-book-showroom' ); ?>
							</option>
							<option value="publisher" <?php selected( $persona, 'publisher' ); ?>>
								<?php esc_html_e( 'Publisher', 'my-book-showroom' ); ?>
							</option>
							<option value="house" <?php selected( $persona, 'house' ); ?>>
								<?php esc_html_e( 'Publishing House', 'my-book-showroom' ); ?>
							</option>
						</select>
						<p class="description">
							<?php esc_html_e( 'Solo Author: personal catalog focus. Publisher: multi-book campaign view. Publishing House: team activity and imprint overview.', 'my-book-showroom' ); ?>
						</p>
					</td>
				</tr>
			</table>

			<!-- ── Book Creation Defaults ────────────────────────────────── -->
			<h2><?php esc_html_e( 'Book Creation Defaults', 'my-book-showroom' ); ?></h2>
			<p class="description">
				<?php esc_html_e( 'These settings are applied automatically when you add a new book.', 'my-book-showroom' ); ?>
			</p>
			<table class="form-table">
				<tr>
					<th scope="row">
						<label for="mbs_setting_default_author_term">
							<?php esc_html_e( 'Set default solo author', 'my-book-showroom' ); ?>
						</label>
					</th>
					<td>
						<select id="mbs_setting_default_author_term" name="mbs_setting_default_author_term">
							<option value="0"><?php esc_html_e( '— None —', 'my-book-showroom' ); ?></option>
							<?php foreach ( $author_terms as $term ) : ?>
							<option value="<?php echo esc_attr( $term->term_id ); ?>"
								<?php selected( $default_author_id, $term->term_id ); ?>>
								<?php echo esc_html( $term->name ); ?>
							</option>
							<?php endforeach; ?>
						</select>
						<br>
						<input type="text"
						       id="mbs_default_author_new"
						       name="mbs_default_author_new"
						       value=""
						       class="regular-text"
						       style="margin-top:0.5rem;"
						       placeholder="<?php esc_attr_e( 'Or type a new author name to create one…', 'my-book-showroom' ); ?>">
						<p class="description">
							<?php esc_html_e( 'Select an existing author or type a new name. This author will be pre-assigned on every new book.', 'my-book-showroom' ); ?>
						</p>
					</td>
				</tr>
			</table>

			<!-- ── Brand Monitor (PRO) ────────────────────────────────────── -->
			<h2><?php esc_html_e( 'Brand Monitor', 'my-book-showroom' ); ?></h2>
			<?php if ( $is_pro ) : ?>
			<p class="description">
				<?php esc_html_e( 'Paste your Google Alerts RSS URL to monitor mentions of your name and books. Generate an alert at google.com/alerts, then copy the RSS feed link.', 'my-book-showroom' ); ?>
			</p>
			<!-- DASH-2A: Multi-URL repeater (up to 5 feeds) -->
			<p class="description"><?php esc_html_e( 'Add up to 5 RSS feed URLs (e.g. Google Alerts). The 2 most recent results per feed are cached.', 'my-book-showroom' ); ?></p>
			<div id="mbs-brand-feed-repeater" style="margin-bottom:0.75rem;">
				<?php
				$pad_urls = array_pad( $feed_urls, 1, '' );
				foreach ( $pad_urls as $i => $feed_url ) :
				?>
				<div class="mbs-brand-feed-row" style="display:flex;gap:0.5rem;margin-bottom:0.4rem;">
					<input type="url"
					       name="mbs_brand_feed_urls[]"
					       value="<?php echo esc_attr( $feed_url ); ?>"
					       class="regular-text"
					       placeholder="https://www.google.com/alerts/feeds/...">
					<?php if ( $i > 0 ) : ?>
					<button type="button" class="button mbs-remove-feed-row"
					        aria-label="<?php esc_attr_e( 'Remove feed', 'my-book-showroom' ); ?>">&#x2715;</button>
					<?php endif; ?>
				</div>
				<?php endforeach; ?>
			</div>
			<button type="button" id="mbs-add-feed-row" class="button"><?php esc_html_e( '+ Add Feed URL', 'my-book-showroom' ); ?></button>
			<script>
			(function(){
				var repeater = document.getElementById('mbs-brand-feed-repeater');
				var addBtn   = document.getElementById('mbs-add-feed-row');
				if ( ! repeater || ! addBtn ) return;
				addBtn.addEventListener('click', function(){
					var rows = repeater.querySelectorAll('.mbs-brand-feed-row');
					if ( rows.length >= 5 ) { alert('Maximum 5 feed URLs allowed.'); return; }
					var tpl  = rows[0].cloneNode(true);
					tpl.querySelector('input').value = '';
					var rm = document.createElement('button');
					rm.type = 'button'; rm.className = 'button mbs-remove-feed-row';
					rm.setAttribute('aria-label','Remove feed'); rm.innerHTML = '&#x2715;';
					rm.addEventListener('click', function(){ tpl.parentNode.removeChild(tpl); });
					tpl.appendChild(rm);
					repeater.appendChild(tpl);
				});
				repeater.addEventListener('click', function(e){
					if ( e.target.classList.contains('mbs-remove-feed-row') ) {
						e.target.closest('.mbs-brand-feed-row').remove();
					}
				});
			})();
			</script>
			<?php else : ?>
			<!-- MBS: Brand Monitor RSS requires PRO license -->
			<div class="mbs-pro-notice">
				<p>
					<?php
					printf(
						/* translators: %s: upgrade link */
						esc_html__( 'Brand Monitor RSS is a PRO feature. %s to monitor your author mentions across the web.', 'my-book-showroom' ),
						'<a href="' . esc_url( admin_url( 'admin.php?page=my-book-showroom&tab=dashboard' ) ) . '">' .
						esc_html__( 'Upgrade to PRO', 'my-book-showroom' ) . '</a>'
					);
					?>
				</p>
			</div>
			<?php endif; ?>

			<?php submit_button( __( 'Save Dashboard Settings', 'my-book-showroom' ) ); ?>
		</form>
		<?php
	}
}
