<?PHP
// load WP
require_once("../wp-load.php");

// config
define("ipn_membership_role_level","2");

// IPN processor
class CB_IPN_membership
{
	private $secret_keys = [
		// old
		"SBP"=> "BGEBA9AUDH",
		// new
		"BMP"=>"BGEBA9AUDH",
		"GTM"=>"BGEBA9AUDH",
		"GUF"=>"BGEBA9AUDH",
		"HAF"=>"BGEBA9AUDH",
		"HBT"=>"BGEBA9AUDH",
		"KVP"=>"BGEBA9AUDH",
		"LPT"=>"BGEBA9AUDH",
		"NCP"=>"BGEBA9AUDH",
		"NEP"=>"BGEBA9AUDH",
		"NSP"=>"BGEBA9AUDH",
		"PMC"=>"BGEBA9AUDH",
		"PST"=>"BGEBA9AUDH",
		"QUP"=>"BGEBA9AUDH",
		"SBPN"=>"BGEBA9AUDH",
		"SER"=>"BGEBA9AUDH",
		"SOC"=>"BGEBA9AUDH",
		"VIF"=>"BGEBA9AUDH",
		"MSP"=>"BGEBA9AUDH",
		"DSP"=>"BGEBA9AUDH",
		"AXP"=>"BGEBA9AUDH"
	];
	

	public function __construct()
	{
		if(isset($_REQUEST["k"]) && isset($this->secret_keys[$_REQUEST["k"]]))
		{
			$order_data = json_decode(file_get_contents('php://input'),true);
			$order_data = json_decode(trim(
				openssl_decrypt(base64_decode($order_data['notification']),
				'AES-256-CBC',
				substr(sha1($this->secret_keys[$_REQUEST["k"]]), 0, 32),
				OPENSSL_RAW_DATA,
				base64_decode($order_data['iv'])), "\0..\32"),true
			);

			$member_id = SwpmMemberUtils::create_swpm_member_entry_from_array_data([
				"user_name"=>$ipn_data["customer"]["shipping"]["email"],
				"first_name"=>$ipn_data["customer"]["shipping"]["firstName"],
				"last_name"=>$ipn_data["customer"]["shipping"]["lastName"],
				"password"=>$ipn_data["receipt"],
				"email"=>$ipn_data["customer"]["shipping"]["email"],
				"phone"=>$ipn_data["customer"]["shipping"]["phoneNumber"],
				"address_street"=>$ipn_data["customer"]["shipping"]["address"]["address1"],
				"address_city"=>$ipn_data["customer"]["shipping"]["address"]["city"],
				"address_state"=>$ipn_data["customer"]["shipping"]["address"]["state"],
				"address_zipcode"=>$ipn_data["customer"]["shipping"]["address"]["postalCode"],
				"member_since"=>date("Y-m-d"),
				"membership_level"=>ipn_membership_role_level
			]);
		}
	}
}

new CB_IPN_membership();