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

/* ======================================================================
   247ChatMate Pro — Founder Beta Registry Client
   FOUNDERBETA3F2PLUGINWIRE

   Pro build only. Admin-side only. No frontend calls. No visitor data.
   No IP address collection, storage, hashing, transmission, logging,
   comparison, or use by this client.
====================================================================== */

if ( ! defined( 'MATEWA_FOUNDER_BETA_LAST_RESULT_OPTION' ) ) {
	define( 'MATEWA_FOUNDER_BETA_LAST_RESULT_OPTION', 'matewa_founder_beta_last_result' );
}

if ( ! defined( 'MATEWA_FOUNDER_BETA_INSTALL_UUID_OPTION' ) ) {
	define( 'MATEWA_FOUNDER_BETA_INSTALL_UUID_OPTION', 'matewa_founder_beta_install_uuid' );
}

if ( ! defined( 'MATEWA_FOUNDER_BETA_TIMEOUT' ) ) {
	define( 'MATEWA_FOUNDER_BETA_TIMEOUT', 6 );
}

if ( ! defined( 'MATEWA_FOUNDER_BETA_CODE_PREFIX' ) ) {
	define( 'MATEWA_FOUNDER_BETA_CODE_PREFIX', 'FBETA-' );
}

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

		return esc_url_raw( $endpoint );
	}
}

if ( ! function_exists( 'matewa_founder_beta_is_configured' ) ) {
	function matewa_founder_beta_is_configured() {
		return '' !== matewa_founder_beta_get_endpoint();
	}
}

