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

/* ======================================================================
   247ChatMate Pro — Trial Abuse Prevention Registry Client
   PROTRIALREGISTRYLIVEFILES1

   Pro build only. No frontend calls. No visitor data. No IP address data.
====================================================================== */

if ( ! defined( 'MATEWA_PRO_TRIAL_REGISTRY_LAST_RESULT_OPTION' ) ) {
	define( 'MATEWA_PRO_TRIAL_REGISTRY_LAST_RESULT_OPTION', 'matewa_pro_trial_registry_last_result' );
}

if ( ! defined( 'MATEWA_PRO_TRIAL_REGISTRY_INSTALL_UUID_OPTION' ) ) {
	define( 'MATEWA_PRO_TRIAL_REGISTRY_INSTALL_UUID_OPTION', 'matewa_pro_trial_registry_install_uuid' );
}

if ( ! defined( 'MATEWA_PRO_TRIAL_REGISTRY_TIMEOUT' ) ) {
	define( 'MATEWA_PRO_TRIAL_REGISTRY_TIMEOUT', 12 );
}

if ( ! defined( 'MATEWA_PRO_TRIAL_REGISTRY_SECRET' ) ) {
	define( 'MATEWA_PRO_TRIAL_REGISTRY_SECRET', '' );
}

if ( ! function_exists( 'matewa_pro_trial_registry_get_endpoint' ) ) {
	function matewa_pro_trial_registry_get_endpoint() {
		$endpoint = defined( 'MATEWA_PRO_TRIAL_REGISTRY_ENDPOINT' ) ? (string) MATEWA_PRO_TRIAL_REGISTRY_ENDPOINT : '';
		$endpoint = trim( $endpoint );

		return esc_url_raw( $endpoint );
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_get_secret' ) ) {
	function matewa_pro_trial_registry_get_secret() {
		return defined( 'MATEWA_PRO_TRIAL_REGISTRY_SECRET' ) ? trim( (string) MATEWA_PRO_TRIAL_REGISTRY_SECRET ) : '';
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_is_configured' ) ) {
	function matewa_pro_trial_registry_is_configured() {
		return '' !== matewa_pro_trial_registry_get_endpoint() && '' !== matewa_pro_trial_registry_get_secret();
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_get_install_uuid' ) ) {
	function matewa_pro_trial_registry_get_install_uuid() {
		$uuid = trim( (string) get_option( MATEWA_PRO_TRIAL_REGISTRY_INSTALL_UUID_OPTION, '' ) );

		if ( '' !== $uuid ) {
			return $uuid;
		}

		$uuid = function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : md5( home_url( '/' ) . microtime( true ) . wp_rand() );
		update_option( MATEWA_PRO_TRIAL_REGISTRY_INSTALL_UUID_OPTION, $uuid, false );

		return $uuid;
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_normalise_whatsapp' ) ) {
	function matewa_pro_trial_registry_normalise_whatsapp( $number ) {
		$number = trim( (string) $number );
		$number = preg_replace( '/[^0-9+]/', '', $number );
		$number = is_string( $number ) ? $number : '';

		if ( '' === $number ) {
			return '';
		}

		if ( '+' === substr( $number, 0, 1 ) ) {
			return '+' . preg_replace( '/[^0-9]/', '', substr( $number, 1 ) );
		}

		return preg_replace( '/[^0-9]/', '', $number );
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_get_domain' ) ) {
	function matewa_pro_trial_registry_get_domain() {
		$host = wp_parse_url( home_url( '/' ), PHP_URL_HOST );
		$host = is_string( $host ) ? strtolower( trim( $host ) ) : '';
		$host = preg_replace( '/^www\./', '', $host );
		$host = preg_replace( '/[^a-z0-9.-]/', '', $host );

		return is_string( $host ) ? $host : '';
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_get_admin_email_hash' ) ) {
	function matewa_pro_trial_registry_get_admin_email_hash() {
		$email = '';

		if ( function_exists( 'matewa_get_owner_email' ) ) {
			$email = matewa_get_owner_email();
		} else {
			$email = sanitize_email( (string) get_option( 'matewa_marketing_email', '' ) );
		}

		$email = strtolower( trim( (string) $email ) );

		if ( '' === $email || ! is_email( $email ) ) {
			return '';
		}

		return hash_hmac( 'sha256', $email, matewa_pro_trial_registry_get_secret() );
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_store_last_result' ) ) {
	function matewa_pro_trial_registry_store_last_result( $result ) {
		if ( ! is_array( $result ) ) {
			$result = array();
		}

		$safe = array(
			'ok'                => ! empty( $result['ok'] ),
			'code'              => sanitize_key( (string) ( $result['code'] ?? 'unknown' ) ),
			'message'           => sanitize_text_field( (string) ( $result['message'] ?? '' ) ),
			'status'            => sanitize_key( (string) ( $result['status'] ?? '' ) ),
			'trial_reference'   => sanitize_text_field( (string) ( $result['trial_reference'] ?? '' ) ),
			'trial_started_at'  => isset( $result['trial_started_at'] ) ? (int) $result['trial_started_at'] : 0,
			'trial_expires_at'  => isset( $result['trial_expires_at'] ) ? (int) $result['trial_expires_at'] : 0,
			'checked_at'        => time(),
			'endpoint'          => matewa_pro_trial_registry_get_endpoint(),
			'domain'            => matewa_pro_trial_registry_get_domain(),
			'install_uuid'      => matewa_pro_trial_registry_get_install_uuid(),
			'configured'        => matewa_pro_trial_registry_is_configured(),
			'privacy_note'      => 'No IP address, visitor data, user agent, or raw admin email is collected by the plugin registry client.',
		);

		update_option( MATEWA_PRO_TRIAL_REGISTRY_LAST_RESULT_OPTION, $safe, false );

		return $safe;
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_get_last_result' ) ) {
	function matewa_pro_trial_registry_get_last_result() {
		$stored = get_option( MATEWA_PRO_TRIAL_REGISTRY_LAST_RESULT_OPTION, array() );

		return is_array( $stored ) ? $stored : array();
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_error' ) ) {
	function matewa_pro_trial_registry_error( $code, $message ) {
		$result = array(
			'ok'      => false,
			'code'    => sanitize_key( (string) $code ),
			'message' => sanitize_text_field( (string) $message ),
			'status'  => 'blocked',
		);

		return matewa_pro_trial_registry_store_last_result( $result );
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_build_payload' ) ) {
	function matewa_pro_trial_registry_build_payload() {
		$whatsapp_number = matewa_pro_trial_registry_normalise_whatsapp( get_option( 'matewa_number', '' ) );
		$domain          = matewa_pro_trial_registry_get_domain();
		$trial_days      = defined( 'MATEWA_TRIAL_DAYS' ) ? max( 1, (int) MATEWA_TRIAL_DAYS ) : 28;

		return array(
			'action'            => 'start_trial',
			'plugin'            => '247chatmate',
			'plugin_version'    => defined( 'MATEWA_VERSION' ) ? (string) MATEWA_VERSION : '',
			'site_url'          => esc_url_raw( home_url( '/' ) ),
			'domain'            => $domain,
			'whatsapp_number'   => $whatsapp_number,
			'install_uuid'      => matewa_pro_trial_registry_get_install_uuid(),
			'admin_email_hash'  => matewa_pro_trial_registry_get_admin_email_hash(),
			'trial_days'        => $trial_days,
			'request_created'   => time(),
		);
	}
}

if ( ! function_exists( 'matewa_pro_trial_registry_start_trial' ) ) {
	function matewa_pro_trial_registry_start_trial() {
		if ( ! matewa_pro_trial_registry_is_configured() ) {
			return matewa_pro_trial_registry_error(
				'registry_not_configured',
				'Pro trial validation is not configured. Trial start has been blocked safely.'
			);
		}

		$payload = matewa_pro_trial_registry_build_payload();

		if ( empty( $payload['whatsapp_number'] ) ) {
			return matewa_pro_trial_registry_error(
				'missing_whatsapp',
				'Add and save a WhatsApp number before starting a Pro trial.'
			);
		}

		if ( empty( $payload['domain'] ) ) {
			return matewa_pro_trial_registry_error(
				'missing_domain',
				'This site domain could not be confirmed. Trial start has been blocked safely.'
			);
		}

		$body = wp_json_encode( $payload, JSON_UNESCAPED_SLASHES );

		if ( ! is_string( $body ) || '' === $body ) {
			return matewa_pro_trial_registry_error(
				'invalid_payload',
				'Pro trial validation payload could not be created.'
			);
		}

		$timestamp = (string) time();
		$signature = hash_hmac( 'sha256', $timestamp . '.' . $body, matewa_pro_trial_registry_get_secret() );

		$response = wp_remote_post(
			matewa_pro_trial_registry_get_endpoint(),
			array(
				'timeout' => MATEWA_PRO_TRIAL_REGISTRY_TIMEOUT,
				'headers' => array(
					'Content-Type'        => 'application/json; charset=utf-8',
					'X-Matewa-Timestamp'  => $timestamp,
					'X-Matewa-Signature'  => $signature,
					'X-Matewa-Registry'   => 'pro-trial-v1',
				),
				'body'    => $body,
			)
		);

		if ( is_wp_error( $response ) ) {
			return matewa_pro_trial_registry_error(
				'registry_unavailable',
				'Pro trial validation server could not be reached. Trial start has been blocked safely.'
			);
		}

		$status_code = (int) wp_remote_retrieve_response_code( $response );
		$response_body = (string) wp_remote_retrieve_body( $response );
		$data = json_decode( $response_body, true );

		if ( $status_code < 200 || $status_code >= 300 || ! is_array( $data ) ) {
			return matewa_pro_trial_registry_error(
				'invalid_registry_response',
				'Pro trial validation returned an invalid response. Trial start has been blocked safely.'
			);
		}

		$data['ok'] = ! empty( $data['ok'] );
		$data['code'] = sanitize_key( (string) ( $data['code'] ?? 'unknown' ) );
		$data['message'] = sanitize_text_field( (string) ( $data['message'] ?? '' ) );
		$data['status'] = sanitize_key( (string) ( $data['status'] ?? '' ) );
		$data['trial_reference'] = sanitize_text_field( (string) ( $data['trial_reference'] ?? '' ) );
		$data['trial_started_at'] = isset( $data['trial_started_at'] ) ? (int) $data['trial_started_at'] : 0;
		$data['trial_expires_at'] = isset( $data['trial_expires_at'] ) ? (int) $data['trial_expires_at'] : 0;

		return matewa_pro_trial_registry_store_last_result( $data );
	}
}
