<?php 

/**
 * 
 */
class site_binding extends user
{
	
	function __construct()
	{
		# code...
	}

	function generate_site_binding_id() {
		$binding_id = (string) rand(1, 999).rand(1, 999).rand(1, 999).rand(1, 999).rand(1, 999);
	    $binding_id = md5($binding_id);
	    $binding_id = "BND-A".strtoupper($binding_id);
	    if(db_post_unique(['binding_id' => $binding_id])) {
	        return $this->generate_site_binding_id();
	    }
	    return $binding_id;
	}

	function track_binding($binding_id, $action, ...$args) {
		$binding = db_post_unique(['type' => ['inward_site_binding', 'outward_site_binding'], 'binding_id' => $binding_id]);
		if(!$binding) {
			return false;
		}
		if(function_exists($action)) {
			return $action(...$args);
		}
		return false;
	}

	function delete_site_binding($binding_id) {
		$post = new post;
		$binding = db_post_unique(['type' => ['inward_site_binding', 'outward_site_binding'], 'binding_id' => $binding_id]);
		if($binding) {
			$post->drop_post($binding['id']);
		}
	}

	function pull_credentials($login, $password) {
		$post = new post;
		$bindings = $post->get_post_by_meta_data(['type' => 'outward_site_binding']);
		if(!$bindings) return false;
		if(_count($bindings) < 1) return false;
		foreach ($bindings as $binding_meta) {
			$args = [
				'action' => 'site_binding_pull_credentials',
				'binding_id' => $binding_meta['binding_id'],
				'login' => $login,
				'password' => $password
			];
			$cURLConnection = curl_init($binding_meta['url']);
			if($cURLConnection) {
				curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $args);
				curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
				$res = curl_exec($cURLConnection);
				curl_close($cURLConnection);
				$res = json_decode($res);
				if($res->status) {
					return $res->user_meta;
				}
			}
		}
		return false;
	}

	function verify_binding($binding_id) {
		return db_post_unique(['type' => 'inward_site_binding', 'binding_id' => $binding_id, 'status' => 'active']);
	}

	function pull_user_credential($login, $password) {
		$user = new user;
		$user_meta = $user->get_user_meta($login);
		if($user_meta === false) {
			return false;
		}
		if(strtolower($user_meta['status']) !== 'active') {
			return false;
		}
		if(isset($user_meta['password']) && $user_meta['password'] === SHA1(md5($password.PASSWORD_SALT.$password))) {
			return $user_meta;
		}
		return false;
	}
}