<?php

/**
 * admin_security.php
 *
 * Admin login
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    1.0
 * @link       http://opencart-api.com/product/opencart-rest-admin-api/
 * @see        http://webshop.opencart-api.com/rest-admin-api/
 */
require_once(DIR_SYSTEM . 'engine/restadmincontroller.php');

class ControllerRestAdminSecurity extends RestAdminController {

	/*
	* Login user
	*/
	public function login() {

		$this->checkPluginSimple();

		$json = array('success' => true);

		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){

			$input = file_get_contents('php://input');

			$post = json_decode($input, true);

			if ($this->user->isLogged()) {
				$json['error']		= "User already is logged";
				$json['success']	= false;
			}

			if ($json['success']) {
				if(!isset($post['username']) || !isset($post['password'])){
					$json['error']['warning'] = 'Username and password required';
					$json['success']	= false;
				} else {
					if (!$this->user->login($post['username'], $post['password'])) {
						$json['error']['warning'] = 'Invalid username or password';
						$json['success']	= false;
					}
				}
			}
		}else {
			$json["error"]		= "Only POST request method allowed";
			$json["success"]	= false;
		}

		$this->sendResponse($json);
	}

	/*
	* Logout user
	*/
	public function logout() {

		$this->checkPluginSimple();


		$json = array('success' => true);

		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){

			if ($this->user->isLogged()) {
				$this->user->logout();
			}
		}else {
			$json["error"]		= "Only POST request method allowed";
			$json["success"]	= false;
		}

		$this->sendResponse($json);
	}

	public function getToken() {
		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){

			$this->response->addHeader('Content-Type: application/json');

			$json = array("success" => false);

			/*check rest api is enabled*/
			if (!$this->config->get('restadmin_status')) {
				$json["error"] = 'Rest Admin API is disabled. Enable it!';
			}

			if(isset($json["error"])){
				echo(json_encode($json));
				exit;
			}

			$requestjson = file_get_contents('php://input');
			$post = json_decode($requestjson, true);

			$oldToken = isset($post['old_token']) ? $post['old_token'] : null;
			$oldTokenData = null;
			$this->load->model('rest/restadmin');

			if(!empty($oldToken)){
				$oldTokenData = $this->model_rest_restadmin->loadOldAdminToken($oldToken);
			}

			$server = $this->getOauthServer();
			$token = $server->handleTokenRequest(OAuth2\Request::createFromGlobals())->getParameters();

			if(!empty($oldTokenData)){
				$this->model_rest_restadmin->loadAdminSessionToNew($oldTokenData['data'], $token['access_token']);
				$this->model_rest_restadmin->deleteOldAdminToken($oldToken);
			}

			//clear token table
			$this->clearAdminTokensTable($token['access_token'], session_id());

			unset($token['scope']);
			$token['expires_in'] = (int)$token['expires_in'];

			return $this->sendResponse($token);

		} else {
			$json["error"]		= "Only POST request method allowed";
			$json["success"]	= false;
		}

		$this->sendResponse($json);
	}


	function clearAdminTokensTable($token=null, $sessionid=null){
		//delete all previous token to this session and delete all expired session
		$this->load->model('rest/restadmin');
		$this->model_rest_restadmin->clearAdminTokens($token, $sessionid);
	}
}