<?php
/**
 * Example configurations for Headless Features.
 */
namespace Greyd\Headless;

use Greyd\Helper as Helper;

if ( !defined( 'ABSPATH' ) ) exit;

new Loader( $config );
class Loader {

	/**
	 * Constructor
	 */
	public function __construct( $config ) {

		// read apis from json files
		add_action( 'init', array( $this, 'get_api_settings_json' ), 0 );

		/**
		 * Examples
		 */

		// configure own rest api
		add_action( 'init', array( $this, 'configure_my_rest_api' ), 10 );

		// add api from file
		add_filter( 'greyd_api_settings_json', function( $files ) {
			// debug("add external file");
			array_push( $files, __DIR__.'/examples/filter/my_config.json');
			return $files;
		} );

		// add cat API
		add_action( 'init', array( $this, 'add_cat_api' ), 10 );
		
		// add helpscout
		add_action( 'init', array( $this, 'add_helpscout_api' ), 10 );
		
		// add cancom examples
		add_action( 'init', array( $this, 'add_cancom_apis' ), 10 );

		// add blackthorn
		add_action( 'init', array( $this, 'add_blackthorn_api' ), 10 );
		
	}

	/**
	 * Read APIs from json files in this dir.
	 * Use filter 'greyd_api_settings_json' to add external files.
	 */
	public function get_api_settings_json() {

		// get files
		$files = glob( __DIR__.'/examples/*.json', GLOB_BRACE);
		$files = apply_filters( 'greyd_api_settings_json', $files);
		// debug($files);

		foreach ( $files as $json ) {
			$json = Helper::url_to_abspath($json);
			if ( !file_exists($json) ) continue;
			$url = Helper::abspath_to_url(wp_normalize_path($json));

			$response = wp_remote_get(
				$url,
				array()
			);
			// debug($response['body']);
			$apis = json_decode($response['body'], true);
			// debug($apis);

			if ( json_last_error() == 0 ) {
				add_filter( 'greyd_api_settings', function( $settings ) use ( $apis ) {

					if ( !isset($settings['apis']) || !is_array($settings['apis']) ) {
						$settings['apis'] = array();
					}

					foreach ( $apis as $api_slug => $api ) {
						$settings['apis'][$api_slug] = $api;
					}

					return $settings;
				}, 0 );
			}

		}

	}

	/*
	=======================================================================
		Example: Configure own rest API
	=======================================================================
	*/

	public function configure_my_rest_api() {
		
		//
		// add rest endpoint settings

		add_filter( 'greyd_api_settings', function( $settings ) {
			
			$settings['basic'] = array(
				'disable_api'  => false,     // empty/false, 'public' or 'all'
				'hide_index'   => 'public',   // empty/false, 'public' or 'all'
				'modify_index' => array(    // empty/false or array
					'remove' => array(      // empty/false or array
						'url'  => 'all',             // 'public' or 'all'
						'home' => 'public',
						// 'icon' => 'false' // invalid
					),
					'add'    => array(
						'name'       => array(
							'show'  => 'all',        // 'loggedin' or 'all'
							'value' => 'Robo API',   // string/object/array
						),
						'extra_info' => array(
							'show'  => 'all',        // 'loggedin' or 'all'
							'value' => 'blahahbl',   // string/object/array
						),
						'more'       => array(
							'show'  => 'all',
							'value' => array(
								'hello' => 'world',
								'foo'   => 'bar',
							),
						),
						'ids'        => array(
							'show'  => 'loggedin',
							'value' => array( 1, 23, 54, 10456 ),
						),
					),
				),
			);

			$settings['posttypes'] = array(           // empty/false or array
				'hide' => array(
					// 'post' => 'all',             // 'public' or 'all'
					'page' => 'public',
				),
				'show' => array(
					'wp_global_styles' => 'all',    // 'loggedin' or 'all'
					'tp_posttypes'     => 'loggedin',
				),
			);

			$settings['taxonomies'] = array(          // empty/false or array
				'hide' => array(
					'category'            => 'all',            // 'public' or 'all'
					'post_tag'            => 'all',
					'template_categories' => 'public',
				),
				'show' => array(
					'wp_theme' => 'all',            // 'loggedin' or 'all'
				),
			);

			$settings['endpoints'] = array(           // empty/false or array
				'remove' => array(
					'/yoast/v1*' => 'all',          // 'public' or 'all'
					'/wp/v2*'    => 'public',
				),
				'add'    => array(
					'custom/v0' => array(
						'show'   => 'loggedin',       // 'loggedin' or 'all'
						'routes' => array(
							'/data',
							'/data/(?P<id>[\d]+)',
							'/infos',
						),
					),
					'greyd/v1'  => array(
						'show'   => 'all',            // 'loggedin' or 'all'
						'routes' => array(
							'/more',
							'/and-then-some',
						),
					),
				),
			);

			return $settings;
		} );

		//
		// rest endpoint filter

		add_filter( 'greyd_rest_api_custom_v0_infos', function( $result ) {
			$result['hello']       = 'world';
			$result['title']       = 'my custom api';
			$result['description'] = 'this is how you get data ...';
			return $result;
		} );

		add_filter( 'greyd_rest_api_custom_v0_data', function( $result ) {
			$result = Helper::get_all_posts( 'post' );
			return $result;
		} );

		add_filter( 'greyd_rest_api_custom_v0_data_(?P<id>[\d]+)', function( $result, $request ) {
			if ( isset( $request['id'] ) ) {
				$post = get_post( intval( $request['id'] ) );
				if ( $post ) {
					return $post;
				}
			}
			return $result;
		}, 10, 2 );

	}


	/*
	=======================================================================
		Example: cat API
	=======================================================================
	*/

