<?php
/**
 * Settings form handler.
 *
 * @package WPLens
 */

namespace WPLens\Admin;

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

final class Settings {

	public function register(): void {
		add_action( 'admin_init', array( $this, 'maybe_save' ) );
	}

	public function maybe_save(): void {
		if ( ! isset( $_POST['wplens_save_settings'] ) ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		check_admin_referer( 'wplens_save_settings' );

		$current = \WPLens\Utils\Options::all();

		// Modules.
		$current['modules']['crawler_log']       = ! empty( $_POST['crawler_log'] );
		$current['modules']['aeo_scans']         = ! empty( $_POST['aeo_scans'] );
		$current['modules']['citation_tracking'] = ! empty( $_POST['citation_tracking'] );
		$current['modules']['weekly_report']     = ! empty( $_POST['weekly_report'] );

		// Crawler.
		$current['crawler']['retention_days']  = isset( $_POST['retention_days'] ) ? max( 1, min( 3650, absint( $_POST['retention_days'] ) ) ) : 90;
		$current['crawler']['sample_rate']     = isset( $_POST['sample_rate'] ) ? max( 0.0, min( 1.0, (float) $_POST['sample_rate'] ) ) : 1.0;
		$current['crawler']['log_admin_paths'] = ! empty( $_POST['log_admin_paths'] );
		$current['crawler']['log_404s']        = ! empty( $_POST['log_404s'] );

		// Reporting recipients.
		$recipients = array();
		if ( isset( $_POST['recipients'] ) ) {
			$raw = sanitize_textarea_field( wp_unslash( (string) $_POST['recipients'] ) );
			foreach ( preg_split( "/[\r\n,]+/", $raw ) as $line ) {
				$email = sanitize_email( trim( $line ) );
				if ( '' !== $email && is_email( $email ) ) {
					$recipients[] = $email;
				}
			}
		}
		$current['reporting']['recipients'] = array_values( array_unique( $recipients ) );

		// Citation target domain (read-only normally — but allow override).
		if ( isset( $_POST['target_domain'] ) ) {
			$dom = sanitize_text_field( wp_unslash( (string) $_POST['target_domain'] ) );
			$current['citations']['target_domain'] = $dom;
		}

		// Schema.
		$current['schema']['enabled'] = ! empty( $_POST['schema_enabled'] );

		$disabled = array();
		if ( isset( $_POST['schema_disabled'] ) && is_array( $_POST['schema_disabled'] ) ) {
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitised below per-item.
			$raw = array_map( 'strval', (array) wp_unslash( $_POST['schema_disabled'] ) );
			$disabled = array_map( 'sanitize_key', $raw );
		}
		$current['schema']['disabled_types'] = array_values( array_unique( $disabled ) );

		$org_name  = isset( $_POST['org_name'] )    ? sanitize_text_field( wp_unslash( $_POST['org_name'] ) )    : '';
		$org_logo  = isset( $_POST['org_logo'] )    ? esc_url_raw( wp_unslash( $_POST['org_logo'] ) )            : '';
		$org_email = isset( $_POST['org_email'] )   ? sanitize_email( wp_unslash( $_POST['org_email'] ) )        : '';
		$same_as_raw = isset( $_POST['org_same_as'] ) ? sanitize_textarea_field( wp_unslash( $_POST['org_same_as'] ) ) : '';
		$same_as = array();
		foreach ( preg_split( "/[\r\n,]+/", $same_as_raw ) as $u ) {
			$u = esc_url_raw( trim( $u ) );
			if ( '' !== $u ) { $same_as[] = $u; }
		}
		$current['schema']['organization'] = array(
			'name'          => $org_name,
			'logo'          => $org_logo,
			'contact_email' => $org_email,
			'same_as'       => array_values( array_unique( $same_as ) ),
		);

		// Privacy.
		$current['privacy']['remove_data_on_uninstall'] = ! empty( $_POST['remove_data_on_uninstall'] );

		// API key — store encrypted, only if a new value was POSTed.
		$openai_key_raw = isset( $_POST['openai_api_key'] )
			? sanitize_text_field( wp_unslash( $_POST['openai_api_key'] ) )
			: '';
		if ( '' !== trim( $openai_key_raw ) ) {
			$keys = get_option( 'wplens_provider_keys', array() );
			if ( ! is_array( $keys ) ) {
				$keys = array();
			}
			$keys['openai'] = \WPLens\Utils\Encryption::encrypt( $openai_key_raw );
			update_option( 'wplens_provider_keys', $keys, false );
		}

		// Remove key if "clear" was clicked.
		if ( ! empty( $_POST['wplens_clear_openai_key'] ) ) {
			$keys = get_option( 'wplens_provider_keys', array() );
			if ( is_array( $keys ) ) {
				unset( $keys['openai'] );
				update_option( 'wplens_provider_keys', $keys, false );
			}
		}

		\WPLens\Utils\Options::save( $current );
		add_settings_error( 'lens-ai-visibility-monitor', 'settings-saved', __( 'Settings saved.', 'lens-ai-visibility-monitor' ), 'updated' );
	
		// If we're inside the welcome wizard, redirect to the next step.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_POST['_wp_http_referer'] )
			? wp_parse_url( esc_url_raw( wp_unslash( $_POST['_wp_http_referer'] ) ), PHP_URL_QUERY )
			: '';
		if ( is_string( $page ) && false !== strpos( $page, 'page=lens-welcome' ) ) {
			$current_step = 1;
			if ( preg_match( '/step=(\d+)/', (string) $page, $m ) ) {
				$current_step = (int) $m[1];
			}
			$next = min( 4, $current_step + 1 );
			wp_safe_redirect( admin_url( 'admin.php?page=lens-welcome&step=' . $next ) );
			exit;
		}
}
}
