<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-advanced-render.php
 *
 * Advanced / Developer Settings Tab — Render Class
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin/Tabs
 * @since      1.0.0
 */

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

class MBS_Tab_Advanced_Render { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Render the Advanced / Developer settings tab.
	 *
	 * @return void
	 */
	public static function render(): void {
		$is_pro           = mbs_is_pro();
		$is_pub           = mbs_is_pub();
		$universe_enabled  = (int) get_option( 'mbs_setting_advanced_universe_enabled', 0 );
		$telemetry_consent = get_option( MBS_Telemetry::CONSENT_KEY, 'pending' );

		if ( isset( $_GET['updated'] ) && '1' === $_GET['updated'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			add_settings_error( 'mbs_advanced', 'mbs_advanced_updated', __( 'Settings saved.', 'my-book-showroom' ), 'updated' );
		}
		settings_errors( 'mbs_advanced' );
		?>
		<form method="post"
		      action="<?php echo esc_url( admin_url( 'admin.php?page=my-book-showroom-settings&tab=advanced' ) ); ?>">

			<div class="mbs-tab-advanced">

				<?php /* UX-01: Top save button — must precede <h2> so the float
				          establishes before the heading and they sit on the same line. */ ?>
				<div class="mbs-save-top"><?php submit_button( null, 'primary', 'submit', true ); ?></div>
				<h2><?php esc_html_e( 'Advanced / Developer Settings', 'my-book-showroom' ); ?></h2>
				<p class="mbs-settings-subtitle">
					<?php esc_html_e( 'Optional features for power users. These settings are off by default — enable only what your catalog needs.', 'my-book-showroom' ); ?>
				</p>

				<?php /* ── Universe / Shared World taxonomy ─────────────────────── */ ?>
				<div class="mbs-settings-card">
					<h3><?php esc_html_e( 'Universe / Shared World', 'my-book-showroom' ); ?></h3>
					<p class="description">
						<?php esc_html_e( 'Enable the Universe taxonomy to group books that share a fictional cosmos — for example, Cosmere, Grishaverse, or The Expanse. Many-to-many: a book can belong to multiple universes.', 'my-book-showroom' ); ?>
					</p>

					<?php if ( ! $is_pro ) : ?>
						<div class="mbs-pro-notice notice notice-info inline">
							<p>
								<strong><?php esc_html_e( 'PRO feature', 'my-book-showroom' ); ?></strong>
								&mdash;
								<?php esc_html_e( 'The Universe taxonomy is available on PRO and Publisher licenses. You can enable the toggle now; the metabox and front-end display will activate once you upgrade.', 'my-book-showroom' ); ?>
								&nbsp;<a href="<?php echo esc_url( add_query_arg( 'tier', 'pro', MBS_UPGRADE_URL ) ); ?>"
								         target="_blank" rel="noopener noreferrer">
									<?php esc_html_e( 'Upgrade to PRO →', 'my-book-showroom' ); ?>
								</a>
							</p>
						</div>
					<?php endif; ?>

					<div class="mbs-settings-field-cell">
						<label style="display:flex; align-items:center; gap:8px; cursor:pointer;">
							<input type="checkbox"
							       id="mbs_setting_advanced_universe_enabled"
							       name="mbs_setting_advanced_universe_enabled"
							       value="1"
							       <?php checked( $universe_enabled, 1 ); ?> />
							<span>
								<strong><?php esc_html_e( 'Enable Universe taxonomy', 'my-book-showroom' ); ?></strong>
								<br>
								<span class="description">
									<?php esc_html_e( 'When enabled, a Universe multi-select field appears in the book editor (PRO only) and assigned universes display on the front-end book page.', 'my-book-showroom' ); ?>
								</span>
							</span>
						</label>
					</div>

					<?php /* Sprint RO-Display (4b): Universe Reading Order global toggle. */ ?>
					<div class="mbs-settings-field-cell">
						<label style="display:flex; align-items:center; gap:8px; cursor:pointer;">
							<input type="checkbox"
							       id="mbs_show_universe_reading_order"
							       name="mbs_show_universe_reading_order"
							       value="1"
							       <?php checked( get_option( 'mbs_setting_show_universe_reading_order', '0' ), '1' ); ?>
							       <?php disabled( ! $is_pro || ! $universe_enabled, true ); ?> />
							<span>
								<strong><?php esc_html_e( 'Show Universe Reading Order', 'my-book-showroom' ); ?></strong>
								<?php if ( ! $is_pro ) : ?>
									<span class="pro-badge"><?php esc_html_e( 'PRO', 'my-book-showroom' ); ?></span>
								<?php endif; ?>
								<br>
								<span class="description">
									<?php esc_html_e( 'When enabled, single-book pages display a Reading Order row below the Universe Order row in the More in This Universe section. Requires an active PRO license.', 'my-book-showroom' ); ?>
								</span>
							</span>
						</label>
					</div>

				</div>

			</div>

			<?php /* ── WooCommerce Integration ─────────────────────────────────── */ ?>
			<?php if ( class_exists( 'WooCommerce' ) ) : ?>
			<div class="mbs-settings-card">
				<h3><?php esc_html_e( 'WooCommerce Integration', 'my-book-showroom' ); ?></h3>
				<p class="description">
					<?php esc_html_e( 'Allow books to be sold via WooCommerce. When enabled, an add-to-cart button links each book to a WooCommerce virtual product.', 'my-book-showroom' ); ?>
				</p>
				<?php if ( ! $is_pro ) : ?>
					<div class="mbs-pro-notice notice notice-info inline">
						<p>
							<strong><?php esc_html_e( 'PRO feature', 'my-book-showroom' ); ?></strong>
							&mdash;
							<?php esc_html_e( 'WooCommerce integration requires a PRO or Publisher license.', 'my-book-showroom' ); ?>
							&nbsp;<a href="<?php echo esc_url( add_query_arg( 'tier', 'pro', MBS_UPGRADE_URL ) ); ?>"
							         target="_blank" rel="noopener noreferrer">
								<?php esc_html_e( 'Upgrade to PRO →', 'my-book-showroom' ); ?>
							</a>
						</p>
					</div>
				<?php endif; ?>
				<div class="mbs-settings-field-cell">
					<label style="display:flex; align-items:center; gap:8px; cursor:pointer;">
						<input type="checkbox"
						       id="mbs_general_wc_enabled"
						       name="mbs_general_wc_enabled"
						       value="1"
						       <?php checked( get_option( 'mbs_setting_general_wc_enabled', '0' ), '1' ); ?>
						       <?php disabled( ! $is_pro, true ); ?> />
						<span><strong><?php esc_html_e( 'Enable WooCommerce integration', 'my-book-showroom' ); ?></strong></span>
					</label>
				</div>
			</div>
			
			<?php /* ── POS Locations (Publisher tier) ──────────────────────────────── */ ?>
			<div class="mbs-settings-card" style="margin-top:16px;">
				<details id="mbs-pos-locations">
					<summary style="cursor:pointer; list-style:none; display:flex; align-items:center; gap:8px;">
						<span style="font-size:16px; line-height:1;">&#9658;</span>
						<h3 style="margin:0;"><?php esc_html_e( 'In-Person Sales Locations', 'my-book-showroom' ); ?></h3>
					</summary>
					<?php if ( ! $is_pub ) : ?>
					<div class="mbs-pro-notice notice notice-info inline" style="margin-top:12px;">
						<p>
							<strong><?php esc_html_e( 'Publisher feature', 'my-book-showroom' ); ?></strong>
							&mdash;
							<?php esc_html_e( 'Multi-location inventory management for POS systems (OpenPOS) requires a Publisher license.', 'my-book-showroom' ); ?>
							&nbsp;<a href="<?php echo esc_url( add_query_arg( 'tier', 'pub', MBS_UPGRADE_URL ) ); ?>"
							         target="_blank" rel="noopener noreferrer">
								<?php esc_html_e( 'Upgrade to Publisher →', 'my-book-showroom' ); ?>
							</a>
						</p>
					</div>
					<?php else : ?>
					<p class="description" style="margin-top:12px;">
						<?php esc_html_e( 'Manage physical locations for in-person sales events. Each location tracks per-format stock via the POS REST API (/wp-json/mbs/v1/pos/location/{id}/inventory).', 'my-book-showroom' ); ?>
					</p>
					<?php $mbs_locations = MBS_POS_Location_DAO::get_all(); ?>
					<?php if ( $mbs_locations ) : ?>
					<table class="wp-list-table widefat fixed striped" style="margin:12px 0;">
						<thead><tr>
							<th><?php esc_html_e( 'Name', 'my-book-showroom' ); ?></th>
							<th><?php esc_html_e( 'Address', 'my-book-showroom' ); ?></th>
							<th><?php esc_html_e( 'Status', 'my-book-showroom' ); ?></th>
							<th><?php esc_html_e( 'Actions', 'my-book-showroom' ); ?></th>
						</tr></thead>
						<tbody>
						<?php foreach ( $mbs_locations as $mbs_loc ) : ?>
						<tr>
							<td><strong><?php echo esc_html( $mbs_loc->name ); ?></strong></td>
							<td><?php echo esc_html( $mbs_loc->address ?? '' ); ?></td>
							<td>
								<?php if ( $mbs_loc->is_active ) : ?>
									<span style="color:#2e7d32;"><?php esc_html_e( 'Active', 'my-book-showroom' ); ?></span>
								<?php else : ?>
									<span style="color:#9e9e9e;"><?php esc_html_e( 'Inactive', 'my-book-showroom' ); ?></span>
								<?php endif; ?>
							</td>
							<td>
								<form method="post" style="display:inline;">
									<?php wp_nonce_field( 'mbs_pos_location_toggle_' . $mbs_loc->id, 'mbs_pos_location_toggle_nonce' ); ?>
									<input type="hidden" name="mbs_pos_location_id" value="<?php echo esc_attr( $mbs_loc->id ); ?>">
									<button type="submit" class="button button-small">
										<?php echo $mbs_loc->is_active ? esc_html__( 'Deactivate', 'my-book-showroom' ) : esc_html__( 'Activate', 'my-book-showroom' ); ?>
									</button>
								</form>
								<?php if ( ! MBS_POS_Location_DAO::has_inventory( (int) $mbs_loc->id ) ) : ?>
								&nbsp;
								<form method="post" style="display:inline;">
									<?php wp_nonce_field( 'mbs_pos_location_delete_' . $mbs_loc->id, 'mbs_pos_location_delete_nonce' ); ?>
									<input type="hidden" name="mbs_pos_location_id" value="<?php echo esc_attr( $mbs_loc->id ); ?>">
									<button type="submit" class="button button-small button-link-delete"
										onclick="return confirm('<?php esc_attr_e( 'Delete this location?', 'my-book-showroom' ); ?>');">
										<?php esc_html_e( 'Delete', 'my-book-showroom' ); ?>
									</button>
								</form>
								<?php endif; ?>
							</td>
						</tr>
						<?php endforeach; ?>
						</tbody>
					</table>
					<?php else : ?>
					<p style="margin-top:12px;"><em><?php esc_html_e( 'No locations yet. Add your first location below.', 'my-book-showroom' ); ?></em></p>
					<?php endif; ?>
					<?php /* ── Add location form ─────────────────────────────────────── */ ?>
					<h4 style="margin-top:16px;"><?php esc_html_e( 'Add Location', 'my-book-showroom' ); ?></h4>
					<form method="post" style="display:flex; gap:12px; flex-wrap:wrap; align-items:flex-end;">
						<?php wp_nonce_field( 'mbs_pos_location_add', 'mbs_pos_location_add_nonce' ); ?>
						<div>
							<label for="mbs_pos_location_name"><strong><?php esc_html_e( 'Name', 'my-book-showroom' ); ?></strong></label><br>
							<input type="text" id="mbs_pos_location_name" name="mbs_pos_location_name"
							       class="regular-text"
							       placeholder="<?php esc_attr_e( 'e.g. BookExpo Booth 42', 'my-book-showroom' ); ?>"
							       required>
						</div>
						<div>
							<label for="mbs_pos_location_address"><strong><?php esc_html_e( 'Address (optional)', 'my-book-showroom' ); ?></strong></label><br>
							<input type="text" id="mbs_pos_location_address" name="mbs_pos_location_address"
							       class="regular-text"
							       placeholder="<?php esc_attr_e( 'Venue or city', 'my-book-showroom' ); ?>">
						</div>
						<div>
							<?php submit_button( __( 'Add Location', 'my-book-showroom' ), 'secondary', 'mbs_pos_location_add_submit', false ); ?>
						</div>
					</form>
					<?php endif; // mbs_is_pub() ?>
				</details>
			</div>

			<?php endif; ?>

			<?php /* ── Usage Telemetry ──────────────────────────────────────────── */ ?>
			<div class="mbs-settings-card">
				<h3><?php esc_html_e( 'Usage Telemetry', 'my-book-showroom' ); ?></h3>
				<p class="description">
					<?php esc_html_e( 'Help improve My Book Showroom by sharing anonymous usage data. No personally identifiable information is collected. You can change this at any time.', 'my-book-showroom' ); ?>
				</p>
				<div class="mbs-settings-field-cell">
					<label style="display:flex; align-items:center; gap:8px; cursor:pointer;">
						<input type="checkbox"
						       id="mbs_telemetry_consent"
						       name="mbs_telemetry_consent"
						       value="1"
						       <?php checked( $telemetry_consent, 'opted_in' ); ?> />
						<span>
							<strong><?php esc_html_e( 'Enable anonymous usage telemetry', 'my-book-showroom' ); ?></strong><br>
							<span class="description">
								<?php esc_html_e( 'Current status:', 'my-book-showroom' ); ?>
								<?php
								if ( 'opted_in' === $telemetry_consent ) {
									esc_html_e( 'Opted in', 'my-book-showroom' );
								} elseif ( 'opted_out' === $telemetry_consent ) {
									esc_html_e( 'Opted out', 'my-book-showroom' );
								} else {
									esc_html_e( 'Not yet decided', 'my-book-showroom' );
								}
								?>
							</span>
						</span>
					</label>
				</div>
			</div>

			<?php /* ── Analytics (moved from Appearance tab, R-ADV-02) ──────────────── */ ?>
			<?php MBS_Appearance_Analytics_Render::render(); ?>

			<?php /* ── Custom CSS (Global) ──────────────────────────────────────── */ ?>
			<div class="mbs-settings-card">
				<h3><?php esc_html_e( 'Custom CSS (Global)', 'my-book-showroom' ); ?></h3>
				<p class="description">
					<?php
					echo wp_kses(
						sprintf(
							/* translators: %s: .mbs-wrapper code element */
							__( 'Custom CSS applied on pages containing MBS content. Scope your selectors to %s to limit styles to MBS elements only.', 'my-book-showroom' ),
							'<code>.mbs-wrapper</code>'
						),
						array( 'code' => array() )
					);
					?>
				</p>
				<textarea name="mbs_setting_appearance_custom_css"
				          rows="12"
				          class="large-text code"><?php echo esc_textarea( mbs_get_setting( 'appearance', 'custom_css', '' ) ); ?></textarea>
			</div>

			<?php /* ── Database Tools ─────────────────────────────────────────────── */ ?>
			<div class="mbs-settings-card">
				<h3><?php esc_html_e( 'Database Tools', 'my-book-showroom' ); ?></h3>
				<p class="description">
					<?php esc_html_e( 'If the Books list shows "No books found" despite books existing, or after a database restore / host migration, use Repair Tables to recreate all MBS database tables, re-seed reference data, and run any pending schema migrations.', 'my-book-showroom' ); ?>
				</p>
				<div>
					<button type="button" id="mbs-repair-tables" class="button button-secondary">
						<?php esc_html_e( 'Repair Tables', 'my-book-showroom' ); ?>
					</button>
					<span id="mbs-repair-spinner" class="spinner" style="float:none; vertical-align:middle; margin-left:6px;"></span>
					<p id="mbs-repair-result" class="description" style="display:none; margin-top:8px;"></p>
				</div>
				<script>
				(function($){
					$('#mbs-repair-tables').on('click', function(){
						var $btn    = $(this);
						var $spin   = $('#mbs-repair-spinner');
						var $result = $('#mbs-repair-result');
						$btn.prop('disabled', true);
						$spin.addClass('is-active');
						$result.hide().removeClass('mbs-repair-ok mbs-repair-err');
						$.post(ajaxurl, {
							action: 'mbs_repair_tables',
							nonce:  '<?php echo esc_js( wp_create_nonce( 'mbs_repair_tables' ) ); ?>'
						}).done(function(r){
							$spin.removeClass('is-active');
							$btn.prop('disabled', false);
							$result.show()
							       .addClass(r.success ? 'mbs-repair-ok' : 'mbs-repair-err')
							       .text(r.success ? r.data.message : r.data.message);
						}).fail(function(){
							$spin.removeClass('is-active');
							$btn.prop('disabled', false);
							$result.show()
							       .addClass('mbs-repair-err')
							       .text('<?php esc_html_e( 'Request failed. Please try again.', 'my-book-showroom' ); ?>');
						});
					});
				}(jQuery));
				</script>
			</div>

			<?php wp_nonce_field( 'mbs_advanced_save', 'mbs_advanced_nonce' ); ?>
			<?php submit_button( __( 'Save Advanced Settings', 'my-book-showroom' ) ); ?>

		</form>
		<?php
	}
}