	public function add_cat_api() {

		//
		// add api settings
		add_filter( 'greyd_api_settings', array( $this, 'add_cat_settings' ) );

		//
		// blockfilter
		// 

		add_filter( 'greyd_render_block_api_data_raw', function( $content, $atts, $api, $response ) {

			if ( $response['status'] !== 'error' && $api['slug'] == 'the-cat-api/with-key' ) {
				$items   = json_decode( $response['body'] );
				$content = '<div style="display:flex; flex-wrap:wrap">';
				foreach ( $items as $item ) {
					$content .= '<div style="flex-basis:20%">
									<img src="' . $item->url . '" width="' . $item->width . '" height="' . $item->height . '">
								</div>';
				}
				$content .= '</div>';
			}

			return $content;
		}, 10, 4 );

		add_filter( 'greyd_render_block_api_data', function( $content, $atts, $api, $response ) {

			if ( $response['status'] !== 'error' && $api['slug'] == 'the-cat-api/public' ) {
				$items = json_decode( $response['body'] );
				foreach ( $items as $item ) {
					$content .= '<div>
									<img src="' . $item->url . '" width="' . $item->width . '" height="' . $item->height . '">
								</div>';
				}
			}

			return $content;
		}, 10, 4 );

	}

	public function add_cat_settings( $settings ) {

		if ( !isset($settings['apis']) || !is_array($settings['apis']) ) {
			$settings['apis'] = array();
		}

		$settings['apis']['the-cat-api'] = array(
			'title'    => 'cat API',
			'slug'     => 'the-cat-api',
			'base_url' => 'https://api.thecatapi.com/v1',
			'url_path' => 'images/search',
			'url_atts' => '',
			'headers'  => '',
			'routes'   => array(
				array(
					'title'       => 'Public',
					'description' => 'one cat - render with filter',
					'slug'        => 'public',
					'url_path'    => 'images/search',
					'url_atts'    => '',
					'headers'     => '',
				),
				array(
					'title'       => 'with key',
					'description' => 'ten cats',
					'slug'        => 'with-key',
					'url_path'    => 'images/search',
					'url_atts'    => array(
						'limit' => '10',
					),
					'headers'     => array(
						'x-api-key' => 'live_bhSZSrmcg5SiS5yBOgizsJhK6QW3SowsxwjZsjaucyFx0FtsdXAC4TZh469S0BCn',
					),
				),
			),
			'blocks'   => array(
				array(
					'route' => 'public',
				),
				array(
					'route'     => 'with-key',
					'data_prop' => '',
					'data_item' => array(
						'id'    => 'id',
						'breed' => array(
							'prop'    => 'breeds.0.name',
							'default' => '',
						),
						'thumb' => array(
							'title' => 'Cat Image',
							'prop'  => 'url',
							'type'  => 'file',
						),
					),
				),
			),
		);

		return $settings;
	}


	/*
	=======================================================================
		Example: Helpscout
	=======================================================================
	*/

	public function add_helpscout_api() {

		//
		// add api settings
		add_filter( 'greyd_api_settings', array( $this, 'add_helpscout_settings' ) );

		//
		// filter
		// 

		// post status
		add_filter( 'greyd_api_data_item_post_status', function( $value, $item_setup, $json_item, $api ) {

			if ( strpos( $api['slug'], 'helpscout' ) === false ) {
				return $value;
			}
			
			// if ( $value == 'published' ) {
				return 'publish';
			// }
			return 'draft';
		}, 10, 4 );

		// video frame
		add_filter( 'greyd_api_data_item_video_frame', function( $value, $item_setup, $json_item, $api ) {

			if ( strpos( $api['slug'], 'helpscout' ) === false ) {
				return $value;
			}
			// debug( esc_attr( $value ) );

			preg_match( '/<div data-html-block>.+?<\/iframe><\/div><\/div>/', $value, $matches );
			if ( count( $matches ) > 0 ) {
				// debug( array_map( 'esc_attr', $matches ) );
				return $matches[0];
			}

			preg_match( '/<div class="video[^>]+?><iframe[^>]+?><\/iframe><\/div>/', $value, $matches );
			if ( count( $matches ) > 0 ) {
				// debug( array_map( 'esc_attr', $matches ) );
				return $matches[0];
			}

			return "";
		}, 10, 4 );

		// video url in metadata
		add_filter( 'greyd_api_data_item_video_url', function( $value, $item_setup, $json_item, $api ) {

			if ( strpos( $api['slug'], 'helpscout' ) === false ) {
				return $value;
			}
			// debug( esc_attr( $value ) );

			preg_match( '/<iframe [^>]+?src="(.+)?\?/', $value, $matches );
			if ( count( $matches ) > 1 ) {
				// debug( array_map( 'esc_attr', $matches ) );
				return $matches[1];
			}

			return "";
		}, 10, 4 );

		// video url in post content
		add_filter( 'greyd_api_data_item_post_content', function( $value, $item_setup, $json_item, $api ) {

			if ( strpos( $api['slug'], 'helpscout' ) === false ) {
				return $value;
			}
			// debug( esc_attr( $value ) );

			$value = preg_replace( '/<div data-html-block>.+?<\/iframe><\/div><\/div>/', '', $value, -1 );
			$value = preg_replace( '/<div class="video[^>]+?><iframe[^>]+?><\/iframe><\/div>/', '', $value, -1 );

			return $value;
		}, 10, 4 );

		// add_filter( 'greyd_api_after_helpscout/tutorial-videos-en', function( $result, $api ) {

		// 	if (
		// 		isset($result['body'])
		// 		&& isset($result['body']['articles'])
		// 		&& is_array($result['body']['articles'])
		// 		&& isset($result['body']['page'])
		// 		&& isset($result['body']['pages'])
		// 	) {

		// 		$current_page = intval( $result['body']['page'] );
		// 		$total_pages  = intval( $result['body']['pages'] );
		// 		if ( $current_page < $total_pages ) {
		// 			$api['url_atts']['page'] = $current_page + 1;
		// 		}
		// 	}


		// 	// error_log( '<pre>' . print_r( $api, true ) . '</pre>' );
		// 	// error_log( '<pre>' . print_r( $result, true ) . '</pre>' );

		// 	return $result;
		// }, 10, 2 );

		// // english posts
		// add_action( 'greyd_api_import_posts_helpscout/tutorial-videos-en', function( $posts, $api_config, $automator ) {
	
		// 	// switch the language
		// 	global $sitepress;
		// 	$sitepress->switch_lang( 'en' );

		// 	// error_log( 'switch language to en' );

		// }, 10, 3 );

		// // german posts
		// add_action( 'greyd_api_import_posts_helpscout/tutorial-videos-de', function( $posts, $api_config, $automator ) {
	
		// 	// switch the language
		// 	global $sitepress;
		// 	$sitepress->switch_lang( 'de' );

		// 	// error_log( 'switch language to de' );

		// }, 10, 3 );

	}

