<?php
if (!defined( 'CANVAS_DIR' )) {
	die();
}
class Canvas_Api {

	static private $api_version = 2;

	/**
	* Plugin API initialization
	*/
	public static function init() {
		add_action( 'init', array( 'Canvas_Api', 'add_endpoint'), 0);
		add_filter( 'query_vars', array( 'Canvas_Api', 'add_query_vars' ), 0 );
		add_action( 'parse_request', array( 'Canvas_Api', 'check_requests' ), 0 );
		if (Canvas::get_option( 'api_version', 1 ) != self::$api_version) {
			add_action( 'init', array( 'Canvas_Api', 'activate' ), 0 );
		}
	}

	/**
	* Plugin API activation
	*/
	public static function activate() {
		self::add_endpoint();
		flush_rewrite_rules();
		Canvas::set_option( 'api_version', self::$api_version);
	}

	/**
	* Add public query vars
	* @return array $vars
	*/
	public static function add_query_vars( $vars ) {
		$vars[] = '__canvas_api';
		$vars[] = '__canvas_path';
		return $vars;
	}

	/**
	* Add Endpoint
	*/
	public static function add_endpoint() {
		add_rewrite_rule( '^canvas-api/loginstate/?', 'index.php?__canvas_api=loginstate', 'top' );
		add_rewrite_rule( '^canvas-api/bp/?(.*)?', 'index.php?__canvas_api=bp&__canvas_path=$matches[1]', 'top' );
	}

	/**
	* Check Requests
	*
	* @param WP $wp
	*/
	public static function check_requests($wp) {
		if ( isset( $wp->query_vars[ '__canvas_api' ] ) ) {
			self::request( $wp->query_vars[ '__canvas_api' ] );
			exit;
		}
	}

	/**
	* Handle Requests
	*/
	protected static function request( $api_endpoint ) {
		switch ( $api_endpoint ) {
			case 'loginstate':
				self::check_activated();
				self::header_json();
				include_once dirname(__FILE__) . '/loginstate.php';
				break;
			case 'bp':
				include_once dirname(__FILE__) . '/bp.php';
				break;
			default:
				echo 'Mobiloud API v1.';
		}
	}

	private static function check_activated() {
		if (isset($_GET[ 'activate' ])) {
			Canvas::set_option( 'activated', '1' );
			Canvas::set_option( 'welcome', '1' );
			if (isset($_GET[ 'email' ]) && !Canvas::get_option( 'init_email' )) {
				Canvas::set_option( 'init_email', $_GET[ 'email' ] );
			}
		}
	}

	static public function header_json() {
		header( 'Content-Type: application/json' );
	}
}

Canvas_Api::init();