<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-advanced.php
 *
 * Advanced / Developer Settings Tab — My Book Showroom
 *
 * Owns save_settings() for the Settings → Advanced tab.
 * Render output delegated to MBS_Tab_Advanced_Render (R-18).
 *
 * Current settings:
 *   · mbs_setting_advanced_universe_enabled (int 0|1)
 *       Opt-in toggle for the Universe / Shared World taxonomy (F-017).
 *       PRO-only feature — the metabox and front-end display only appear
 *       when this is enabled AND the site has a PRO license.
 *       Default: 0 (off), even on PRO installs.
 *   · mbs_setting_general_wc_enabled (int 0|1)
 *       WooCommerce Integration toggle (F-WC-01). PRO-only; no-op when
 *       WooCommerce is not active. Moved from General tab (R-ADV-01).
 *       Default: 0 (off).
 *   · mbs_telemetry_consent (string opted_in|opted_out|deferred)
 *       Telemetry opt-in/out. Moved from General tab (R-ADV-01).
 *       Drives MBS_Telemetry cron schedule.
 *   · mbs_setting_appearance_custom_css (string)
 *       Global custom CSS injected into front-end MBS pages. Moved from
 *       Appearance tab (R-ADV-01). Sanitized via wp_strip_all_tags().
 *
 * Save flow: custom admin_init handler with check_admin_referer() + PRG redirect,
 * matching the General tab pattern. Advanced is in MBS_Settings::AJAX_ONLY_TABS
 * so options.php is bypassed; the tab renders its own <form> tag.
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin/Tabs
 * @since      1.0.0
 */

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

class MBS_Tab_Advanced {

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

	// -------------------------------------------------------------------------
	// Save handler
	// -------------------------------------------------------------------------