	public function add_helpscout_settings( $settings ) {

		if ( !isset($settings['apis']) || !is_array($settings['apis']) ) {
			$settings['apis'] = array();
		}

		$settings['apis']['helpscout'] = array(
			'title'     => 'HelpScout',
			'slug'      => 'helpscout',
			'base_url'  => 'https://docsapi.helpscout.net/v1',
			'url_path'  => 'collections',
			'url_atts'  => '',
			'headers'   => array(
				'Authorization' => 'Basic e8d02c30f507e1f4b96de846655ce07a30e243c5:X',
			),
			'routes'    => array(
				'greydsuite-helpdesk' => array(
					'title'    => 'GREYD.SUITE Helpdesk',
					'slug'     => 'greydsuite-helpdesk',
					'url_path' => 'collections/641ab560f5464117fe74d02c/articles',
					'url_atts' => array(
						'status' => 'published',
						'page' => 1,
						'pageSize' => 100,
					),
					'headers'  => '',
					'wp_cache' => array(
						'enabled' => true,
						'expire'  => 60 * 60 * 24, // 1 day
					),
				),
				'tutorial-videos-de' => array(
					'title'    => 'Tutorial Videos',
					'slug'     => 'tutorial-videos-de',
					'url_path' => 'collections/64abce36f606dd072b2b2b31/articles',
					'url_atts' => array(
						'status' => 'published',
						'page' => 1,
						'pageSize' => 100,
					),
					'headers'  => '',
					'wp_cache' => array(
						'enabled' => true,
						'expire'  => 60 * 60 * 24, // 1 day
					),
				),
				'tutorial-videos-en' => array(
					'title'    => 'Tutorial Videos EN',
					'slug'     => 'tutorial-videos-en',
					'url_path' => 'collections/64b52d92a9c74861f34db390/articles',
					'url_atts' => array(
						'status' => 'published',
						'page' => 1,
						'pageSize' => 100
					),
					'headers'  => '',
					'wp_cache' => array(
						'enabled' => true,
						'expire'  => 60 * 60 * 24, // 1 day
					),
				),
				'get-article'         => array(
					'title'       => 'Get article',
					'description' => 'single article with variable {article-id}',
					'slug'        => 'get-article',
					'url_path'    => 'articles/{article-id}',
					'url_atts'    => '',
					'headers'     => '',
					'wp_cache'    => array(
						'enabled' => true,
						'expire'  => 60 * 60, // 1 hour
					),
				),
				'get-category'        => array(
					'title'       => 'Get category',
					'description' => 'single category with variable {category-id}',
					'slug'        => 'get-category',
					'url_path'    => 'categories/{category-id}',
					'url_atts'    => '',
					'headers'     => '',
					'wp_cache' => array(
						'enabled' => true,
						'expire'  => 60 * 60 * 24, // 1 day
					),
				),
			),
			'blocks'    => array(
				'collections'    => array(
					'route'     => 'helpscout',
					'data_prop' => 'collections.items',
					'data_item' => array(
						'id'          => 'id',
						'title'       => 'name',
						'items_count' => 'articleCount',
						'link'        => 'publicUrl',
					),
				),
				'all-articles'   => array(
					'route'     => 'greydsuite-helpdesk',
					'data_prop' => 'articles.items',
					'data_item' => array(
						'id'    => 'id',
						'title' => 'name',
						'date'  => 'updatedAt',
						'link'  => array(
							'prop'    => 'id',
							'actions' => array(
								array(
									'action' => 'prepend',
									'value'  => 'https://greyd2.localhost/07/?page_id=874&article-id=',
								),
							),
							'type'    => 'url',
						),
						// 'text' => array(
						// 	'prop' => 'id',
						// 	'actions' => array(
						// 		array(
						// 			'action' => 'call',
						// 			'value' => array(
						// 				'route' => 'get-article',
						// 				'vars' => array(
						// 					'{article-id}' => 'id'
						// 				),
						// 				'data_prop' => 'article.text',
						// 			)
						// 		)
						// 	)
						// ),
					),
				),
				'single-article' => array(
					'route'     => 'get-article',
					'vars'      => array(
						'{article-id}' => '123',
					),
					'data_prop' => 'article',
					'data_item' => array(
						'id'    => 'id',
						'title' => 'name',
						'date'  => 'updatedAt',
						'text'  => 'text',
						'link'  => array(
							'prop' => 'publicUrl',
							'type' => 'url',
						),
					),
				),
			),
			'posttypes' => array(
				'post-en'     => array(
					'posttype_settings' => array(
						'slug'        => 'post',
						'title'       => 'Post',
						'is_taxonomy' => false,
						'singular'    => 'Post',
						'plural'      => 'Posts',
						// "categories" => "categories",
						// "tags"       => "tags",
						'supports'    => array(
							'editor'    => 'editor',
							'thumbnail' => 'thumbnail',
							'excerpt'   => 'excerpt',
							'author'    => 'author',
						),
						'arguments'   => array(
							'search'  => 'search',
							'archive' => 'archive',
						),
						'fields'      => array(
							array(
								"name"  => "helpscout_id",
								"label" => "helpscout_id",
								"type"  => "text",
							)
						),
					),
					'api_settings'      => array(
						'route'     => 'greydsuite-helpdesk',
						'data_prop' => 'articles.items',
						'data_item' => array(
							'post_title'   => 'name',
							'post_name'    => 'slug',
							'post_date'    => 'updatedAt',
							'post_status' => array(
								'prop' => 'status'
							),
							'lang' => array(
								'value' => 'en'
							),
							'post_content' => array(
								'actions' => array(
									array(
										'action' => 'call',
										'value' => array(
											'route' => 'get-article',
											'vars' => array(
												'{article-id}' => 'id',
											),
											'data_prop' => 'article.text',
										),
									),
								),
							),
							'meta_input'   => array(
								'value' => array(
									'helpscout_id' => 'id', // shorthand for 'helpscout_id' => array( 'prop' => 'id' ),
									'dynamic_meta' => array(
										'value' => array(
											'helpscout_id' => array(
												'prop' => 'id',
											)
										)
									)
								)
							),
							'tax_input' => array(
								'value' => array(
									'topics' => array(
										'actions' => array(
											array(
												'action' => 'call',
												'value' => array(
													'route' => 'get-article',
													'vars' => array(
														'{article-id}' => 'id',
													),
													'data_prop' => 'article.categories',
													'type'     => 'array',
													'actions' => array(
														array(
															'action' => 'call',
															'value' => array(
																'route' => 'get-category',
																'vars' => array(
																	'{category-id}' => 'value'
																),
																'data_prop' => 'category.name',
															)
														)
													)
												)
											)
										)
									),
									'post_tag' => array(
										'actions' => array(
											array(
												'action' => 'call',
												'value' => array(
													'route' => 'get-article',
													'vars' => array(
														'{article-id}' => 'id',
													),
													'data_prop' => 'article.keywords',
													'type'     => 'array',
												)
											)
										)
									)
								)
							)
						)
					)
				),
				'post-de'     => array(
					'posttype_settings' => array(
						'slug'        => 'post',
						'title'       => 'Post',
						'is_taxonomy' => false,
						'singular'    => 'Post',
						'plural'      => 'Posts',
						// "categories" => "categories",
						// "tags"       => "tags",
						'supports'    => array(
							'editor'    => 'editor',
							'thumbnail' => 'thumbnail',
							'excerpt'   => 'excerpt',
							'author'    => 'author',
						),
						'arguments'   => array(
							'search'  => 'search',
							'archive' => 'archive',
						),
						'fields'      => array(
							array(
								"name"  => "helpscout_id",
								"label" => "helpscout_id",
								"type"  => "text",
							)
						),
					),
					'api_settings'      => array(
						'route'     => 'greydsuite-helpdesk',
						'data_prop' => 'articles.items',
						'data_item' => array(
							'post_title'   => 'name',
							'post_name'    => 'slug',
							'post_date'    => 'updatedAt',
							'post_status' => array(
								'prop' => 'status'
							),
							'lang' => array(
								'value' => 'de'
							),
							'post_content' => array(
								'actions' => array(
									array(
										'action' => 'call',
										'value' => array(
											'route' => 'get-article',
											'vars' => array(
												'{article-id}' => 'id',
											),
											'data_prop' => 'article.text',
										),
									),
								),
							),
							'meta_input'   => array(
								'value' => array(
									'helpscout_id' => 'id', // shorthand for 'helpscout_id' => array( 'prop' => 'id' ),
									'dynamic_meta' => array(
										'value' => array(
											'helpscout_id' => array(
												'prop' => 'id',
											)
										)
									)
								)
							),
							'tax_input' => array(
								'value' => array(
									'topics' => array(
										'actions' => array(
											array(
												'action' => 'call',
												'value' => array(
													'route' => 'get-article',
													'vars' => array(
														'{article-id}' => 'id',
													),
													'data_prop' => 'article.categories',
													'type'     => 'array',
													'actions' => array(
														array(
															'action' => 'call',
															'value' => array(
																'route' => 'get-category',
																'vars' => array(
																	'{category-id}' => 'value'
																),
																'data_prop' => 'category.name',
															)
														)
													)
												)
											)
										)
									),
									'post_tag' => array(
										'actions' => array(
											array(
												'action' => 'call',
												'value' => array(
													'route' => 'get-article',
													'vars' => array(
														'{article-id}' => 'id',
													),
													'data_prop' => 'article.keywords',
													'type'     => 'array',
												)
											)
										)
									)
								)
							)
						)
					)
				),
				'tutorial-en' => array(
					'posttype_settings' => array(
						'slug'        => 'tutorial',
						'title'       => 'Tutorial',
						'is_taxonomy' => false,
						'singular'    => 'Tutorial',
						'plural'      => 'Tutorials',
						'icon'        => 'format-video',
						'position'    => 6,
						// 'categories'  => 'categories',
						'tags'        => 'tags',
						'supports'    => array(
							'editor'    => 'editor',
							'thumbnail' => 'thumbnail',
							'excerpt'   => 'excerpt',
							'author'    => 'author',
						),
						'arguments'   => array(
							'search'  => 'search',
							'archive' => 'archive',
						),
						'fields'      => array(
							array(
								"name"  => "helpscout_id",
								"label" => "helpscout_id",
								"type"  => "text",
							),
							array(
								"name"  => "video_url",
								"label" => "Video URL",
								"type"  => "url",
							),
							array(
								"name"  => "video_frame",
								"label" => "Video frame",
								"type"  => "text_html",
							),
							// array(
							// 	"name"  => "related_articles",
							// 	"label" => "Related Articles",
							// 	"type"  => "text_html",
							// )
						),
					),
					'api_settings'      => array(
						'route'     => 'tutorial-videos-en',
						'data_prop' => 'articles.items',
						'data_item' => array(
							'post_title'   => 'name',
							'post_name'    => 'slug',
							'post_date'    => 'updatedAt',
							'lang' => array(
								'value' => 'en'
							),
							'post_status' => array(
								'prop' => 'status'
							),
							'post_content' => array(
								'actions' => array(
									array(
										'action' => 'call',
										'value' => array(
											'route' => 'get-article',
											'vars' => array(
												'{article-id}' => 'id',
											),
											'data_prop' => 'article.text',
										),
									),
								),
							),
							'meta_input'   => array(
								'value' => array(
									'helpscout_id' => 'id', // shorthand for 'helpscout_id' => array( 'prop' => 'id' ),
									'dynamic_meta' => array(
										'value' => array(
											'helpscout_id' => array(
												'prop' => 'id',
											),
											'video_frame' => array(
												'actions' => array(
													array(
														'action' => 'call',
														'value' => array(
															'route' => 'get-article',
															'vars' => array(
																'{article-id}' => 'id',
															),
															'data_prop' => 'article.text',
														),
													),
												),
											),
											'video_url' => array(
												'actions' => array(
													array(
														'action' => 'call',
														'value' => array(
															'route' => 'get-article',
															'vars' => array(
																'{article-id}' => 'id',
															),
															'data_prop' => 'article.text',
														),
													),
												),
											)
										)
									),
								)
							),
							'tax_input' => array(
								'value' => array(
									'topics' => array(
										'actions' => array(
											array(
												'action' => 'call',
												'value' => array(
													'route' => 'get-article',
													'vars' => array(
														'{article-id}' => 'id',
													),
													'data_prop' => 'article.categories',
													'type'     => 'array',
													'actions' => array(
														array(
															'action' => 'call',
															'value' => array(
																'route' => 'get-category',
																'vars' => array(
																	'{category-id}' => 'value'
																),
																'data_prop' => 'category.name',
															)
														)
													)
												)
											)
										)
									)
								)
							)
						)
					)
				),
				'tutorial-de' => array(
					'posttype_settings' => array(
						'slug'        => 'tutorial',
						'title'       => 'Tutorial',
						'is_taxonomy' => false,
						'singular'    => 'Tutorial',
						'plural'      => 'Tutorials',
						'icon'        => 'format-video',
						'position'    => 6,
						// 'categories'  => 'categories',
						'tags'        => 'tags',
						'supports'    => array(
							'editor'    => 'editor',
							'thumbnail' => 'thumbnail',
							'excerpt'   => 'excerpt',
							'author'    => 'author',
						),
						'arguments'   => array(
							'search'  => 'search',
							'archive' => 'archive',
						),
						'fields'      => array(
							array(
								"name"  => "helpscout_id",
								"label" => "helpscout_id",
								"type"  => "text",
							),
							array(
								"name"  => "video_url",
								"label" => "Video URL",
								"type"  => "url",
							),
							array(
								"name"  => "video_frame",
								"label" => "Video frame",
								"type"  => "text_html",
							),
							// array(
							// 	"name"  => "related_articles",
							// 	"label" => "Related Articles",
							// 	"type"  => "text_html",
							// )
						),
					),
					'api_settings'      => array(
						'route'     => 'tutorial-videos-de',
						'data_prop' => 'articles.items',
						'data_item' => array(
							'post_title'   => 'name',
							'post_name'    => 'slug',
							'post_date'    => 'updatedAt',
							'lang' => array(
								'value' => 'de'
							),
							'post_status' => array(
								'prop' => 'status'
							),
							'post_content' => array(
								'actions' => array(
									array(
										'action' => 'call',
										'value' => array(
											'route' => 'get-article',
											'vars' => array(
												'{article-id}' => 'id',
											),
											'data_prop' => 'article.text',
										),
									),
								),
							),
							'meta_input'   => array(
								'value' => array(
									'helpscout_id' => 'id', // shorthand for 'helpscout_id' => array( 'prop' => 'id' ),
									'dynamic_meta' => array(
										'value' => array(
											'helpscout_id' => array(
												'prop' => 'id',
											),
											'video_frame' => array(
												'actions' => array(
													array(
														'action' => 'call',
														'value' => array(
															'route' => 'get-article',
															'vars' => array(
																'{article-id}' => 'id',
															),
															'data_prop' => 'article.text',
														),
													),
												),
											),
											'video_url' => array(
												'actions' => array(
													array(
														'action' => 'call',
														'value' => array(
															'route' => 'get-article',
															'vars' => array(
																'{article-id}' => 'id',
															),
															'data_prop' => 'article.text',
														),
													),
												),
											)
										)
									),
								)
							),
							'tax_input' => array(
								'value' => array(
									'topics' => array(
										'actions' => array(
											array(
												'action' => 'call',
												'value' => array(
													'route' => 'get-article',
													'vars' => array(
														'{article-id}' => 'id',
													),
													'data_prop' => 'article.categories',
													'type'     => 'array',
													'actions' => array(
														array(
															'action' => 'call',
															'value' => array(
																'route' => 'get-category',
																'vars' => array(
																	'{category-id}' => 'value'
																),
																'data_prop' => 'category.name',
															)
														)
													)
												)
											)
										)
									)
								)
							)
						)
					)
				),
				'topics'   => array(
					'posttype_settings' => array(
						'slug'        => 'topics',
						'title'       => 'Topics',
						'singular'    => 'Topic',
						'plural'      => 'Topics',
						'mark'        => '',
						'is_taxonomy' => true,
						'arguments'   => array(
							'public' => 'public',
						),
						'posttypes'   => array(
							'post'     => 'post',
							'tutorial' => 'tutorial',
						),
					),
				),
			)

		);

		return $settings;
	}


