<?php
defined( 'ABSPATH' ) || exit;

/**
 * Registers the Settings page under WooCommerce > Analytics Dashboard > Settings.
 */
class WAD_Settings {

	const OPTION_GROUP = 'wad_settings';
	const PAGE_SLUG    = 'woo-analytics-settings';

	public static function init() {
		add_action( 'admin_menu', [ __CLASS__, 'register_settings_page' ] );
		add_action( 'admin_init', [ __CLASS__, 'register_options' ] );
		add_action( 'admin_post_wad_seed_data',  [ __CLASS__, 'handle_seed' ] );
		add_action( 'admin_post_wad_clean_data', [ __CLASS__, 'handle_clean' ] );
	}

	public static function register_settings_page() {
		$capability = current_user_can( 'manage_options' ) ? 'manage_options' : 'manage_woocommerce';

		add_submenu_page(
			'woocommerce',
			__( 'Analytics Dashboard Settings', 'woo-analytics-dashboard' ),
			__( 'Analytics Settings', 'woo-analytics-dashboard' ),
			$capability,
			self::PAGE_SLUG,
			[ __CLASS__, 'render_page' ]
		);
	}

	public static function register_options() {
		// AI Configuration
		register_setting( self::OPTION_GROUP, 'wad_ai_enabled', [ 'type' => 'boolean', 'default' => true ] );
		register_setting( self::OPTION_GROUP, 'wad_ai_daily_limit', [ 'type' => 'integer', 'default' => 50, 'sanitize_callback' => 'absint' ] );

		// Dashboard Configuration
		register_setting( self::OPTION_GROUP, 'wad_tier_platinum', [ 'type' => 'number', 'default' => 3000, 'sanitize_callback' => 'floatval' ] );
		register_setting( self::OPTION_GROUP, 'wad_tier_gold', [ 'type' => 'number', 'default' => 1500, 'sanitize_callback' => 'floatval' ] );
		register_setting( self::OPTION_GROUP, 'wad_tier_silver', [ 'type' => 'number', 'default' => 500, 'sanitize_callback' => 'floatval' ] );
		register_setting( self::OPTION_GROUP, 'wad_low_stock_threshold', [ 'type' => 'integer', 'default' => 10, 'sanitize_callback' => 'absint' ] );

		// Access Control
		register_setting( self::OPTION_GROUP, 'wad_min_role', [ 'type' => 'string', 'default' => 'manage_woocommerce', 'sanitize_callback' => [ __CLASS__, 'sanitize_role' ] ] );

		// White Label
		register_setting( self::OPTION_GROUP, 'wad_dashboard_name', [ 'type' => 'string', 'default' => 'WooCommerce', 'sanitize_callback' => 'sanitize_text_field' ] );
	}

	public static function sanitize_api_key( $value ): string {
		$value = sanitize_text_field( $value );
		if ( empty( $value ) ) {
			return '';
		}
		// If the value looks like a raw key, encrypt it.
		if ( str_starts_with( $value, 'sk-' ) ) {
			return WAD_AI::encrypt_key( $value );
		}
		// Otherwise assume it is already encrypted (re-saved from form).
		return $value;
	}

	public static function sanitize_role( $value ): string {
		return in_array( $value, [ 'manage_woocommerce', 'manage_options' ], true )
			? $value
			: 'manage_woocommerce';
	}