	/**
	 * Handle Advanced tab form saves submitted via admin_init (PRG pattern).
	 *
	 * @return void
	 */
	public function save_settings(): void {
		// ── POS Location CRUD actions (separate nonces; PUB-tier only) ───────────
		if ( isset( $_POST['mbs_pos_location_add_nonce'] ) ) {
			$this->handle_add_location();
			return;
		}
		if ( isset( $_POST['mbs_pos_location_toggle_nonce'] ) ) {
			$this->handle_toggle_location();
			return;
		}
		if ( isset( $_POST['mbs_pos_location_delete_nonce'] ) ) {
			$this->handle_delete_location();
			return;
		}

		if ( ! isset( $_POST['mbs_advanced_nonce'] ) ) {
			return;
		}

		check_admin_referer( 'mbs_advanced_save', 'mbs_advanced_nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// mbs_setting_advanced_universe_enabled — checkbox: 1 when checked, absent when unchecked.
		$prev_universe_enabled = (int) get_option( 'mbs_setting_advanced_universe_enabled', 0 );
		$universe_enabled      = isset( $_POST['mbs_setting_advanced_universe_enabled'] ) ? 1 : 0;
		update_option( 'mbs_setting_advanced_universe_enabled', $universe_enabled );

		// mbs_setting_show_universe_reading_order — PRO-only Universe RO toggle (Sprint RO-Display).
		// Auto-enable on first activation of the Universe feature (0 → 1 transition).
		if ( mbs_is_pro() ) {
			if ( 0 === $prev_universe_enabled && 1 === $universe_enabled ) {
				// Universe just turned on for the first time: default RO toggle to enabled.
				update_option( 'mbs_setting_show_universe_reading_order', '1' );
			} else {
				update_option(
					'mbs_setting_show_universe_reading_order',
					isset( $_POST['mbs_show_universe_reading_order'] ) ? '1' : '0'
				);
			}
		}

		// mbs_setting_general_wc_enabled — PRO-only; only saved when WooCommerce is active.
		if ( mbs_is_pro() && class_exists( 'WooCommerce' ) ) {
			update_option( 'mbs_setting_general_wc_enabled', isset( $_POST['mbs_general_wc_enabled'] ) ? '1' : '0' );
		}

		// mbs_telemetry_consent — checkbox: 'opted_in' when checked, 'opted_out' when absent.
		$prev_consent = get_option( MBS_Telemetry::CONSENT_KEY, '' );
		$new_consent  = isset( $_POST['mbs_telemetry_consent'] ) ? 'opted_in' : 'opted_out';
		if ( $prev_consent !== $new_consent ) {
			update_option( MBS_Telemetry::CONSENT_KEY, $new_consent );
			if ( 'opted_in' === $new_consent ) {
				MBS_Telemetry::schedule_cron();
			} else {
				MBS_Telemetry::clear_cron();
			}
		}

		// mbs_setting_appearance_custom_css — global custom CSS; strip tags, preserve safe CSS.
		$custom_css = wp_strip_all_tags( wp_unslash( $_POST['mbs_setting_appearance_custom_css'] ?? '' ) );
		update_option( 'mbs_setting_appearance_custom_css', $custom_css );

		// Analytics settings (moved from Appearance tab, R-ADV-02).
		$analytics_enabled  = isset( $_POST['mbs_setting_analytics_enabled'] ) ? 1 : 0;
		$analytics_provider = sanitize_key( wp_unslash( $_POST['mbs_setting_analytics_provider'] ?? 'ga4' ) );
		if ( ! in_array( $analytics_provider, array( 'ga4', 'plausible' ), true ) ) {
			$analytics_provider = 'ga4';
		}
		update_option( 'mbs_setting_analytics_enabled', $analytics_enabled );
		update_option( 'mbs_setting_analytics_provider', $analytics_provider );
		$raw_analytics_id = sanitize_text_field( wp_unslash( $_POST['mbs_setting_analytics_id'] ?? '' ) );
		// V9-B-013: Validate ID format before saving — prevent malformed IDs from silently persisting.
		$_analytics_valid = false;
		if ( '' === $raw_analytics_id ) {
			$_analytics_valid = true; // Clearing is always valid.
		} elseif ( 'ga4' === $analytics_provider && preg_match( '/^G-[A-Z0-9]{1,15}$/', $raw_analytics_id ) ) {
			$_analytics_valid = true;
		} elseif ( 'plausible' === $analytics_provider && preg_match( '/^[a-zA-Z0-9][a-zA-Z0-9\-\.]{0,251}[a-zA-Z0-9]$/', $raw_analytics_id ) ) {
			$_analytics_valid = true;
		}
		if ( '' !== $raw_analytics_id && $_analytics_valid ) {
			$enc_analytics_id = MBS_Encryption::encrypt( $raw_analytics_id );
			if ( '' !== $enc_analytics_id ) {
				update_option( 'mbs_setting_analytics_id', $enc_analytics_id );
			}
		} elseif ( '' === $raw_analytics_id ) {
			update_option( 'mbs_setting_analytics_id', '' );
		} // else: invalid format — silently discard (field retains previous value).

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


	// -------------------------------------------------------------------------
	// POS Location CRUD handlers (PUB-tier; WooCommerce required)
	// -------------------------------------------------------------------------

	/**
	 * Handle "Add Location" form submission.
	 *
	 * @return void
	 */
	private function handle_add_location(): void {
		check_admin_referer( 'mbs_pos_location_add', 'mbs_pos_location_add_nonce' );
		if ( ! current_user_can( 'manage_options' ) || ! mbs_is_pub() ) {
			return;
		}
		$name    = sanitize_text_field( wp_unslash( $_POST['mbs_pos_location_name'] ?? '' ) );
		$address = sanitize_text_field( wp_unslash( $_POST['mbs_pos_location_address'] ?? '' ) );
		if ( $name ) {
			MBS_POS_Location_DAO::insert( $name, $address ?: null );
		}
		wp_safe_redirect(
			add_query_arg(
				array( 'page' => 'my-book-showroom-settings', 'tab' => 'advanced', 'updated' => '1' ),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	/**
	 * Handle location active/inactive toggle.
	 *
	 * @return void
	 */
	private function handle_toggle_location(): void {
		$location_id = absint( $_POST['mbs_pos_location_id'] ?? 0 );
		check_admin_referer( 'mbs_pos_location_toggle_' . $location_id, 'mbs_pos_location_toggle_nonce' );
		if ( ! current_user_can( 'manage_options' ) || ! mbs_is_pub() || ! $location_id ) {
			return;
		}
		MBS_POS_Location_DAO::toggle_active( $location_id );
		wp_safe_redirect(
			add_query_arg(
				array( 'page' => 'my-book-showroom-settings', 'tab' => 'advanced', 'updated' => '1' ),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	/**
	 * Handle location delete.  Blocked if the location has inventory rows.
	 *
	 * @return void
	 */
	private function handle_delete_location(): void {
		$location_id = absint( $_POST['mbs_pos_location_id'] ?? 0 );
		check_admin_referer( 'mbs_pos_location_delete_' . $location_id, 'mbs_pos_location_delete_nonce' );
		if ( ! current_user_can( 'manage_options' ) || ! mbs_is_pub() || ! $location_id ) {
			return;
		}
		// Guard: do not delete locations that have inventory records.
		if ( ! MBS_POS_Location_DAO::has_inventory( $location_id ) ) {
			MBS_POS_Location_DAO::delete( $location_id );
		}
		wp_safe_redirect(
			add_query_arg(
				array( 'page' => 'my-book-showroom-settings', 'tab' => 'advanced', 'updated' => '1' ),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	// -------------------------------------------------------------------------
	// Assets
	// -------------------------------------------------------------------------

	/**
	 * Enqueue Advanced tab assets when this tab is active.
	 *
	 * @param string $current_tab The active tab slug.
	 */
	public function enqueue( string $current_tab ): void {
		if ( 'advanced' !== $current_tab ) {
			return;
		}

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

		// R-ADV-02: Analytics accordion moved here from Appearance tab (Session 183).
		// mbs-admin-customization.js owns the .mbs-accordion-toggle handler.
		wp_enqueue_script(
			'mbs-admin-customization',
			plugins_url( 'assets/js/adminjs/mbs-admin-customization.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery' ),
			MBS_VERSION,
			true
		);
	}

	// -------------------------------------------------------------------------
	// Render
	// -------------------------------------------------------------------------

	/**
	 * Render the Advanced / Developer settings tab.
	 *
	 * Delegates to MBS_Tab_Advanced_Render::render().
	 * Kept as a thin instance method so class-mbs-settings.php can call
	 * $tab->render() without modification (R-18 delegate pattern).
	 *
	 * @return void
	 */
	public function render(): void {
		MBS_Tab_Advanced_Render::render();
	}
}
