<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

final class Flexilay_Woo_Options {
	const OPTION_KEY = 'flexilay_woo_settings';

	public static function init() : void {
		// Migrate legacy gateway settings once.
		self::maybe_migrate_legacy_gateway_settings();
	}

	public static function get_all() : array {
		$opts = get_option( self::OPTION_KEY, array() );
		return is_array( $opts ) ? $opts : array();
	}

	public static function update_all( array $opts ) : bool {
		return update_option( self::OPTION_KEY, $opts, false );
	}

	public static function get( string $key, $default = '' ) {
		$opts = self::get_all();
		return array_key_exists( $key, $opts ) ? $opts[ $key ] : $default;
	}

	public static function set( string $key, $value ) : bool {
		$opts         = self::get_all();
		$opts[ $key ] = $value;
		return self::update_all( $opts );
	}

	public static function sanitize_api_base( string $api ) : string {
		$api = trim( $api );
		if ( $api === '' ) {
			return '';
		}

		$api = esc_url_raw( $api );
		if ( $api === '' ) {
			return '';
		}

		$parts = wp_parse_url( $api );
		if ( ! is_array( $parts ) || empty( $parts['scheme'] ) || empty( $parts['host'] ) ) {
			return '';
		}

		$scheme = strtolower( (string) $parts['scheme'] );
		// Enforce HTTPS in production; allow HTTP only in debug mode
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			if ( ! in_array( $scheme, array( 'https', 'http' ), true ) ) {
				return '';
			}
		} else {
			if ( $scheme !== 'https' ) {
				return '';
			}
		}

		$normalized = $scheme . '://' . strtolower( (string) $parts['host'] );
		if ( ! empty( $parts['port'] ) ) {
			$normalized .= ':' . (int) $parts['port'];
		}
		if ( ! empty( $parts['path'] ) ) {
			$normalized .= '/' . ltrim( (string) $parts['path'], '/' );
		}

		return rtrim( $normalized, '/' );
	}

	public static function get_api_base() : string {
		return self::sanitize_api_base( (string) self::get( 'api_base', '' ) );
	}

	public static function get_shop_domain() : string {
		$shop = (string) self::get( 'shop_domain', '' );
		$shop = trim( $shop );
		if ( $shop !== '' ) {
			return $shop;
		}
		$host = wp_parse_url( home_url(), PHP_URL_HOST );
		if ( ! $host ) {
			$host = (string) home_url();
			$host = preg_replace( '#^https?://#', '', $host );
			$host = preg_replace( '#/.*$#', '', $host );
		}
		return 'woocommerce:' . strtolower( (string) $host );
	}

	public static function ensure_install_token() : string {
		$token = (string) self::get( 'install_token', '' );
		$token = trim( $token );
		if ( $token !== '' ) {
			return $token;
		}
		$token = wp_generate_password( 32, false, false );
		self::set( 'install_token', $token );
		return $token;
	}

	public static function get_install_token() : string {
		return (string) self::get( 'install_token', '' );
	}

	public static function get_api_key() : string {
		return (string) self::get( 'api_key', '' );
	}

	public static function get_enable_crisp() : bool {
		$opts = self::get_all();
		return ! empty( $opts['enable_crisp'] );
	}

	public static function set_enable_crisp( bool $enabled ) : bool {
		$opts                 = self::get_all();
		$opts['enable_crisp'] = $enabled ? 1 : 0;
		return self::update_all( $opts );
	}

	public static function maybe_migrate_legacy_gateway_settings() : void {
		$opts = self::get_all();
		if ( ! empty( $opts ) ) {
			if ( isset( $opts['api_base'] ) ) {
				$sanitized = self::sanitize_api_base( (string) $opts['api_base'] );
				if ( $sanitized !== (string) $opts['api_base'] ) {
					$opts['api_base'] = $sanitized;
					self::update_all( $opts );
				}
			}
			return;
		}

		$legacy = get_option( 'woocommerce_flexilay_settings', array() );
		if ( ! is_array( $legacy ) || empty( $legacy ) ) {
			return;
		}

		$new = array(
			'api_base'      => isset( $legacy['flexilay_api_url'] ) ? self::sanitize_api_base( (string) $legacy['flexilay_api_url'] ) : '',
			'shop_domain'   => isset( $legacy['shop_domain'] ) ? (string) $legacy['shop_domain'] : '',
			'api_key'       => isset( $legacy['api_key'] ) ? (string) $legacy['api_key'] : '',
			'install_token' => '',
		);

		update_option( self::OPTION_KEY, $new, false );
	}
}