	/*
	=======================================================================
		Example: cancom
	=======================================================================
	*/

	public function add_cancom_apis() {

		//
		// add api settings
		add_filter( 'greyd_api_settings', array( $this, 'add_cancom_settings' ) );

		//
		// filter

		// add_filter( 'greyd_block_api_item_value', function( $res, $key, $api, $response ) {
		// 	// debug($res);
		// 	// debug($key);
		// 	// debug($api);
		// 	if ( $api['slug'] == 'cancom-xml/cancom-xml' && ( $key == 'id' || $key == 'language' ) ) {
		// 		$new_res = '';
		// 		$tmp     = explode( '&', $res );
		// 		if ( count( $tmp ) > 0 ) {
		// 			foreach ( $tmp as $item ) {
		// 				if ( strpos( $item, 'id=' ) === 0 && $key == 'id' ) {
		// 					$new_res = str_replace( 'id=', '', $item );
		// 				}
		// 				if ( strpos( $item, 'language=' ) === 0 && $key == 'language' ) {
		// 					$new_res = str_replace( 'language=', '', $item );
		// 					if ( $new_res == 'eng' ) {
		// 						$new_res = 'en';
		// 					}
		// 				}
		// 			}
		// 		}
		// 		return $new_res;
		// 	}
		// 	return $res;
		// }, 10, 4 );

	}