	public static function render_page() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'woo-analytics-dashboard' ) );
		}

		$currency = get_woocommerce_currency_symbol();
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Analytics Dashboard Settings', 'woo-analytics-dashboard' ); ?></h1>

			<?php if ( isset( $_GET['settings-updated'] ) ) : ?>
				<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'woo-analytics-dashboard' ); ?></p></div>
			<?php endif; ?>

			<?php if ( isset( $_GET['seeded'] ) ) : ?>
				<div class="notice notice-success is-dismissible"><p><?php
					printf(
						esc_html__( 'Demo data created: %1$d products, %2$d customers, %3$d orders.', 'woo-analytics-dashboard' ),
						(int) $_GET['products'], (int) $_GET['customers'], (int) $_GET['orders']
					);
				?></p></div>
			<?php endif; ?>

			<?php if ( isset( $_GET['cleaned'] ) ) : ?>
				<div class="notice notice-success is-dismissible"><p><?php
					printf(
						esc_html__( 'Demo data removed: %1$d products, %2$d customers, %3$d orders.', 'woo-analytics-dashboard' ),
						(int) $_GET['products'], (int) $_GET['customers'], (int) $_GET['orders']
					);
				?></p></div>
			<?php endif; ?>

			<form method="post" action="options.php">
				<?php settings_fields( self::OPTION_GROUP ); ?>

				<h2><?php esc_html_e( 'AI Assistant', 'woo-analytics-dashboard' ); ?></h2>
				<table class="form-table">
					<tr>
						<th><?php esc_html_e( 'Enable AI Assistant', 'woo-analytics-dashboard' ); ?></th>
						<td>
							<input type="checkbox" name="wad_ai_enabled" value="1" <?php checked( get_option( 'wad_ai_enabled', 1 ) ); ?> />
						</td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'OpenAI API Key', 'woo-analytics-dashboard' ); ?></th>
						<td>
							<input type="password" class="regular-text" disabled
								placeholder="<?php esc_attr_e( 'Managed in the StoreSight admin portal', 'woo-analytics-dashboard' ); ?>"
								value="" />
							<p class="description"><?php esc_html_e( 'OpenAI credentials are managed in StoreSight admin and never stored in the plugin.', 'woo-analytics-dashboard' ); ?></p>
						</td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Daily Query Limit (per user)', 'woo-analytics-dashboard' ); ?></th>
						<td>
							<input type="number" name="wad_ai_daily_limit" min="1" max="500"
								value="<?php echo esc_attr( get_option( 'wad_ai_daily_limit', 50 ) ); ?>" />
						</td>
					</tr>
				</table>

				<h2><?php esc_html_e( 'Customer Tiers', 'woo-analytics-dashboard' ); ?></h2>
				<table class="form-table">
					<tr>
						<th><?php esc_html_e( 'Platinum threshold', 'woo-analytics-dashboard' ); ?></th>
						<td><input type="number" name="wad_tier_platinum" min="0" value="<?php echo esc_attr( get_option( 'wad_tier_platinum', 3000 ) ); ?>" /> <?php echo esc_html( $currency ); ?></td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Gold threshold', 'woo-analytics-dashboard' ); ?></th>
						<td><input type="number" name="wad_tier_gold" min="0" value="<?php echo esc_attr( get_option( 'wad_tier_gold', 1500 ) ); ?>" /> <?php echo esc_html( $currency ); ?></td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Silver threshold', 'woo-analytics-dashboard' ); ?></th>
						<td><input type="number" name="wad_tier_silver" min="0" value="<?php echo esc_attr( get_option( 'wad_tier_silver', 500 ) ); ?>" /> <?php echo esc_html( $currency ); ?></td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Low Stock threshold', 'woo-analytics-dashboard' ); ?></th>
						<td><input type="number" name="wad_low_stock_threshold" min="1" value="<?php echo esc_attr( get_option( 'wad_low_stock_threshold', 10 ) ); ?>" /> <?php esc_html_e( 'units', 'woo-analytics-dashboard' ); ?></td>
					</tr>
				</table>

				<h2><?php esc_html_e( 'Access Control', 'woo-analytics-dashboard' ); ?></h2>
				<table class="form-table">
					<tr>
						<th><?php esc_html_e( 'Minimum Role', 'woo-analytics-dashboard' ); ?></th>
						<td>
							<select name="wad_min_role">
								<option value="manage_woocommerce" <?php selected( get_option( 'wad_min_role', 'manage_woocommerce' ), 'manage_woocommerce' ); ?>>
									<?php esc_html_e( 'Shop Manager (and above)', 'woo-analytics-dashboard' ); ?>
								</option>
								<option value="manage_options" <?php selected( get_option( 'wad_min_role', 'manage_woocommerce' ), 'manage_options' ); ?>>
									<?php esc_html_e( 'Administrator only', 'woo-analytics-dashboard' ); ?>
								</option>
							</select>
						</td>
					</tr>
				</table>

				<h2><?php esc_html_e( 'White Label', 'woo-analytics-dashboard' ); ?></h2>
				<table class="form-table">
					<tr>
						<th><?php esc_html_e( 'Dashboard Name', 'woo-analytics-dashboard' ); ?></th>
						<td>
							<input type="text" name="wad_dashboard_name" class="regular-text"
								value="<?php echo esc_attr( get_option( 'wad_dashboard_name', 'WooCommerce' ) ); ?>" />
						</td>
					</tr>
				</table>

				<h2><?php esc_html_e( 'Cache', 'woo-analytics-dashboard' ); ?></h2>
				<p>
					<a href="<?php echo esc_url( admin_url( 'admin-post.php?action=wad_clear_cache&_wpnonce=' . wp_create_nonce( 'wad_clear_cache' ) ) ); ?>"
						class="button button-secondary">
						<?php esc_html_e( 'Clear Dashboard Cache', 'woo-analytics-dashboard' ); ?>
					</a>
				</p>

				<?php submit_button(); ?>
			</form>

			<hr />

			<h2><?php esc_html_e( 'Demo Data', 'woo-analytics-dashboard' ); ?></h2>
			<p><?php esc_html_e( 'Populate your store with 42 fashion products, 25 customers, and ~200 orders spread across the past year — useful for testing the dashboard.', 'woo-analytics-dashboard' ); ?></p>
			<p style="display:flex;gap:12px;align-items:center;">
				<a href="<?php echo esc_url( admin_url( 'admin-post.php?action=wad_seed_data&_wpnonce=' . wp_create_nonce( 'wad_seed_data' ) ) ); ?>"
					class="button button-primary"
					onclick="return confirm('<?php esc_attr_e( 'This will create demo products, customers and orders. Continue?', 'woo-analytics-dashboard' ); ?>')">
					<?php esc_html_e( 'Seed Demo Data', 'woo-analytics-dashboard' ); ?>
				</a>
				<?php if ( WAD_Seeder::has_seeded_data() ) : ?>
					<a href="<?php echo esc_url( admin_url( 'admin-post.php?action=wad_clean_data&_wpnonce=' . wp_create_nonce( 'wad_clean_data' ) ) ); ?>"
						class="button button-secondary"
						onclick="return confirm('<?php esc_attr_e( 'This will permanently delete all seeded demo data. Continue?', 'woo-analytics-dashboard' ); ?>')">
						<?php esc_html_e( 'Remove Demo Data', 'woo-analytics-dashboard' ); ?>
					</a>
				<?php endif; ?>
			</p>
		</div>
		<?php
	}

	public static function handle_seed(): void {
		check_admin_referer( 'wad_seed_data' );
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'woo-analytics-dashboard' ) );
		}

		$result = WAD_Seeder::seed();

		wp_safe_redirect( add_query_arg( [
			'page'      => self::PAGE_SLUG,
			'seeded'    => 1,
			'products'  => $result['products'],
			'customers' => $result['customers'],
			'orders'    => $result['orders'],
		], admin_url( 'admin.php' ) ) );
		exit;
	}

	public static function handle_clean(): void {
		check_admin_referer( 'wad_clean_data' );
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'woo-analytics-dashboard' ) );
		}

		$result = WAD_Seeder::clean();

		wp_safe_redirect( add_query_arg( [
			'page'      => self::PAGE_SLUG,
			'cleaned'   => 1,
			'products'  => $result['products'],
			'customers' => $result['customers'],
			'orders'    => $result['orders'],
		], admin_url( 'admin.php' ) ) );
		exit;
	}
}

// Handle manual cache-clear action.
add_action( 'admin_post_wad_clear_cache', function () {
	check_admin_referer( 'wad_clear_cache' );
	if ( ! current_user_can( 'manage_woocommerce' ) ) {
		wp_die( esc_html__( 'Insufficient permissions.', 'woo-analytics-dashboard' ) );
	}
	wad_bust_cache();
	wp_safe_redirect( admin_url( 'admin.php?page=' . WAD_Settings::PAGE_SLUG . '&cache-cleared=1' ) );
	exit;
} );
