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

if ( ! class_exists( 'EXECVITR_License' ) ) {

	final class EXECVITR_License {

		/** Domain getter (www. temizlenmiş) */
		private static function site_domain(): string {
			$host = (string) wp_parse_url( home_url(), PHP_URL_HOST );
			return strtolower( preg_replace( '/^www\./i', '', $host ) );
		}

		/** Lisans doğrulama URL’i oluşturur */
		private static function check_url(): string {
			$base = rtrim( EXECVITR_LICENSE_CHECK_URL, '/' );
			return add_query_arg( 'domain', rawurlencode( self::site_domain() ), $base );
		}

		/** Uzak lisans doğrulama */
		public static function verify(): bool {
			$url = self::check_url();

			$res = wp_remote_get( $url, [
				'timeout' => 10,
				'headers' => [ 'Accept' => 'application/json' ],
			] );

			// Hata durumunda invalid işaretle
			if ( is_wp_error( $res ) ) {
				update_option( EXECVITR_OPT_LICENSE_STATUS, 'invalid' );
				update_option( EXECVITR_OPT_LICENSE_LASTCHECK, time() );
				return false;
			}

			$code = wp_remote_retrieve_response_code( $res );
			$body = wp_remote_retrieve_body( $res );

			$ok   = false;
			$meta = [ 'raw' => $body ];

			if ( $code === 200 && $body ) {
				$json = json_decode( $body, true );
				if ( is_array( $json ) ) {
					$meta['json']    = $json;
					$meta['status']  = $json['status']  ?? null;
					$meta['domain']  = $json['domain']  ?? null;
					$meta['email']   = $json['email']   ?? null;
					$meta['name']    = $json['name']    ?? null;
					$meta['expires'] = $json['expires'] ?? null;

					// Domain eşleşmesi ve geçerlilik kontrolü
					$domain_ok = ( strtolower( (string) ( $json['domain'] ?? '' ) ) === self::site_domain() );
					$expires_ts = strtotime( $json['expires'] ?? '' );
					$not_expired = $expires_ts ? time() <= $expires_ts : true;

					$ok = ( ( $json['status'] ?? '' ) === 'valid' ) && $domain_ok && $not_expired;
				}
			}

			update_option( EXECVITR_OPT_LICENSE_META, wp_json_encode( $meta ) );
			update_option( EXECVITR_OPT_LICENSE_STATUS, $ok ? 'valid' : 'invalid' );
			update_option( EXECVITR_OPT_LICENSE_LASTCHECK, time() );

			return $ok;
		}
		
			public static function maybe_ping(): void {
    $last = (int) get_option( EXECVITR_OPT_LICENSE_LASTCHECK, 0 );
    if ( $last && time() - $last < 6 * HOUR_IN_SECONDS ) return;
    self::verify();
}

	}
}

/** PRO açık mı? */
if ( ! function_exists( 'execvitr_is_pro_active' ) ) {
	function execvitr_is_pro_active(): bool {
		$status = get_option( EXECVITR_OPT_LICENSE_STATUS, 'invalid' );
		if ( $status !== 'valid' ) return false;

		$meta_raw = get_option( EXECVITR_OPT_LICENSE_META, '' );
		$meta = json_decode( $meta_raw, true );
		$json = is_array( $meta['json'] ?? null ) ? $meta['json'] : [];

		$expires_ts = strtotime( $json['expires'] ?? '' );
		if ( $expires_ts && time() > $expires_ts ) return false;

		return true;
	}
}