	public function add_cancom_settings( $settings ) {

		if ( !isset($settings['apis']) || !is_array($settings['apis']) ) {
			$settings['apis'] = array();
		}

		$examples = array(

			'xml'              => array(
				'title'    => 'Simple XML',
				'slug'     => 'xml',
				'base_url' => 'https://codetogo.io/api/users.xml',
				'url_path' => '',
				'url_atts' => '',
				'headers'  => '',
				'blocks'   => array(
					array(
						'route'     => 'xml',
						'data_prop' => 'user',
						'data_item' => array(
							'user_id' => 'id',
							'name'    => 'name',
						),
					),
				),
			),
			'cancom-xml'       => array(
				'title'    => 'cancom Jobs XML',
				'slug'     => 'cancom-xml',
				'base_url' => 'https://cancom.rexx-recruitment.com/xml/public/list.php?agid=cancom_xml_portal',
				'url_path' => '',
				'url_atts' => '',
				'headers'  => '',
				'blocks'   => array(
					array(
						'route'     => 'cancom-xml',
						'data_prop' => 'Link',
						'data_item' => array(
							'index'    => array(
								'actions' => array(
									array(
										'action' => 'index',
										'value'  => 'append',
									),
									array(
										'action' => 'append',
										'value'  => ' / ',
									),
									array(
										'action' => 'count',
										'value'  => 'append',
									),
								),
							),
							'id'       => array(
								'prop'    => 'value',
								'actions' => array(
									array( 'action' => 'filter' ),
								),
							),
							'language' => array(
								'prop'    => 'value',
								'actions' => array(
									array( 'action' => 'filter' ),
								),
							),
							'link'     => array(
								'title' => '',
								'prop'  => 'value',
								'type'  => 'url',
							),
						),
					),
				),
			),
			'cancom-news-xml'  => array(
				'title'    => 'cancom News XML',
				'slug'     => 'cancom-news-xml',
				'base_url' => 'https://irpages2.eqs.com/websites/newsfeed',
				'url_path' => 'English/1/xml-feed.html',
				'url_atts' => array(
					'companyToken' => '4c6252c6-e5be-4add-a857-c5ab0fdc6e9e',
					'type'         => 'dgap_pvr;dgap_nvr',
					'limit'        => '-1',
				),
				'headers'  => '',
				'routes'   => array(
					array(
						'title'    => 'English',
						'slug'     => 'en',
						'url_path' => 'English/1/xml-feed.html',
						'url_atts' => '',
						'headers'  => '',
					),
					array(
						'title'    => 'German',
						'slug'     => 'de',
						'url_path' => 'German/1/xml-feed.html',
						'url_atts' => '',
						'headers'  => '',
					),
				),
				'blocks'   => array(
					array(
						'route'     => 'en',
						'data_prop' => 'EquityStory-News',
						'data_item' => array(
							'id'    => array(
								'title' => '',
								'prop'  => 'issuer.NewsItem.news_id',
							),
							'title' => array(
								'title' => '',
								'prop'  => 'issuer.NewsItem.Headline',
							),
							'story' => array(
								'title' => '',
								'prop'  => 'issuer.NewsItem.Story',
							),
							'date'  => array(
								'title' => '',
								'prop'  => 'header.deliveryDate',
							),
							'url'   => array(
								'title' => '',
								'prop'  => 'issuer.NewsItem.link',
								'type'  => 'url',
							),
						),
					),
				),
			),
			'cancom-news-html' => array(
				'title'    => 'cancom News html',
				'slug'     => 'cancom-news-html',
				'base_url' => 'https://irpages2.eqs.com/websites/newsfeed',
				'url_path' => 'German/99/detail-page.html',
				'url_atts' => array(
					'companyToken' => '4c6252c6-e5be-4add-a857-c5ab0fdc6e9e',
					'newsID'       => '2557747',
				),
				'headers'  => '',
			)

		);

		$settings['apis'] = array_merge(
			$settings['apis'],
			$examples
		);

		return $settings;

	}