if ( ! function_exists( 'matewa_founder_beta_get_install_uuid' ) ) {
	function matewa_founder_beta_get_install_uuid() {
		if ( function_exists( 'matewa_pro_trial_registry_get_install_uuid' ) ) {
			return matewa_pro_trial_registry_get_install_uuid();
		}

		$uuid = trim( (string) get_option( MATEWA_FOUNDER_BETA_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_FOUNDER_BETA_INSTALL_UUID_OPTION, $uuid, false );

		return $uuid;
	}
}

if ( ! function_exists( 'matewa_founder_beta_normalise_whatsapp' ) ) {
	function matewa_founder_beta_normalise_whatsapp( $number ) {
		if ( function_exists( 'matewa_pro_trial_registry_normalise_whatsapp' ) ) {
			return 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_founder_beta_get_site_url' ) ) {
	function matewa_founder_beta_get_site_url() {
		return esc_url_raw( home_url( '/' ) );
	}
}

if ( ! function_exists( 'matewa_founder_beta_get_admin_email_hash' ) ) {
	function matewa_founder_beta_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( 'sha256', $email );
	}
}

if ( ! function_exists( 'matewa_founder_beta_sanitise_access_code' ) ) {
	function matewa_founder_beta_sanitise_access_code( $code ) {
		$code = strtoupper( trim( (string) $code ) );
		$code = preg_replace( '/[^A-Z0-9_\-.]/', '', $code );

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

if ( ! function_exists( 'matewa_founder_beta_is_access_code' ) ) {
	function matewa_founder_beta_is_access_code( $code ) {
		$code = matewa_founder_beta_sanitise_access_code( $code );

		if ( '' === $code ) {
			return false;
		}

		$prefix = defined( 'MATEWA_FOUNDER_BETA_CODE_PREFIX' ) ? (string) MATEWA_FOUNDER_BETA_CODE_PREFIX : 'FBETA-';

		return 0 === strpos( $code, strtoupper( $prefix ) );
	}
}

if ( ! function_exists( 'matewa_founder_beta_get_saved_access_code' ) ) {
	function matewa_founder_beta_get_saved_access_code() {
		$code = function_exists( 'matewa_get_license_key' ) ? matewa_get_license_key() : get_option( 'matewa_license_key', '' );
		$code = matewa_founder_beta_sanitise_access_code( $code );

		return matewa_founder_beta_is_access_code( $code ) ? $code : '';
	}
}

if ( ! function_exists( 'matewa_founder_beta_get_domain' ) ) {
	function matewa_founder_beta_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_founder_beta_store_last_result' ) ) {
	function matewa_founder_beta_store_last_result( $result ) {
		if ( ! is_array( $result ) ) {
			$result = array();
		}

		$safe = array(
			'success'      => ! empty( $result['success'] ),
			'code'         => sanitize_key( (string) ( $result['code'] ?? ( $result['message'] ?? 'unknown' ) ) ),
			'message'      => sanitize_text_field( (string) ( $result['message'] ?? '' ) ),
			'status'       => sanitize_key( (string) ( $result['status'] ?? '' ) ),
			'beta_start'   => sanitize_text_field( (string) ( $result['beta_start'] ?? '' ) ),
			'beta_expiry'  => sanitize_text_field( (string) ( $result['beta_expiry'] ?? '' ) ),
			'converted'    => ! empty( $result['converted'] ),
			'checked_at'   => time(),
			'endpoint'     => matewa_founder_beta_get_endpoint(),
			'site_url'     => matewa_founder_beta_get_site_url(),
			'domain'       => matewa_founder_beta_get_domain(),
			'install_uuid'          => matewa_founder_beta_get_install_uuid(),
			'activation_code_hash' => isset( $result['activation_code_hash'] ) ? sanitize_text_field( (string) $result['activation_code_hash'] ) : '',
			'configured'           => matewa_founder_beta_is_configured(),
			'privacy_note' => 'No IP address, visitor data, user agent, or raw admin email is collected by the Founder Beta registry client.',
		);

		update_option( MATEWA_FOUNDER_BETA_LAST_RESULT_OPTION, $safe, false );

		return $safe;
	}
}

if ( ! function_exists( 'matewa_founder_beta_get_last_result' ) ) {
	function matewa_founder_beta_get_last_result() {
		$stored = get_option( MATEWA_FOUNDER_BETA_LAST_RESULT_OPTION, array() );

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

if ( ! function_exists( 'matewa_clear_founder_beta_validation_state' ) ) {
	function matewa_clear_founder_beta_validation_state( $old_access_code = '', $new_access_code = '' ) {
		$old_access_code = matewa_founder_beta_sanitise_access_code( $old_access_code );
		$new_access_code = matewa_founder_beta_sanitise_access_code( $new_access_code );

		$old_is_beta = matewa_founder_beta_is_access_code( $old_access_code );
		$new_is_beta = matewa_founder_beta_is_access_code( $new_access_code );

		if ( $new_is_beta && $old_access_code === $new_access_code ) {
			return false;
		}

		if ( ! $old_is_beta && ! $new_is_beta ) {
			$stored = matewa_founder_beta_get_last_result();

			if ( empty( $stored ) ) {
				return false;
			}
		}

		delete_option( MATEWA_FOUNDER_BETA_LAST_RESULT_OPTION );

		return true;
	}
}

if ( ! function_exists( 'matewa_founder_beta_get_expiry_timestamp' ) ) {
	function matewa_founder_beta_get_expiry_timestamp( $beta_expiry = '' ) {
		$beta_expiry = trim( (string) $beta_expiry );

		if ( '' === $beta_expiry ) {
			$stored      = matewa_founder_beta_get_last_result();
			$beta_expiry = isset( $stored['beta_expiry'] ) ? trim( (string) $stored['beta_expiry'] ) : '';
		}

		if ( '' === $beta_expiry ) {
			return 0;
		}

		if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $beta_expiry ) ) {
			$beta_expiry .= ' 23:59:59 UTC';
		}

		$timestamp = strtotime( $beta_expiry );

		return $timestamp ? (int) $timestamp : 0;
	}
}

if ( ! function_exists( 'matewa_founder_beta_is_active' ) ) {
	function matewa_founder_beta_is_active() {
		$stored = matewa_founder_beta_get_last_result();

		if ( ! is_array( $stored ) || empty( $stored['success'] ) ) {
			return false;
		}

		// PAIDLICENCECLEARSYNC3F5E3:
		// Founder Beta should not silently keep Pro active after the access key
		// has been removed or replaced by a paid LemonSqueezy key. The stored
		// registry result remains available for admin history, but active beta
		// entitlement requires the private FBETA key to still be saved.
		if ( '' === matewa_founder_beta_get_saved_access_code() ) {
			return false;
		}

		$status    = isset( $stored['status'] ) ? sanitize_key( (string) $stored['status'] ) : '';
		$converted = ! empty( $stored['converted'] );

		// PAIDBETAENTITLEMENTSEPARATION3F5E1:
		// Converted Founder Beta records must not continue granting beta access.
		// A valid paid LemonSqueezy licence is handled separately and wins in
		// matewa_get_entitlement_state() before this helper is consulted.
		if ( $converted || 'converted' === $status || 'active' !== $status ) {
			return false;
		}

		$expiry_ts = matewa_founder_beta_get_expiry_timestamp( $stored['beta_expiry'] ?? '' );

		if ( $expiry_ts <= 0 ) {
			return false;
		}

		return time() <= $expiry_ts;
	}
}

if ( ! function_exists( 'matewa_founder_beta_error' ) ) {
	function matewa_founder_beta_error( $code, $message ) {
		$result = array(
			'success' => false,
			'code'    => sanitize_key( (string) $code ),
			'message' => sanitize_text_field( (string) $message ),
			'status'  => 'unavailable',
		);

		return matewa_founder_beta_store_last_result( $result );
	}
}

if ( ! function_exists( 'matewa_founder_beta_build_payload' ) ) {
	function matewa_founder_beta_build_payload( $access_code = '' ) {
		$access_code = matewa_founder_beta_sanitise_access_code( $access_code );

		if ( '' === $access_code ) {
			$access_code = matewa_founder_beta_get_saved_access_code();
		}

		return array(
			'site_url'     => matewa_founder_beta_get_site_url(),
			'whatsapp'     => matewa_founder_beta_normalise_whatsapp( get_option( 'matewa_number', '' ) ),
			'install_uuid' => matewa_founder_beta_get_install_uuid(),
			'email_hash'   => matewa_founder_beta_get_admin_email_hash(),
			'beta_code'    => $access_code,
		);
	}
}

if ( ! function_exists( 'matewa_founder_beta_register_activation' ) ) {
	function matewa_founder_beta_register_activation( $access_code = '' ) {
		if ( ! matewa_founder_beta_is_configured() ) {
			return matewa_founder_beta_error(
				'registry_not_configured',
				'Founder Beta registry is not configured. Admin remains usable; try again after the endpoint is configured.'
			);
		}

		$access_code = matewa_founder_beta_sanitise_access_code( $access_code );

		if ( '' === $access_code ) {
			$access_code = matewa_founder_beta_get_saved_access_code();
		}

		if ( ! matewa_founder_beta_is_access_code( $access_code ) ) {
			return matewa_founder_beta_error(
				'missing_beta_code',
				'Enter a valid access key before activating this private entitlement.'
			);
		}

		$payload = matewa_founder_beta_build_payload( $access_code );

		if ( empty( $payload['site_url'] ) ) {
			return matewa_founder_beta_error(
				'missing_site_url',
				'This site URL could not be confirmed. Founder Beta registration was not completed.'
			);
		}

		if ( empty( $payload['whatsapp'] ) ) {
			return matewa_founder_beta_error(
				'missing_whatsapp',
				'Add and save a WhatsApp number before registering Founder Beta.'
			);
		}

		if ( empty( $payload['install_uuid'] ) ) {
			return matewa_founder_beta_error(
				'missing_install_uuid',
				'This plugin install could not be identified. Founder Beta registration was not completed.'
			);
		}

		$body = wp_json_encode( $payload, JSON_UNESCAPED_SLASHES );

		if ( ! is_string( $body ) || '' === $body ) {
			return matewa_founder_beta_error(
				'invalid_payload',
				'Founder Beta registration payload could not be created.'
			);
		}

		$response = wp_remote_post(
			matewa_founder_beta_get_endpoint(),
			array(
				'timeout' => MATEWA_FOUNDER_BETA_TIMEOUT,
				'headers' => array(
					'Accept'       => 'application/json',
					'Content-Type' => 'application/json; charset=utf-8',
				),
				'body'    => $body,
			)
		);

		if ( is_wp_error( $response ) ) {
			return matewa_founder_beta_error(
				'registry_unavailable',
				'Founder Beta registry could not be reached. Admin remains usable; try again later.'
			);
		}

		$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_founder_beta_error(
				'invalid_registry_response',
				'Founder Beta registry returned an invalid response. Admin remains usable; try again later.'
			);
		}

		$data['success']     = ! empty( $data['success'] );
		$data['code']        = sanitize_key( (string) ( $data['message'] ?? 'unknown' ) );
		$data['message']     = sanitize_text_field( (string) ( $data['message'] ?? '' ) );
		$data['status']      = sanitize_key( (string) ( $data['status'] ?? '' ) );
		$data['beta_start']  = sanitize_text_field( (string) ( $data['beta_start'] ?? '' ) );
		$data['beta_expiry'] = sanitize_text_field( (string) ( $data['beta_expiry'] ?? '' ) );
		$data['converted']   = ! empty( $data['converted'] );
		$data['activation_code_hash'] = hash( 'sha256', $access_code . '|' . home_url( '/' ) );

		return matewa_founder_beta_store_last_result( $data );
	}
}
