<?php

namespace Vinteract\Payments;

use Vinteract\DB;

class AccessToken {
	
	private $db = null;
	private $accessToken = null;
	
	private $headers = [];
	private $client = [];
	
	protected $table = "payments_access_tokens";
	
	function __construct() {
		
		// Store headers.
		
		$this->headers = array_change_key_case(getallheaders());
		
		// Load the database.
		
		$this->db = new DB(\Vinteract\Client::getDatabaseConnections());
		
		// Check headers for access token.
		
		if (ENVIRONMENT === "development") {
			$this->accessToken = "0f85165cf40a11ab81669da365096ff1056e53919fdb5d8e74538097ee66aab5";
		}
		
		if (array_key_exists("vinteract-access-token", $this->headers)) {
			$this->accessToken = $this->headers["vinteract-access-token"];
		}
		
	}
	
	public function get($key) {
		if (property_exists($this->client, $key)) {
			return $this->client->$key;
		}
		return null;
	}
	
	public function valid() {
		return count($this->client) > 0;
	}
	
	public function load() {
		
		// Load the access token.
		
		$accessToken = $this->db
			->capsule
			->getConnection("default")
			->table($this->table)
			->where("access_token", $this->accessToken)
			->first();
		
		// Did we find an access token?
		
		if (count($accessToken)) {
			$this->client = $this->db
				->capsule
				->getConnection("default")
				->table("global_{$accessToken->org_type}")
				->where("id", $accessToken->org_id)
				->first();
		}
		
		return $this;
		
	}
	
}
