<?php

namespace HaoZiTeam\IPUA\Service;

use Exception;
use function HaoZiTeam\IPUA\request;
use const HaoZiTeam\IPUA\PLUGIN_DIR;

/**
 * Class IP
 * 该类用于实现插件的IP属地功能
 * @package HaoZiTeam\IPUA\Service
 */
class IP {
	private $setting;
	private $ip;
	private $ip_info;

	public function __construct( $ip = "" ) {
		$this->setting = is_multisite() ? get_site_option( 'wp_ipua_setting' ) : get_option( 'wp_ipua_setting' );
		$this->ip      = $ip;
	}

	public function get_ip_info() {
		if ( empty( $this->ip ) || ! is_string( $this->ip ) ) {
			return [];
		}

		if ( isset( $this->setting['from'] ) && $this->setting['from'] == 'qqwry' ) {
			try {
				$qqwry = new QQWry( PLUGIN_DIR . '/qqwry.dat' );
			} catch ( Exception $e ) {
				return [ "country" => "读取数据失败", "area" => "读取数据失败" ];
			}

			return $qqwry->query( $this->ip );
		}

		if ( ! isset( $this->setting['tx_key'] ) ) {
			return [];
		}
		if ( ! $this->get_ip_info_from_cache( $this->ip ) ) {
			$api_url    = "https://apis.map.qq.com/ws/location/v1/ip?key={$this->setting['tx_key']}&ip={$this->ip}&output=json";
			$result_raw = request( $api_url );
			// 判断是否为JSON格式
			if ( empty( $result_raw ) || ! is_string( $result_raw ) || ! is_array( json_decode( $result_raw,
					true ) ) ) {
				return [];
			} else {
				$result = json_decode( $result_raw, true );
			}
			// 判断响应是否正确
			if ( isset( $result['status'] ) && $result['status'] == 0 ) {
				$this->ip_info = $result['result']['ad_info'];
				$this->set_ip_info_cache( $this->ip, $this->ip_info );
			} else {
				return [];
			}

			return $this->ip_info;
		}


		return $this->ip_info;

	}

	private function get_ip_info_from_cache( $ip ) {
		// 通过将IP分割进行缓存，可以大大提高缓存命中率
		// 首先判断是ipv4还是ipv6，ipv6过于复杂，暂时不考虑缓存
		if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
			list( $ip1, $ip2, $ip3, $ip4 ) = explode( ".", $ip );
			$cache_key = "wp_ipua_{$ip1}_{$ip2}_{$ip3}";
			if ( get_transient( $cache_key ) ) {
				$this->ip_info = get_transient( $cache_key );

				return true;
			}

		}

		return false;
	}

	private function set_ip_info_cache( $ip, $ip_info ) {

		// 如果用户设置了不缓存，则不缓存
		if ( $this->setting['cache'] == 'no' ) {
			return;
		}
		// 通过将IP分割进行缓存，可以大大提高缓存命中率
		// 首先判断是ipv4还是ipv6，ipv6过于复杂，暂时不考虑缓存
		if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
			list( $ip1, $ip2, $ip3, $ip4 ) = explode( ".", $ip );
			$cache_key = "wp_ipua_{$ip1}_{$ip2}_{$ip3}";
			set_transient( $cache_key, $ip_info, 84000 * $this->setting['cache'] );

		}

	}
}
