<?php

namespace PureCharity\Base;

class ApiController extends BaseController {
    
    public $moduleConfig;
	public $endpoints;

	public static $apiUrl;
	public static $apiKey;

	private $config;
	private $path;

    function __construct($moduleConfig) {

		// Init Module Config
        $this->moduleConfig = $moduleConfig;

		// Init Path
		$this->path = dirname(__FILE__);

		// Init Config
		$this->config = [
			'namespace' => (
                $this->moduleConfig['mainNamespace'] .'\\'.
                'Base'
            ),
			'endpoints' => [
                'path' => $this->path .'/endpoints/',
                'restricted' => [
                    '.',
                    '..',
                    'index.php',
					'README-Sponsorhips.md',
                ],
            ],
		];

		// Init Endpoints Container
		$this->endpoints = [];

		// Autoload Endpoints
		$this->autoloadEndpoints();

		// Init API
		$this->initApi();
    }

	private function autoloadEndpoints() {

		if (
            empty($this->config['endpoints']) ||
            empty($this->config['endpoints']['path'])
        ) { return false; }

        $endpointsDir = scandir($this->config['endpoints']['path']);

        if (
            empty($endpointsDir) ||
            count($endpointsDir) <= 3
        ) { return false; }
        
		foreach ($endpointsDir as $index => $endpointScript) {

			if (in_array($endpointScript, $this->config['endpoints']['restricted'])) { continue; }

			$endpointPath = $this->config['endpoints']['path'] . $endpointScript;
			$endpointClassName = str_replace('.php', '', $endpointScript);
			$endpointClassNameToEndpointName = strtolower($endpointClassName);

			if (
                !file_exists($endpointPath) ||
                !empty($this->endpoints[$endpointClassNameToEndpointName])
            ) { continue; }

			require_once $endpointPath;

			$endpointClass = (
				$this->config['namespace'] .'\\'.
				$endpointClassName
			);

			$this->endpoints[$endpointClassNameToEndpointName] = new $endpointClass();
		}
	}

	public function initApi() {
		$pure_base_options = get_option('purecharity_plugin_settings');
		$mode = $pure_base_options['mode'];
		self::$apiKey = $pure_base_options['api_key'];

		if ('production' == $mode) {
			self::$apiUrl = "https://purecharity.com/api/";
		} elseif('sandbox' == $mode) {
			self::$apiUrl = "https://staging.purecharity.com/api/";
		} elseif('demo' == $mode) {
			self::$apiUrl = "https://demo.purecharity.com/api/";
		} else {
			self::$apiUrl = $_ENV["API_URL"];
		}
	}

	public function apiCall($endpoint, $urlParams, $queryParams) {

		// Init Default Result
		$response = null;

		if (
			empty($endpoint) ||
			empty($this->endpoints[$endpoint])
		) { return $response; }

		$endpointObject = (
			!empty($this->endpoints[$endpoint]) ?
			$this->endpoints[$endpoint] :
			null
		);

		$endpointRest = (
			!empty($endpointObject) &&
			!empty($endpointObject::$rest) ?
			$endpointObject::$rest :
			null
		);

		if (empty($endpointRest)) { return $response; }

		// Prepare the API URL 
		$apiCallUrl = (
		  self::$apiUrl . 
		  $endpointRest .'/'
		);

		if (!empty($urlParams)) {

			$apiCallUrl .= implode('/', $urlParams);
		}

		$apiCallUrl = rtrim($apiCallUrl, '/');

		if (!empty($queryParams)) {

			$apiCallUrl .= '?'. http_build_query($queryParams);
		}

		// Set Request Headers
		$headers = array();
		$headers[] = 'Authorization: Token token="'. self::$apiKey .'"';

		// Call the API URL
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $apiCallUrl);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response = curl_exec($ch);

		curl_close($ch);
	
		if ($response) {
		  $response = json_decode($response);
		}
	
		return $response;
	  }
}