	/*
	=======================================================================
		Blackthorn
	=======================================================================
	*/

	public function add_blackthorn_api() {

		//
		// add api settings
		add_filter( 'greyd_api_settings', array( $this, 'add_blackthorn_settings' ) );

		//
		// filter
		add_filter( 'greyd_api_before_blackthorn/get-resources', array( $this, 'authenticate_blackthorn' ), 10, 2 );
		add_filter( 'greyd_api_before_blackthorn/query', array( $this, 'authenticate_blackthorn' ), 10, 2 );
		add_filter( 'greyd_api_before_blackthorn/query-var', array( $this, 'authenticate_blackthorn' ), 10, 2 );

	}

	public function authenticate_blackthorn( $call, $api ) {

		// echo "\r\n\r\n";
		// echo "FILTER CALL";
		// echo "\r\n\r\n";

		// get route
		$route = Api_Helper::get_api( 'blackthorn/get-token' );

		// echo "GET TOKEN FROM";
		// echo "\r\n\r\n";
		// debug($route);
		// echo "\r\n\r\n";

		// call to get token (cached for 2h)
		$route_response = Api_Helper::remote_get( $route );

		if (
			$route_response['status'] === 'success' &&
			strpos( $route_response['type'], 'application/json' ) === 0
		) {
			$route_result = json_decode( $route_response['body'], true );
			if ( $route_result && isset($route_result['access_token']) ) {

				// echo "NEW TOKEN";
				// echo "\r\n\r\n";
				// debug($route_result);
				// echo "\r\n\r\n";

				// set access token to header
				$token = $route_result['access_token'];
				$call['params']['headers']['Authorization'] = 'Bearer '.$token;
			}
			else {
				return new \WP_Error(
					'no_token',
					'no access token',
					array(
						'status' => 403,
					)
				);
			}
		}
		else {
			return new \WP_Error(
				'no_token',
				sprintf( 'no access token route (%s)', $route_response['body'] ),
				array(
					'status' => 403,
				)
			);

		}

		return $call;
	}

	public function add_blackthorn_settings( $settings ) {
				
		if ( !isset($settings['apis']) || !is_array($settings['apis']) ) {
			$settings['apis'] = array();
		}

		$settings['apis']['blackthorn'] = array(

			'title'    => 'Salesforce Blackthorn',
			'slug'     => 'blackthorn',
			// 'base_url' => 'https://test.salesforce.com',
			'base_url' => 'https://cancom--release.sandbox.my.salesforce.com',
			'url_path' => 'services/data',
			'url_atts' => array(),
			'headers'  => array(),
			'method'    => 'GET',
			'routes'	=> array(
				'get-token'		=> array(
					'title'			=> 'Get Access Token',
					'description'	=> '',
					'slug'			=> 'get-token',
					'url_path'		=> 'services/oauth2/token',
					'url_atts'		=> array(
						'grant_type'    => 'password',
						'client_id'		=> '3MVG9buXpECUESHiRAGClMnrSZPDDWVaPGryKef39HfEOVZTgZdfMxsx5pW9kGP4JMMS76J.YUkZQTgNIUlZ1',
						'client_secret'	=> '97D75C2CD7A8A292C9E0E54340FA77575306353CB2D7B54EDC4DA1B4DE5873F6',
						'username'		=> 'integration@user.cancom.release',
						'password'		=> 'Wordpress1!v32chexWEbn4Y2SWMwQUPZbS'
					),
					'headers'		=> '',
					'wp_cache'		=> array(
						'enabled'		=> true,
						'expire'		=> 60 * 60 * 2, // 2 hours
					),
					'method'		=> 'POST',
				),
				// example (now invalid) access token (response from get-token call)
				// {
				// 	"access_token": "00D3L0000000r2a!AQEAQHER6zzNmgrRyym87fYpo752tW8lJmvCx4KmbySBSLX46F185yZeJpkUGAIoM7bATLBiyKQhE9VQmFpyYz6l4dKvJfcI",
				// 	"instance_url": "https://cancom--release.sandbox.my.salesforce.com",
				// 	"id": "https://test.salesforce.com/id/00D3L0000000r2aUAA/0059M0000039rZdQAI",
				// 	"token_type": "Bearer",
				// 	"issued_at": "1702559960173",
				// 	"signature": "v6B5shiAO0CP7ptvOrzXSR9XMdHySDH2/Ys6lKmEXyg="
				// }

				// example 'Get a List of Resources'
				// https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_code.htm
				'get-resources'		=> array(
					'title'			=> 'Get resources',
					'description'	=> '',
					'slug'			=> 'get-resources',
					'url_path'		=> 'services/data/v59.0',
					'url_atts'		=> '',
					'headers'		=> '',
					// example header with (now invalid) access token (actual Authorization made by filter)
					// 'headers'		=> array(
					// 	'Authorization' => 'Bearer 00D3L0000000r2a!AQEAQHER6zzNmgrRyym87fYpo752tW8lJmvCx4KmbySBSLX46F185yZeJpkUGAIoM7bATLBiyKQhE9VQmFpyYz6l4dKvJfcI'
					// ),
					'wp_cache'		=> array(
						'enabled'		=> true,
						'expire'		=> 60 * 60 * 24, // 1 day
					),
					'method'		=> 'GET',
				),

				// // query example (conference360__Event__c)
				// 'query'		=> array(
				// 	'title'			=> 'Query',
				// 	'description'	=> '',
				// 	'slug'			=> 'query',
				// 	'url_path'		=> 'services/data/v59.0/query',
				// 	'url_atts'		=> array(
				// 		'q' => 'SELECT+FIELDS(All)+FROM+conference360__Event__c+ORDER+BY+CreatedDate+DESC+LIMIT+200'
				// 	),
				// 	'headers'		=> '',
				// 	'wp_cache'		=> array(
				// 		'enabled'		=> true,
				// 		'expire'		=> 60 * 60 * 24, // 1 day
				// 	),
				// 	'method'		=> 'GET',
				// ),

				// query with var {object} and {max}
				'query-var'		=> array(
					'title'			=> 'Query with var',
					'description'	=> 'use var {object} and {max}',
					'slug'			=> 'query-var',
					'url_path'		=> 'services/data/v59.0/query',
					'url_atts'		=> array(
						'q' => 'SELECT+FIELDS(All)+FROM+{object}+ORDER+BY+CreatedDate+DESC+LIMIT+{max}'
					),
					'headers'		=> '',
					'wp_cache'		=> array(
						'enabled'		=> true,
						'expire'		=> 60 * 60 * 24, // 1 day
					),
					'method'		=> 'GET',
				)
			),
			'blocks'    => array(
				// // query example
				// 'all-events'   => array(
				// 	'route'     => 'query',
				// 	'data_prop' => 'records',
				// 	'data_item' => array(
				// 		'id'    => 'Id',
				// 		'title' => 'Name',
				// 		'date'  => 'CreatedDate',
				// 		'start' => 'conference360__Event_End_Date_Time__c',
				// 		'end'   => 'conference360__Event_Start_Date_Time__c',
				// 	),
				// ),

				// query with var {object} = conference360__Event__c and {max} = 50
				'query-event' => array(
					'description'  => 'Event -> conference360__Event__c',
					'route'     => 'query-var',
					'vars'      => array(
						'{object}' => 'conference360__Event__c',
						'{max}' => '50',
					),
					'data_prop' => 'records',
					'data_item' => array(
						'id'    => 'Id',
						'name' => 'Name',
						// custom fields
						'event-group' => 'conference360__Event_Group__c',
						'status' => 'conference360__Status__c',
						'sategory' => 'conference360__Category__c',
						'event-type' => 'Event_Type__c',
						'industry-topic' => 'Industry_Topic__c',
						'event-start-date' => 'conference360__Event_Start_Date__c',
						'event-start-time' => 'conference360__Event_Start_Time__c',
						'event-end-date' => 'conference360__Event_End_Date__c',
						'event-end-time' => 'conference360__Event_End_Time__c',
						'event-url-german' => 'Event_URL_German__c',
						'image-url' => 'conference360__Image_URL__c',
						'description' => 'conference360__Calendar_Description__c',
						'short-description' => 'conference360__Short_Description__c',
						'venue-name' => 'conference360__Venue_Name__c',
						'venue-street' => 'conference360__Venue_Street__c',
						'venue-postal-code' => 'conference360__Venue_Postal_Code__c',
						'venue-city' => 'conference360__Venue_City__c',
						'venue-country' => 'conference360__Venue_Country__c',
						'contact-event-name' => 'Contact_Event_Name__c',
						'contact-event-title' => 'Contact_Event_Title__c',
						'contact-event-email' => 'Contact_Event_Email__c',
						'contact-event-phone' => 'Contact_Event_Phone__c',
						'contact-department-name' => 'Contact_Department_Name__c',
						'contact-department-title' => 'Contact_Department_Title__c',
						'contact-department-email' => 'Contact_Department_Email__c',
						'contact-department-phone' => 'Contact_Department_Phone__c',
						'remaining-capacity' => 'conference360__Remaining_Capacity__c',
						'remaining-waitlist-capacity' => 'conference360__Remaining_Waitlist_Capacity__c',
						'waitlist-enabled' => 'conference360__Waitlist_Enabled__c ',
					),
				),
				// query with var {object} = conference360__Event_Item__c and {max} = 50
				'query-event-item' => array(
					'description'  => 'Event Item -> conference360__Event_Item__c',
					'route'     => 'query-var',
					'vars'      => array(
						'{object}' => 'conference360__Event_Item__c',
						'{max}' => '50',
					),
					'data_prop' => 'records',
					'data_item' => array(
						'id'    => 'Id',
						'name' => 'Name',
						// custom fields
						'event' => 'conference360__Event__c',
						'sales-start-date' => 'conference360__Sales_Start_Date__c',
						'sales-start-time' => 'conference360__Sales_Start_Time__c',
						'sales-end-date' => 'conference360__Sales_Start_Date__c',
						'sales-end-time' => 'conference360__Sales_End_Time__c',
					),
				),
				// query with var {object} = conference360__Session__c and {max} = 50
				'query-session' => array(
					'description'  => 'Session -> conference360__Session__c',
					'route'     => 'query-var',
					'vars'      => array(
						'{object}' => 'conference360__Session__c',
						'{max}' => '50',
					),
					'data_prop' => 'records',
					'data_item' => array(
						'id'    => 'Id',
						'name' => 'Name',
						// custom fields
						'status' => 'conference360__Status__c',
						'event' => 'conference360__Event__c',
						'location' => 'conference360__Room_Text__c',
						'topic' => 'conference360__Topic__c',
						'type' => 'conference360__Type__c',
						'image-url' => 'conference360__Image_URL__c',
						'description' => 'conference360__Description__c',
						'start-date' => 'conference360__Start_Date__c',
						'start-time' => 'conference360__Start_Time__c',
						'end-date' => 'conference360__End_Date__c',
						'end-time' => 'conference360__End_Time__c',
					),
				),
				// query with var {object} = conference360__Session_Speaker__c and {max} = 50
				'query-session-speaker' => array(
					'description'  => 'Session Speaker -> conference360__Session_Speaker__c',
					'route'     => 'query-var',
					'vars'      => array(
						'{object}' => 'conference360__Session_Speaker__c',
						'{max}' => '50',
					),
					'data_prop' => 'records',
					'data_item' => array(
						'id'    => 'Id',
						'name' => 'Name',
						// custom fields
						'session' => 'conference360__Session__c',
						'speaker' => 'conference360__Speaker__c',
						'speaker-name' => 'conference360__Speaker_Name__c',
					)
				),
				// query with var {object} = conference360__Speaker__c and {max} = 50
				'query-speaker' => array(
					'description'  => 'Speaker -> conference360__Speaker__c',
					'route'     => 'query-var',
					'vars'      => array(
						'{object}' => 'conference360__Speaker__c',
						'{max}' => '50',
					),
					'data_prop' => 'records',
					'data_item' => array(
						'id'    => 'Id',
						'name' => 'Name',
						// custom fields
						'event' => 'conference360__Event__c',
						'status' => 'conference360__Status__c',
						'first-name' => 'conference360__First_Name__c',
						'lLast-name' => 'conference360__Last_Name__c',
						'email' => 'conference360__Email__c',
						'phone' => 'conference360__Phone__c',
						'image-url' => 'conference360__Image_URL__c',
						'bio' => 'conference360__Bio_Rich__c',
					)
				),
				// query with var {object} = conference360__Sponsor__c and {max} = 50
				'query-sponsor' => array(
					'description'  => 'Sponsor -> conference360__Sponsor__c',
					'route'     => 'query-var',
					'vars'      => array(
						'{object}' => 'conference360__Sponsor__c',
						'{max}' => '50',
					),
					'data_prop' => 'records',
					'data_item' => array(
						'id'    => 'Id',
						'name' => 'Name',
						// custom fields
						'display-name' => 'conference360__Display_Name__c',
						'event' => 'conference360__Event__c',
						'tier' => 'conference360__Tier__c',
						'status' => 'conference360__Status__c',
						'image-url' => 'conference360__Image_URL__c',
						'description' => 'conference360__Bio_Rich__c',
					)
				),
				// query with var {object} = conference360__Event_FAQ__c and {max} = 50
				'query-event-faq' => array(
					'description'  => 'Event FAQ -> conference360__Event_FAQ__c',
					'route'     => 'query-var',
					'vars'      => array(
						'{object}' => 'conference360__Event_FAQ__c',
						'{max}' => '50',
					),
					'data_prop' => 'records',
					'data_item' => array(
						'id'    => 'Id',
						'name' => 'Name',
						// custom fields
						'event' => 'conference360__Event__c',
						'category' => 'conference360__Category__c',
						'sort-order' => 'conference360__Sort_Order__c',
						'question' => 'conference360__FAQ_Question__c',
						'answer' => 'conference360__Answer__c',
					)
				),
				// query with var {object} = conference360__Event_Group__c and {max} = 50
				'query-event-group' => array(
					'description'  => 'Event Group -> conference360__Event_Group__c',
					'route'     => 'query-var',
					'vars'      => array(
						'{object}' => 'conference360__Event_Group__c',
						'{max}' => '50',
					),
					'data_prop' => 'records',
					'data_item' => array(
						'id'    => 'Id',
						'name' => 'Name',
						// custom fields
						'default' => 'conference360__Default__c',
						'type' => 'conference360__Event_Group_Type__c',
						'image-url' => 'conference360__Event_Group_Image_URL__c',
					)
				),
			),
			'posttypes' => array(
				
			)

		);

		return $settings;
	}

}