<?php 

/**
 * OVIS database version
 */
global $ovis_db_version;
$ovis_db_version = '1.0';


/**
 * Log to file
 *
 * @param mixed $message
 * @return void
 */
function ovis_write_log( $message ) {
	if( !defined( 'OVIS_PLUGIN_DEV_MODE' ) ) return;
	if( !OVIS_PLUGIN_DEV_MODE ) return;
	
	$file = path_join(OVIS_PLUGIN_DIR_PATH, 'ovis-plugin.log');
	
	if( is_array( $message ) || is_object( $message ) ) {
        $message = print_r( $message, true );
    }
	
    error_log( '[' . date( 'Y-m-d H:i:s' ) . '] ' . $message . PHP_EOL, 3, $file );
}


/**
 * Install necessary OVIS database tables
 *
 * @return void
 * @link https://developer.wordpress.org/reference/functions/dbdelta/
 */
function ovis_db_install() {
	
	global $ovis_db_version;

	require_once ABSPATH . 'wp-admin/includes/upgrade.php';

	/**
	 * Store table names
	 */
    $sSettingsTableName = OVIS_DB_PREFIX . OVIS_PLUGIN_SLUG;

	/**
	 * Create & store SQL queries
	 */
	$sqlCreateSettingsTable = "
		CREATE TABLE IF NOT EXISTS `" . $sSettingsTableName . "` (
			OVIS_id mediumint(9) NOT NULL AUTO_INCREMENT,
			OVIS_authentication varchar(100) NOT NULL DEFAULT '0',
			OVIS_button_bg_color varchar(7) NOT NULL DEFAULT '#DFDFDF',
			OVIS_button_text_color varchar(7) NOT NULL DEFAULT '#333333',
			OVIS_object_bg_color varchar(7) NOT NULL DEFAULT '#DFDFDF',
			OVIS_object_text_color varchar(7) NOT NULL DEFAULT '#333333',
			OVIS_items_per_page int(3) NOT NULL DEFAULT '12',
			OVIS_items_per_page_no_filter int(3) NOT NULL DEFAULT '12',
			OVIS_items_per_row int(1) NOT NULL DEFAULT '3',
			OVIS_position_video_in_gallery varchar(10) NOT NULL DEFAULT 'second',
			OVIS_bg_color varchar(7) NOT NULL DEFAULT '#f6f6f6',
			OVIS_text_color varchar(7) NOT NULL DEFAULT '#333333',
			PRIMARY KEY (OVIS_id)
		) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
	";

	/**
	 * Execute SQL queries
	 * 
	 * @link https://developer.wordpress.org/reference/functions/dbdelta/
	 */
	dbDelta( $sqlCreateSettingsTable);

	/**
	 * Add OVIS database version to the wp_options table
	 * 
	 * @link https://developer.wordpress.org/reference/functions/add_option/
	 */
	add_option('ovis_db_version', $ovis_db_version);
}


/**
 * Insert data into OVIS database
 * 
 * @return void
 */
function ovis_data_install() {
	
	global $wpdb;

    $sSettingsTableName = OVIS_DB_PREFIX . OVIS_PLUGIN_SLUG;

	$sQuery = "
		INSERT INTO `" . $sSettingsTableName . "` (`OVIS_id`) values ('1') 
		ON DUPLICATE KEY UPDATE `OVIS_id`='1'
	";

	if(!$stmt = $wpdb->dbh->prepare( $sQuery)) {
		exit;
	}
	else {
		$sResult = $wpdb->dbh->query( $sQuery) or trigger_error(mysqli_error( $wpdb->dbh), E_USER_ERROR);
	}
}


/**
 * Delete database tables on uninstall
 *
 * @return void
 */
function ovis_db_uninstall() {

    global $wpdb;

	/**
	 * Store table names
	 */
    $sSettingsTableName = OVIS_DB_PREFIX . OVIS_PLUGIN_SLUG;

	/**
	 * Create & store SQL queries
	 */
	$sqlDeleteSettingsTable = "DROP TABLE IF EXISTS `" . $sSettingsTableName . "`";

	/**
	 * Execute SQL queries
	 * 
	 * @link https://developer.wordpress.org/reference/functions/dbdelta/
	 */
	$wpdb->query( $sqlDeleteSettingsTable);

	/**
	 * Delete stored OVIS options
	 */
    delete_option('ovis_db_version');
	delete_option('ovis_plugin_version');
}


/**
 * Delete legacy database tables
 *
 * @return void
 */
function ovis_legacy_db_uninstall() {

	/**
	 * Option name to track if uninstall has run
	 */
	$sOptionName = 'ovis_legacy_db_cleaned';
    
	if(get_option($sOptionName)) {
        return;
    }

	global $wpdb;

	/**
	 * Store table names
	 */
    $sLegacySessionsTableName = OVIS_DB_PREFIX . 'ovis_sessions';

	/**
	 * Create & store SQL queries
	 */
	$sDeleteLegacySessionsTableQuery = "DROP TABLE IF EXISTS `" . $sLegacySessionsTableName . "`";

	/**
	 * Execute SQL queries
	 */
	$wpdb->query($sDeleteLegacySessionsTableQuery);

	/**
	 * Mark as done
	 */
	add_option($sOptionName, 1);
}
add_action('admin_init', 'ovis_legacy_db_uninstall');


/**
 * Register plugin menu
 *
 * OVIS_PAGE_SLUG_1 = general
 * 
 * OVIS_PAGE_SLUG_2 = design
 * 
 * OVIS_PAGE_SLUG_3 = integration
 * 
 * OVIS_PAGE_SLUG_4 = settings
 * 
 * OVIS_PAGE_SLUG_5 = appearance
 * 
 * @return void
 * @link https://developer.wordpress.org/reference/functions/add_menu_page/
 */
function register_menu() {
	
	/**
	 * OVIS
	 */
	add_menu_page(
        OVIS_PLUGIN_NAME, 
        OVIS_PLUGIN_NAME, 
        'manage_options', 
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_1,
        'page_' . OVIS_PAGE_SLUG_1,
		plugin_dir_url( __FILE__ ) . '../assets/img/plugin-icon.png' 
    );

	/**
	 * General / Informatie
	 */
	add_submenu_page(
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_1,
        OVIS_PAGE_NAME_1, 
        OVIS_PAGE_NAME_1, 
        'manage_options', 
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_1,
        'page_' . OVIS_PAGE_SLUG_1
    );

	/**
	 * Design / Vormgeving
	 */
	add_submenu_page(
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_1,
        OVIS_PAGE_NAME_2, 
        OVIS_PAGE_NAME_2,
        'manage_options', 
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_2,
        'page_' . OVIS_PAGE_SLUG_2
    );

	/**
	 * Integration / Integratie
	 */
    add_submenu_page(
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_1,
        OVIS_PAGE_NAME_3, 
        OVIS_PAGE_NAME_3, 
        'manage_options', 
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_3,
        'page_' . OVIS_PAGE_SLUG_3
    );

	/**
	 * Settings / Instellingen
	 */
    add_submenu_page(
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_1,
        OVIS_PAGE_NAME_4, 
        OVIS_PAGE_NAME_4, 
        'manage_options', 
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_4,
        'page_' . OVIS_PAGE_SLUG_4
    );

	/**
	 * Appearance / Weergave
	 */
    add_submenu_page(
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_1,
        OVIS_PAGE_NAME_5, 
        OVIS_PAGE_NAME_5, 
        'manage_options', 
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_5,
        'page_' . OVIS_PAGE_SLUG_5
    );  

	/**
	 * SEO
	 */
    add_submenu_page(
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_1,
        OVIS_PAGE_NAME_6, 
        OVIS_PAGE_NAME_6, 
        'manage_options', 
        OVIS_PLUGIN_SLUG . '-' . OVIS_PAGE_SLUG_6,
        'page_' . OVIS_PAGE_SLUG_6
    );

}


/**
 * Check user permissions
 * 
 * @return void
 */
function user_permissions() {
    if(!current_user_can('manage_options')) {
        wp_die(__('You do not have sufficient permissions to access this page.'));
    }
}


/**
 * General / Informatie page
 * 
 * @return void
 */
function page_general() {
	user_permissions();
    require plugin_dir_path( __FILE__ ) . 'inc_page_general.php';
}


/**
 * Design / Vormgeving page
 * 
 * @return void
 */
function page_design() {
    user_permissions();
	global $oForms;
    require plugin_dir_path( __FILE__ ) . 'inc_page_design.php';
}


/**
 * Integration / Integratie page
 * 
 * @return void
 */
function page_integration() {
    user_permissions();
    global $oData;
	global $oForms;
    require plugin_dir_path( __FILE__ ) . 'inc_page_integration.php';
}


/**
 * Settings / Instellingen page
 * 
 * @return void
 */
function page_settings() {
    user_permissions();
    global $oForms;
    require plugin_dir_path( __FILE__ ) . 'inc_page_settings.php';
}


/**
 * Appearance / Weergave page
 * 
 * @return void
 */
function page_appearance() {
    user_permissions();
    global $oForms;
    require plugin_dir_path( __FILE__ ) . 'inc_page_appearance.php';
}


/**
 * SEO page
 * 
 * @return void
 */
function page_seo() {
    user_permissions();
    require plugin_dir_path( __FILE__ ) . 'inc_page_seo.php';
}


/**
 * Undocumented function
 *
 * @param string $sLanguage
 * @return string
 */
function getOVISTranslation( $sLanguage) {
	switch( $sLanguage) {
		case 'de':
		case 'de_DE':
		case 'de_CH':
			return 'de_DE';

		case 'en':
		case 'en_US':
		case 'en_GB':
		case 'en_CA':
		case 'en_AU':
			return 'en_EN';

		case 'fr':
		case 'fr_FR':
			return 'fr_FR';

		default:
			return 'nl_NL';
	}
}


add_action( 'parse_request', function($wp) {

	if( preg_match( '#ovissitemap/?#', $wp->request, $matches ) ) {
		include_once plugin_dir_path( __FILE__ ) . 'inc_sitemap.php';
		exit;
	}

	if( preg_match( '#^ovis-file/?#', $wp->request, $matches ) ) {
		include_once plugin_dir_path( __FILE__ ) . 'process.file.php';
		exit;
    }
});


/**
 * Rewrite rules
 */
function add_output_rewrite() {
	
	function output_query_vars( $vars ) {
		$vars[] = 'page';
		$vars[] = 'ovis_category';
		$vars[] = 'ovis_object_id';

		return $vars;
	}
	add_filter( 'query_vars', 'output_query_vars' );


	$page_on_front = get_option('page_on_front');

	$rules  = add_rewrite_rule( 
		'^([0-9]+)/?$', 
		'index.php?page=$matches[1]', 
		'top'
	);

	$rules .= add_rewrite_rule( 
		'^([^/]+)/([0-9]+)/?$', 
		'index.php?pagename=$matches[1]&page=$matches[2]', 
		'top' 
	);

	$rules .= add_rewrite_rule( 
		'^details/([^/]+)/([^/]+)/?$',
		'index.php?page_id=' . $page_on_front . '&display=odetails&ovis_category=$matches[1]&ovis_object_id=$matches[2]', 
		'top' 
	);
	
	$rules .= add_rewrite_rule(
		'^([^/]+)/details/([^/]+)/([^/]+)/?$', 
		'index.php?pagename=$matches[1]&display=odetails&ovis_category=$matches[2]&ovis_object_id=$matches[3]',
		'top'
	);

	$rules .= add_rewrite_rule( 
		'^([^/]+)/([^/]+)/details/([^/]+)/([^/]+)/?$', 
		'index.php?pagename=$matches[1]/$matches[2]&display=odetails&ovis_category=$matches[3]&ovis_object_id=$matches[4]', 
		'top' 
	);
	
	$rules .= add_rewrite_rule(
		'^([^/]+)/([^/]+)/([^/]+)/details/([^/]+)/([^/]+)/?$', 
		'index.php?pagename=$matches[1]/$matches[2]/$matches[3]&display=odetails&ovis_category=$matches[4]&ovis_object_id=$matches[5]',
		'top' 
	);

	return $rules;
}
add_action( 'init', 'add_output_rewrite', 1 );


/**
 *  Disable canonical redirect (necessary for output to work on frontpage)
 *
 * @param [type] $redirect
 */
function disable_canonical_redirect_for_front_page( $redirect ) {
	
	if( is_page() && $front_page = get_option( 'page_on_front' ) ) {
		if( is_page( $front_page ) ) {
			$redirect = false;
		}
	}
	return $redirect;
}
add_filter( 'redirect_canonical', 'disable_canonical_redirect_for_front_page' );
add_filter( 'plugins_api', 'ovis_plugin_info', 20, 3 );


/**
 * Undocumented function
 * 
 * $res empty at this step
 * 
 * $args stdClass Object ( [slug] => woocommerce [is_ssl] => [fields] => Array ( [banners] => 1 [reviews] => 1 [downloaded] => [active_installs] => 1 ) [per_page] => 24 [locale] => en_US )
 *
 * @param [type] $res
 * @param [type] $action
 * @param [type] $args
 * @return object|boolean
 */
function ovis_plugin_info( $res, $action, $args ) {
	
	if( 'plugin_information' !== $action ) {
		return false;
	}

	$plugin_slug = 'ovis/index.php';

	if( $plugin_slug !== $args->slug ) {
		return false;
	}

	if( false == $remote = get_transient( 'ovis_update_' . $plugin_slug ) ) {
		
		$remote = wp_remote_get( OVIS_REPOSITORY_URL . '/include/inc.json.php', array(
			'timeout' => 10,
			'headers' => array(
				'Accept' => 'application/json'
			)
		) );
		
		if ( !is_wp_error( $remote ) && isset( $remote['response']['code'] ) && $remote['response']['code'] == 200 && ! empty( $remote['body'] ) ) {
			set_transient( 'ovis_update_' . $plugin_slug, $remote, 43200 ); /* 12 hours cache */
		}
	}
	
	if( !is_wp_error( $remote ) && isset( $remote['response']['code'] ) && $remote['response']['code'] == 200 && ! empty( $remote['body'] ) ) {
		$remote = json_decode( $remote['body'] );
		$res = new stdClass();
		$res->name = $remote->name;
		$res->slug = $plugin_slug;
		$res->version = $remote->version;
		$res->tested = $remote->tested;
		$res->requires = $remote->requires;
		$res->author = $remote->author;
		$res->download_link = $remote->download_url;
		$res->trunk = $remote->download_url;
		$res->requires_php = $remote->requires_php;
		$res->last_updated = $remote->last_updated;
		$res->sections = array(
			'description' => $remote->sections->description,
			'installation' => $remote->sections->installation,
			'changelog' => $remote->sections->changelog
		);
		
		if( !empty( $remote->sections->screenshots ) ) {
			$res->sections['screenshots'] = $remote->sections->screenshots;
		}
		
		if(isset( $remote->banners->high) || isset( $remote->banners->low)) {
			
			$res->banners = array();
			
			if(isset( $remote->banners->high)) {
				$res->banners['high'] = $remote->banners->high;
			}
			
			if(isset( $remote->banners->low)) {
				$res->banners['low'] = $remote->banners->high;
			}
		}
		
		return $res;
	}
	
	return false;
}


/**
 * Undocumented function
 *
 * @param [type] $transient
 */
function ovis_push_update( $transient ) {
	
	if ( empty( $transient->checked ) ) {
		return $transient;
    }

	if( false == $remote = get_transient( 'ovis_index' ) ) {
		
		$remote = wp_remote_get( OVIS_REPOSITORY_URL . '/wp-plugin/json.php', array(
			'timeout' => 10,
			'headers' => array(
				'Accept' => 'application/json'
			)
		) );
		
		if ( !is_wp_error( $remote ) && isset( $remote['response']['code'] ) && $remote['response']['code'] == 200 && !empty( $remote['body'] ) ) {
			set_transient( 'ovis_index', $remote, 43200 ); /* 12 hours cache */
		}
	}

	if( $remote && !is_wp_error($remote) ) {
		$remote = json_decode( $remote['body'] );
		
		if( $remote && version_compare( OVIS_VERSION, $remote->version, '<' ) && version_compare( $remote->requires, get_bloginfo('version'), '<' ) ) {
			$res = new stdClass();
			$res->slug = 'ovis/index.php';
			$res->plugin = 'ovis/index.php';
			$res->new_version = $remote->version;
			$res->tested = $remote->tested;
			$res->package = $remote->download_url;
			$transient->response[$res->plugin] = $res;
		}
	}

    return $transient;
}
add_filter( 'site_transient_update_plugins', 'ovis_push_update' );


/**
 * Set title tag
 *
 * @param [type] $title
 * @return string
 */
function ovis_overrule_title( $title ) {
	
	global $metaTitle404;
	
	if( !empty( $metaTitle404 ) ) {
		return $metaTitle404;
	}

	$ovisUrlCategory = get_query_var( 'ovis_category' );
	$ovisUrlObjectId = get_query_var( 'ovis_object_id' );

	if( empty( $ovisUrlObjectId ) ) {
		return $title;
	}

	/**
	 * OVIS presentation details
	 */
	$metaData 		= explode('-', $ovisUrlObjectId );
	$metaLastKeys 	= array_keys( $metaData );
	$metaLastPart   = end( $metaLastKeys );
	$metaParts 		= '';
	
	foreach( $metaData as $key => $data ) {
		if ( $key == $metaLastPart ) {
			$metaParts .= ucfirst( $data );
		} 
		else if( $key > 0 ) {
			$metaParts .= ucfirst( $data ) . ' ';
		}
	}

	$metaObject = str_replace( '.html', '', $metaParts );
	$metaTitle = urldecode( $metaObject ) . ' - ' . get_bloginfo();
	
	if( !empty( $ovisUrlCategory ) && !empty( $ovisUrlObjectId ) ) {
		$title = $metaTitle;
		return $title;
	}
}
add_filter( 'pre_get_document_title', 'ovis_overrule_title', 999, 1 );


/**
 * Check for active SEO plugin
 *
 * @return bool Returns true for active SEO plugin
 */
function ovis_check_seo_plugins_active() {
	
	/**
	 * wp-seo = Yoast SEO
	 * all-in-one-seo-pack = All in One SEO Pack
	 * 
	 * @link https://wordpress.org/plugins/wordpress-seo/
	 * @link https://wordpress.org/plugins/all-in-one-seo-pack/
	 */
	$active_plugins = apply_filters( 'active_plugins', get_option( 'active_plugins' ) );	

	/**
	 * Loop through active plugins
	 */
	foreach( $active_plugins as $plugin) {

		/**
		 * Check for SEO plugins
		 */
		if( strpos( $plugin, 'wp-seo' ) || strpos( $plugin, 'all_in_one_seo_pack' ) ) {

			/**
			 * Active SEO plugin
			 */
			return true;
		}
	}

	/**
	 * No active SEO plugin
	 */
	return false;
}


/**
 * Set meta and og tags
 *
 * @return void
 */
function ovis_meta_tags() {
	
	$ovisUrlCategory = get_query_var( 'ovis_category' );
	$ovisUrlObjectId = get_query_var( 'ovis_object_id' );

	if(empty($ovisUrlObjectId)) return;

	global $metaTitle;
	global $metaTitle404;
	global $metaDescr;
	global $metaCanonical;
	global $sDetailImage;
	global $wp_session;

	/**
	 * OVIS presentation details
	 */
	$metaData 		= explode('-', $ovisUrlObjectId );
	$metaLastKeys 	= array_keys( $metaData );
	$metaLastPart   = end( $metaLastKeys );
	$metaParts 		= '';

	foreach( $metaData as $key => $data) {
		if ( $key == $metaLastPart ) {
			$metaParts .= ucfirst( $data );
		}
		else if( $key > 0) {
			$metaParts .= ucfirst( $data ) . ' ';
		}
	}

	$sCusomCanoURL  = get_home_url();
	$sCusomCanoURL .= !empty( $_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : false;
	$metaObject 	= str_replace( '.html', '', $metaParts );
	$metaTitle  	= urldecode( $metaObject ) . ' - ' . get_bloginfo();
	$metaDescr 		= 'Bekijk deze ' . $ovisUrlCategory . ' ' . urldecode( $metaObject ) . ' bij ' . get_bloginfo();
	$metaKeywords	= ucfirst( $ovisUrlCategory ) . ', ' . str_replace( ' ', ', ', urldecode( $metaObject ) );
	$metaURL		= $sCusomCanoURL;
	$metaCanonical  = $sCusomCanoURL;
	$sDetailImage 	= false;
	$aSessionKeys 	= array('checkdetails');
	addDataToSession( $aSessionKeys, '' );

	if(empty($ovisUrlCategory)) return;

	if( !empty( $wp_session['session_data']['sSettings'] ) ) {
		$oItemDetails = new data( $wp_session['session_data']['sSettings'], false, 1, false, false, 'all', false, $ovisUrlObjectId, false, false );
		$oItemDetails->search_data(true);
		$bIs404 = true;
		
		if( !empty( $oItemDetails->oObjectData) ) {
			
			$oObjectData = json_decode( $oItemDetails->oObjectData);
			
			if( !empty( $oObjectData->result) && !empty( $oObjectData->data) ) {
				$aSessionKeys = array('checkdetails');
				addDataToSession( $aSessionKeys,base64_encode( $oItemDetails->oObjectData));
				
				if( !empty( $oObjectData->data->data) ) {
					
					if( !empty( $oObjectData->data->data[0]) ) {
						
						$oObjectData = $oObjectData->data->data[0];
						
						if( !empty( $oObjectData->presentation ) ) {

							$bIs404 = false;	

							if( !empty( $oObjectData->presentation->mediainfo) ) {
								if( !empty( $oObjectData->presentation->mediainfo->images) ) {
									if( !empty( $oObjectData->presentation->mediainfo->images[0]) ) {
										$oObjectImages = $oObjectData->presentation->mediainfo->images[0];
										$sDetailImage = $oObjectImages->traditional->original->default->url;
									}
								}
							}
						}
					}
				}
			}
		}

		if( !empty( $bIs404 ) ) {
			$metaTitle404  	= 'Pagina niet gevonden - ' . get_bloginfo();
			$metaTitle  	= 'Pagina niet gevonden - ' . get_bloginfo();
			$metaDescr 		= 'Bekijk deze ' . $ovisUrlCategory . ' ' . urldecode( $metaObject ) . ' bij ' . get_bloginfo();					
			status_header(404);
		}

	}

	/**
	 * OVIS meta tags
	 */
	$metaTags  = "\n";

	/**
	 * No active SEO plugin
	 */
	if( !ovis_check_seo_plugins_active() ) {

		$metaTags .= "<!-- OVIS Meta Tags -->\n";
		$metaTags .= "<meta name=\"title\" content=\"" . $metaTitle . "\" />\n";
		$metaTags .= "<meta name=\"keywords\" content=\"" . $metaKeywords . "\" />\n";
		$metaTags .= "<meta name=\"description\" content=\"" . $metaDescr . "\" />\n";
		
		if(!empty( $sDetailImage)) {
			$metaTags .= "<meta property=\"og:image\" content=\"".$sDetailImage."\">";
			$metaTags .= "<meta property=\"og:image:width\" content=\"800\">";
			$metaTags .= "<meta property=\"og:image:width\" content=\"600\">";
		}

		$metaTags .= "<meta property=\"og:locale\" content=\"nl_NL\" />\n";
		$metaTags .= "<meta property=\"og:type\" content=\"website\" />\n";
		$metaTags .= "<meta property=\"og:title\" content=\"" . $metaTitle . "123456\" />\n";
		$metaTags .= "<meta property=\"og:description\" content=\"" . $metaDescr . "\" />\n";
		$metaTags .= "<meta property=\"og:url\" content=\"".get_permalink()."\" />\n";
		$metaTags .= "<meta property=\"og:site_name\" content=\"" . get_bloginfo() . "\" />\n";
		$metaTags .= "<meta name=\"twitter:card\" content=\"summary_large_image\" />\n";
		$metaTags .= "<meta name=\"twitter:description\" content=\"" . $metaDescr . "\" />\n";
		$metaTags .= "<meta name=\"twitter:title\" content=\"" . $metaTitle . "\" />\n";
	}
	
	echo $metaTags;


	/**
	 * Replace YOAST SEO meta tags
	 *
	 * @param [type] $title
	 * @return string
	 */
	function ovis_replace_ogtitle( $title ) {
		global $metaTitle;
		$title = $metaTitle;
		return $title;
	}
	add_filter( 'wpseo_opengraph_title', 'ovis_replace_ogtitle', 999 );


	function ovis_replace_ogdescription( $description ) {
		global $metaDescr;
		$description = $metaDescr;
		return $description;
	}
	add_filter( 'wpseo_opengraph_desc', 'ovis_replace_ogdescription', 999 );


	function ovis_replace_ogimage( $presentation ) {
		
		global $sDetailImage;
		
		if (!empty( $sDetailImage) ) {
			$presentation->open_graph_images = [
				[
					'url' => $sDetailImage,
					'width' => 800,
					'height' => 600,
					'type' => 'image/jpeg'
				]
			];
		}

		return $presentation;
	}
	add_filter( 'wpseo_frontend_presentation', 'ovis_replace_ogimage', 999 );


	function ovis_replace_ogurl( $url ) {
		global $metaURL;
		$url = $metaURL;
		return $url;
	}
	add_filter( 'wpseo_opengraph_url', 'ovis_replace_ogurl', 999 );


	function ovis_replace_description( $description ) {
		global $metaDescr;
		$description = $metaDescr;
		return $description;
	}
	add_filter( 'wpseo_metadesc', 'ovis_replace_description', 999 );
	
	
	function ovis_replace_canonical( $canonical ) {
		global $metaCanonical;
		$canonical = $metaCanonical;
		return $canonical;
	}
	add_filter( 'wpseo_canonical', 'ovis_replace_canonical', 999 );


	function ovis_replace_title( $title ) {
		global $metaTitle;
		$title = $metaTitle;
		return $title;
	}
	add_filter( 'wpseo_title', 'ovis_replace_title', 999 );

}
add_action( 'wp_head', 'ovis_meta_tags', 1 );


/**
 * Start session
 *
 * @return void
 */
function start_session() {

	global $wp_session;

	check_database();

	if( empty( $wp_session['session_data']['sSettings']) || is_user_logged_in() ) {
		$_oSettings = new settings();
		addDataToSession( array('sSettings'), $_oSettings->get_settings() );

		$sAuthKeyRaw = $wp_session['session_data']['sSettings']['settings']['authentication_key'];
	}
}
add_action( 'init', 'start_session', 2 );


/**
 * Add data to a nested session array using an array of keys.
 *
 * @param array [$aKeys] - Keys representing the nested structure
 * @param mixed [$data] - The data to store
 * @return bool True on success, false on failure
 */
function addDataToSession( $aKeys = false, $data = false ) {

	if(empty($aKeys) || !is_array($aKeys)) return false;

	global $wp_session;

	if(!isset($wp_session['session_data']) || !is_array($wp_session['session_data'])) {
		$wp_session['session_data'] = [];
	}

	$ref = &$wp_session['session_data'];

	foreach($aKeys as $key) {
        if(!isset($ref[$key]) || !is_array($ref[$key])) {
            $ref[$key] = [];
        }
        $ref =& $ref[$key];
    }

    // Now $ref points to the final nested level; assign data
    $ref = $data;

	return true;
}


/**
 * Check database
 */
function check_database() {
	
	/**
	 * Check if admin
	 */
	if( !is_admin() ) {
		return;
	}

	global $wpdb;
	
	$iCurrentVersion = get_option( 'ovis_plugin_version' );

	/**
	 * Check for stored OVIS plugin version
	 */
	if( empty( $iCurrentVersion ) ) {

		/**
		 * Store OVIS plugin version
		 */
		add_option( 'ovis_plugin_version', OVIS_VERSION );
	}
	
	/**
	 * Retrieve & store the set OVIS plugin version
	 */
	$iNewVerson = OVIS_VERSION;
	
	/**
	 * Check if OVIS plugin versions match
	 */
	if( $iCurrentVersion != $iNewVerson ) {
		
		/**
		 * Update OVIS plugin version
		 */
		update_option('ovis_plugin_version', OVIS_VERSION);
	
		/**
		 * Create settings table name
		 */
		$sSettingsTableName = OVIS_DB_PREFIX . "ovis";
	
		/**
		 * Create settings table SQL query
		 */
		$sqlCreateSettingsTable = "
			CREATE TABLE IF NOT EXISTS `" . $sSettingsTableName . "` (
				OVIS_id mediumint(9) NOT NULL AUTO_INCREMENT,
				OVIS_authentication varchar(100) NOT NULL DEFAULT '0',
				OVIS_button_bg_color varchar(7) NOT NULL DEFAULT '#DFDFDF',
				OVIS_button_text_color varchar(7) NOT NULL DEFAULT '#333333',
				OVIS_object_bg_color varchar(7) NOT NULL DEFAULT '#DFDFDF',
				OVIS_object_text_color varchar(7) NOT NULL DEFAULT '#333333',
				OVIS_items_per_page int(3) NOT NULL DEFAULT '12',
				OVIS_items_per_page_no_filter int(3) NOT NULL DEFAULT '12',
				OVIS_items_per_row int(1) NOT NULL DEFAULT '3',
				OVIS_position_video_in_gallery varchar(10) NOT NULL DEFAULT 'second',
				OVIS_bg_color varchar(7) NOT NULL DEFAULT '#f6f6f6',
				OVIS_text_color varchar(7) NOT NULL DEFAULT '#333333',
				PRIMARY KEY (OVIS_id)
			) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
		";

		$sResult = $wpdb->dbh->query( $sqlCreateSettingsTable ) or trigger_error( mysqli_error( $wpdb->dbh ), E_USER_ERROR );

		$sQuery = "
			SELECT * FROM " . OVIS_DB_PREFIX . "ovis 
			WHERE 1=1 LIMIT 1
		";
	
		if(!$stmt = $wpdb->dbh->prepare( $sQuery)) {
			/*$this->bSettingsError = true; */
		} 
		else {
			
			$sResult = $wpdb->dbh->query( $sQuery ) or trigger_error( mysqli_error( $wpdb->dbh ), E_USER_ERROR );
			
			if( $sResult) {
				
				$sRow = mysqli_fetch_object( $sResult );
				
				if( !property_exists( $sRow, 'OVIS_anchor' ) ) {
					
					$sQueryAdd = "
						ALTER TABLE `".OVIS_DB_PREFIX."ovis` 
						ADD COLUMN `OVIS_anchor` VARCHAR(50) NOT NULL;
					";
					
					if( !$stmt = $wpdb->dbh->prepare( $sQueryAdd ) ) {
						/*$this->bSettingsError = true;	 */
					} 
					else {
						$sResult = $wpdb->dbh->query( $sQueryAdd) or trigger_error(mysqli_error( $wpdb->dbh), E_USER_ERROR);
					}
				}
				
				if( !property_exists( $sRow, 'OVIS_sessionclean' ) ) {
					
					$sQueryAdd = "
						ALTER TABLE `".OVIS_DB_PREFIX."ovis` 
						ADD COLUMN `OVIS_sessionclean` DATETIME NULL;
					";
					
					if( !$stmt = $wpdb->dbh->prepare( $sQueryAdd ) ) {
						/*$this->bSettingsError = true;	 */
					} 
					else {
						$sResult = $wpdb->dbh->query( $sQueryAdd ) or trigger_error( mysqli_error( $wpdb->dbh ), E_USER_ERROR );
					}
				} 
				
				if( !property_exists( $sRow, 'OVIS_items_per_page_no_filter' ) ) {
					
					$sQueryAdd = "
						ALTER TABLE `".OVIS_DB_PREFIX."ovis` 
						ADD COLUMN `OVIS_items_per_page_no_filter` int(3) NOT NULL DEFAULT '12' AFTER OVIS_items_per_page;
					";
					
					if( !$stmt = $wpdb->dbh->prepare( $sQueryAdd ) ) {
						/*$this->bSettingsError = true; */
					} 
					else {
						$sResult = $wpdb->dbh->query( $sQueryAdd ) or trigger_error( mysqli_error( $wpdb->dbh ), E_USER_ERROR );
					}
				}

				if( !property_exists( $sRow, 'OVIS_position_video_in_gallery' ) ) {
					
					$sQueryAdd = "
						ALTER TABLE `" . OVIS_DB_PREFIX . "ovis` 
						ADD COLUMN `OVIS_position_video_in_gallery` varchar(7) NOT NULL DEFAULT 'second' AFTER OVIS_items_per_page_no_filter;
					";
					
					if( !$stmt = $wpdb->dbh->prepare( $sQueryAdd ) ) {
						/*$this->bSettingsError = true; */
					} 
					else {
						$sResult = $wpdb->dbh->query( $sQueryAdd ) or trigger_error( mysqli_error( $wpdb->dbh ), E_USER_ERROR );
					}
				}
				
				if( !property_exists( $sRow,'OVIS_custom_css' ) ) {
					
					$sQueryAdd = "
						ALTER TABLE `" . OVIS_DB_PREFIX . "ovis` 
						ADD COLUMN `OVIS_custom_css` TEXT NOT NULL;
					";
					
					if( !$stmt = $wpdb->dbh->prepare( $sQueryAdd ) ) {
						/*$this->bSettingsError = true;		 */
					} 
					else {
						$sResult = $wpdb->dbh->query( $sQueryAdd ) or trigger_error(mysqli_error( $wpdb->dbh ), E_USER_ERROR);
					}
				}
				
				if( !property_exists( $sRow,'OVIS_translations' ) ) {
					
					$sQueryAdd = "
						ALTER TABLE `" . OVIS_DB_PREFIX . "ovis` 
						ADD COLUMN `OVIS_translations` TEXT NOT NULL;
					";
					
					if( !$stmt = $wpdb->dbh->prepare( $sQueryAdd ) ) {
						/*$this->bSettingsError = true;	 */
					} 
					else {
						$sResult = $wpdb->dbh->query( $sQueryAdd ) or trigger_error( mysqli_error( $wpdb->dbh ), E_USER_ERROR );
					}
				}
				
				if (!property_exists( $sRow,'OVIS_texts' ) ) {
					
					$sQueryAdd = "
						ALTER TABLE `" . OVIS_DB_PREFIX . "ovis` 
						ADD COLUMN `OVIS_texts` TEXT NOT NULL;
					";
					
					if( !$stmt = $wpdb->dbh->prepare( $sQueryAdd ) ) {
						/*$this->bSettingsError = true;		 */
					} 
					else {
						$sResult = $wpdb->dbh->query( $sQueryAdd ) or trigger_error( mysqli_error( $wpdb->dbh ), E_USER_ERROR );
					}
				}
			}
		}
	}
}
add_action('init', 'check_database', 1);


function ovis_get_css_dep_file($file_name) {
	return OVIS_CSS_PATH . 'dependencies/' . $file_name . '.min.css';
}


function ovis_get_js_file($file_name) {
	$devPath = OVIS_JS_PATH . $file_name . '.js';
	$prodPath = OVIS_ROOT_PATH . 'dist/' . $file_name . '.min.js';
	return OVIS_PLUGIN_DEV_MODE ? $devPath : $prodPath;
}


function ovis_get_js_dep_file($file_name) {
	return OVIS_JS_PATH . 'dependencies/' . $file_name . '.min.js';
}


/**
 * Include necessary scripts and styles for admin section
 *
 * @param string $hook The current admin page
 * @return void
 * @link https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/
 */
function enqueue_admin_ovis( string $hook ) {
	
	$pages = array(
		'toplevel_page_ovis-general',
		'ovis_page_ovis-design',
		'ovis_page_ovis-integration',
		'ovis_page_ovis-settings',
		'ovis_page_ovis-appearance',
		'ovis_page_ovis-translation',
		'ovis_page_ovis-seo'
	);

	/**
	 * Look through pages for match
	 */
	if( !in_array( $hook, $pages) ) {
        return;
    }

	/**
	 * CSS
	 */
	if( OVIS_PLUGIN_DEV_MODE ) {
		wp_enqueue_style( 'ovis_style_default', OVIS_CSS_PATH . 'style-default.css', array(), OVIS_VERSION );
	} else {
		$cssProdDir = OVIS_ROOT_PATH . 'dist/css/';
		wp_enqueue_style( 'ovis_style_default', $cssProdDir . 'style-default.min.css', array(), OVIS_VERSION );
	}
	wp_enqueue_style( 'ovis_style_spectrum', ovis_get_css_dep_file('legacy/jquery-spectrum'), array(), OVIS_VERSION );

	/**
	 * Scripts
	 */
	wp_enqueue_script( 'ovis_script_admin', ovis_get_js_file('ovis-admin'), array('jquery'), OVIS_VERSION );
	wp_enqueue_script( 'ovis_script_jquery_spectrum', ovis_get_js_dep_file('legacy/jquery.spectrum'), array('jquery'), OVIS_VERSION );
	wp_enqueue_script( 'ovis_script_jquery_ui', ovis_get_js_dep_file('legacy/jquery.ui'), array('jquery'), OVIS_VERSION );
	wp_enqueue_script( 'ovis_script_jquery_ui_widget', ovis_get_js_dep_file('legacy/jquery.ui.widget'), array('jquery'), OVIS_VERSION );
	wp_localize_script( 'ovis_script_admin', 'plugin_url', array( 'plugin_url' => plugins_url() ) );
}
add_action('admin_enqueue_scripts', 'enqueue_admin_ovis');


function load_ovis_plugin_js() {

	$manifestPath = path_join(OVIS_PLUGIN_DIST_DIR_PATH, 'manifest.json');

	if( file_exists( $manifestPath ) && is_readable( $manifestPath ) ) {
		$content = file_get_contents( $manifestPath );

		$manifest = json_decode( $content, true );

		if( json_last_error() !== JSON_ERROR_NONE ) {
			ovis_write_log( 'JSON decode error in manifest.json: ' . json_last_error_msg() );
			$manifest = [];
		}
	} else {
		ovis_write_log( 'manifest.json not found or unreadable at ' . $manifestPath );
		$manifest = [];
	}

	$ovisUrlObjectId = get_query_var( 'ovis_object_id' );

	$distUri = OVIS_PLUGIN_DIR_URI . 'dist/';

	if( !empty( $ovisUrlObjectId ) ) {
		wp_enqueue_script( 'ovis-detail', $distUri . $manifest['detail.js'], array(), null, false );
		wp_add_inline_script( 'ovis-detail', 'window.ovisPublicPath = "' . $distUri . '";', 'before' );
		wp_enqueue_script( 'ovis_script_presentation_detail', ovis_get_js_file( 'ovis-presentation-detail' ), array('jquery'), OVIS_VERSION );
	} else {
		wp_enqueue_script( 'ovis-listing', $distUri . $manifest['listing.js'], array(), null, false );
		wp_add_inline_script( 'ovis-listing', 'window.ovisPublicPath = "' . $distUri . '";', 'before' );
	}

	/**
	 * Dependencies
	 */
	// Check if jQuery is already enqueued
	if( !wp_script_is( 'jquery', 'enqueued' ) ) {
		wp_enqueue_script( 'jquery' );
	}

	if( !empty($ovisUrlObjectId) ) {
		wp_enqueue_script( 'ovis_script_jquery_ui', ovis_get_js_dep_file('legacy/jquery.ui'), array('jquery'), OVIS_VERSION );
		wp_enqueue_script( 'ovis_script_jquery_dateTimePicker', ovis_get_js_dep_file('legacy/dateTimePicker'), array('jquery'), OVIS_VERSION );
		wp_enqueue_script( 'ovis_script_jquery_fotorama', ovis_get_js_dep_file('legacy/jquery.fotorama'), array('jquery'), OVIS_VERSION );
	}

	/**
	 * Pass data to JavaScript
	 */
	if( !empty($ovisUrlObjectId) ) {
		wp_localize_script( 'ovis_script_presentation_detail', 'plugin_url', array( 'plugin_url' => plugins_url() ) );
		wp_localize_script( 'ovis_script_presentation_detail', 'my_ajax_object', array( 'ajax_url' => admin_url('admin-ajax.php')) );
	}
}


/**
 * Load CSS files
 *
 * @param [type] $versionAssets
 * @return void
 */
function load_ovis_plugin_css( $versionAssets ) {
	
	global $wp_session;

	/**
	 * Retrieve & store OVIS presentation ID
	 */
	$ovisUrlObjectId = get_query_var( 'ovis_object_id' );

	if( OVIS_PLUGIN_DEV_MODE ) {
		wp_enqueue_style( 'ovis_style_theme', OVIS_CSS_PATH . 'ovis-theme.css', array(), true, $versionAssets );
		wp_enqueue_style( 'ovis_style_global', OVIS_CSS_PATH . 'ovis-global.css', array(), true, $versionAssets );
		wp_enqueue_style( 'ovis_style_output', OVIS_CSS_PATH . 'style-output.css', array(), true, $versionAssets );
	
		if( !empty($ovisUrlObjectId) ) {
			wp_enqueue_style( 'ovis_style_print', OVIS_CSS_PATH . 'style-print.css', array(), true, 'print' );
			wp_enqueue_style( 'ovis_style_detail', OVIS_CSS_PATH . 'ovis-detail.css', array(), true, $versionAssets );
		} else {
			wp_enqueue_style ('ovis_style_listing', OVIS_CSS_PATH . 'ovis-listing.css', array('ovis_style_global'), true, $versionAssets );
			wp_enqueue_style ('ovis_style_filter', OVIS_CSS_PATH . 'ovis-filter.css', array('ovis_style_global'), true, $versionAssets );
		}
	} else {
		$cssProdDir = OVIS_ROOT_PATH . 'dist/css/';
		wp_enqueue_style( 'ovis_style_global_bundle', $cssProdDir . 'ovis-wp-plugin-global-bundle.min.css', array(), true, $versionAssets );
		
		if( !empty($ovisUrlObjectId) ) {
			wp_enqueue_style( 'ovis_style_detail_bundle', $cssProdDir . 'ovis-wp-plugin-detail-bundle.min.css', array('ovis_style_global_bundle'), true, $versionAssets );
		} else {
			wp_enqueue_style( 'ovis_style_listing_bundle', $cssProdDir . 'ovis-wp-plugin-listing-bundle.min.css', array('ovis_style_global_bundle'), true, $versionAssets );
		}
	}

	/**
	 * Dependencies
	 */
	if( !empty($ovisUrlObjectId) ) {
		wp_enqueue_style('ovis_style_font_awesome', ovis_get_css_dep_file('legacy/all'), array(), true );
		wp_enqueue_style('ovis_style_fotorama', ovis_get_css_dep_file('legacy/jquery-fotorama'), array(), true );
		wp_enqueue_style('ovis_style_jquery_ui', ovis_get_css_dep_file('legacy/jquery-ui'), array(), true );
		wp_enqueue_style('ovis_style_dateTimePicker', ovis_get_css_dep_file('legacy/dateTimePicker'), array(), true );
		wp_enqueue_style('ovis_style_dropzone', ovis_get_css_dep_file('dropzone'), array(), false );
	} else {
		wp_enqueue_style('ovis_style_choices', ovis_get_css_dep_file('choices'), array(), true );
	}
	wp_enqueue_style('ovis_style_air_datepicker', ovis_get_css_dep_file('air-datepicker'), array(), true );
	
	$button_bg_color 	= isset($wp_session['session_data']['sSettings']['settings']['button_bg_color']) ? $wp_session['session_data']['sSettings']['settings']['button_bg_color'] : '';
	$button_text_color 	= isset($wp_session['session_data']['sSettings']['settings']['button_text_color']) ? $wp_session['session_data']['sSettings']['settings']['button_text_color'] : '';
	$object_bg_color 	= isset($wp_session['session_data']['sSettings']['settings']['object_bg_color']) ? $wp_session['session_data']['sSettings']['settings']['object_bg_color'] : '';
	$object_text_color 	= isset($wp_session['session_data']['sSettings']['settings']['object_text_color']) ? $wp_session['session_data']['sSettings']['settings']['object_text_color'] : '';
	$bg_color 			= isset($wp_session['session_data']['sSettings']['settings']['bg_color']) ? $wp_session['session_data']['sSettings']['settings']['bg_color'] : '';
	$text_color 		= isset($wp_session['session_data']['sSettings']['settings']['text_color']) ? $wp_session['session_data']['sSettings']['settings']['text_color'] : '';
	$items_per_row 		= isset($wp_session['session_data']['sSettings']['settings']['items_per_row']) ? $wp_session['session_data']['sSettings']['settings']['items_per_row'] : '';
	$custom_css_db		= isset($wp_session['session_data']['sSettings']['settings']['custom_css']) ? $wp_session['session_data']['sSettings']['settings']['custom_css'] : '';

	$custom_css = '

	#ovis-container {
		--ovis-general-background-color: '.$bg_color.' !important;
		--ovis-general-text-color: '.$text_color.' !important;
		--ovis-hover-general-background-color: '.adjustBrightness($bg_color, -20).' !important;
		--ovis-hover-general-text-color: '.adjustBrightness($text_color, -20).' !important;

		--ovis-button-background-color: '.$button_bg_color.' !important;
		--ovis-label-text-color: '.$button_text_color.' !important;
		--ovis-hover-button-background-color: '.adjustBrightness($button_bg_color, -20).' !important;
		--ovis-hover-label-text-color: '.adjustBrightness($button_text_color, -20).' !important;

		--ovis-price-background-color: '.$object_bg_color.' !important;
		--ovis-price-text-color: '.$object_text_color.' !important;
		--ovis-hover-price-background-color: '.adjustBrightness($object_bg_color, -20).' !important;
		--ovis-hover-price-text-color: '.adjustBrightness($object_text_color, -20).' !important;

		--ovis-detail-top-button-background-color: #f0f0f0;
		--ovis-detail-top-button-text-color: #585858;
	}
	
	.ovis-download-attachment {
		background-color:'.$button_bg_color.' !important; 
		border-color:'.$button_bg_color.' !important; 
		color: '.$button_text_color.' !important;
	}
	
	div.ovis-detail div.ovis-detail-section,
	div.ovis-detail div.ovis-detail-section ul li,
	div.ovis-detail div.ovis-detail-section p,
	section.content .vlak.page p,
	div.ovis-detail div.ovis-detail-section.ovis-user div.ovis-user-block {
		color: '.$text_color.' !important;
	}
	div.ovis-filters {
		background: '.$bg_color.' !important;
		border-color: '.adjustBrightness( $bg_color, -20).' !important;
	}
	div.ovis-filters h3 {
		color: '.$text_color.' !important;			
	}
	form.ovis-search {
		background: '.$bg_color.' !important;
		border-color: '.adjustBrightness( $bg_color, -20).' !important;
	}
	form.ovis-search div.contain-filters,
	form.ovis-search div.contain-filters.hidden {
		border-color: '.adjustBrightness( $bg_color, -20).';
		color: '.$text_color.' !important;
	}
	form.ovis-search div.contain-filter label,
	form.ovis-search div.contain-buttons div.ovis-found p,
	form.ovis-search div div.moreFilters {
		color: '.$text_color.' !important;
	}
	form.ovis-search div.contain-filters.main div.moreFilters:hover,
	form.ovis-search div.contain-filters.main div.moreFilters:hover i {
		color: ' . adjustBrightness( $text_color, -30) . ' !important;
	}
	form.ovis-search input[type="submit"] {
		background: ' . $button_bg_color . ' !important;
		color: ' . $button_text_color . ' !important;
	}
	form.ovis-search input[type="submit"]:hover {
		background: ' . adjustBrightness( $button_bg_color, 20 ) . ' !important;
	}
	#ovis-container.list:not(.minimal) li.object a div.ovis-open-verhuurform .ovis-open-verhuurform-btn {
		background: '.$object_bg_color.' !important;
		color: '.$object_text_color.' !important;
	}
	#ovis-container.list:not(.minimal) li.object a div.ovis-open-verhuurform .ovis-open-verhuurform-btn i {
		color: '.$object_text_color.' !important;	}
	div.ovis-detail div.ovis-detail-top-links a:hover {
		border-color: '.$button_bg_color.' !important;
	}
	';
	
	if( strtolower( $button_bg_color) != '#dfdfdf' ) {
		$custom_css .= 'div.ovis-contactline {
			color: '.$button_bg_color.' !important;
		}';
	}
	
	if( strtolower( $button_bg_color) != '#dfdfdf' ) {
		$custom_css .= '
		div.ovis-detail div.ovis-contain div.ovis-specifications div.more-specs {
			color: ' . $button_bg_color . ' !important;
		}
		
		div.ovis-contactline a {
			color: ' . $button_bg_color . ' !important;
		}';
	}

	if( strtolower( $button_bg_color) != '#dfdfdf' ) {
		$custom_css .= '.ovis-ctabutton, .ovis-ctabutton a {
			color: ' . $button_bg_color . ' !important;
		}';
	}

	$custom_css .= '.ovis-ctabutton.ovis-shop-knop {
		background: ' . $button_bg_color . ' !important;
		color: ' . $button_text_color . ' !important;
	}
	.ovis-cta-choice.active {
		background: ' . $button_bg_color . ' !important;
		color: ' . $button_text_color . ' !important;
	}
	.ovis-action-form .sendbutton {
		background: ' . $button_bg_color . ' !important;
		color: ' . $button_text_color . ' !important;
	}
	.dialog::-webkit-scrollbar {
		width: 12px;
	}
	.dialog::-webkit-scrollbar-thumb {
		border-radius: 12px;
		background-color: ' . $button_text_color . ';
	}
	.dialog::-webkit-scrollbar-thumb:hover {
		background-color: ' . adjustBrightness( $button_text_color, 20 ) . ';
	}
	div.ovis-detail div.ovis-detail-top-links div.social-buttons-c a.social-buttons {
		background: ' . $button_bg_color . ';
		color: ' . $button_text_color . ' !important;
	}
	div.ovis-detail div.ovis-detail-top-links div.social-buttons-c a.social-buttons i {
		color: '.$button_text_color.' !important;
	}
	div.ovis-detail div.ovis-detail-top-links div.social-buttons-c a.social-buttons:hover {
		background: '.adjustBrightness( $button_bg_color, 20).' !important;
	}
	.fotorama__thumb-border {
		border-color: '.$button_bg_color.' !important;
	}';
	
	if( strtolower( $button_bg_color) != '#dfdfdf' ) {
		$custom_css .= 'div.ovis-detail div.ovis-detail-section h3 i {
			color: '.$button_bg_color.' !important;
		}';
	}

	$custom_css .= 'div.ovis-objecten li.object .imgContainer div.label,
	div.ovis-detail .ovis-detail-title div.label {
		background: '.$button_bg_color.' !important;
		color: '.$button_text_color.' !important;
	}
	form.ovis-search div.contain-buttons div.ovis-sort .ovis-order span:hover {
		color: '.$button_text_color.' !important;
	}	
	form.ovis-search div.contain-buttons div.ovis-sort .ovis-order span.active {
		color: '.$button_text_color.' !important;
	}	
	div.ovis-detail div.ovis-detail-section.ovis-media h3 span.button.active {
		background: '.$button_bg_color.' !important;
		border-color: '.$button_bg_color.' !important;
		color: '.$button_text_color.' !important;
	}
	div.ovis-detail div.ovis-detail-section .do-verhuur {
		background: '.$button_bg_color.' !important;
		color: '.$button_text_color.' !important;
	}
	.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active, a.ui-button:active, .ui-button:active, .ui-button.ui-state-active:hover, a.ui-state-default.ui-state-active:hover, a.ui-state-default.ui-state-highlight.ui-state-active, a.ui-state-default.ui-state-highlight.ui-state-active:hover {
		background: '.$button_bg_color.' !important;
		color: '.$button_text_color.' !important;
	}';
	
	if( strtolower( $button_bg_color) != '#dfdfdf' ) {
		$custom_css .= '
		div.ovis-open-inruilform i { color: '.$button_bg_color.' !important; }
		div.ovis-open-inruilform i a { color: '.$button_bg_color.' !important; }
		div.ovis-open-verhuurform i { color: '.$button_bg_color.' !important; }
		div.ovis-open-verhuurform i a { color: '.$button_bg_color.' !important; }
		div.ovis-open-contactform i { color: '.$button_bg_color.' !important; }
		div.ovis-open-contactform i a { color: '.$button_bg_color.' !important; }
		div.ovis-phonenumber i { color: '.$button_bg_color.' !important; }
		div.ovis-phonenumber i a { color: '.$button_bg_color.' !important; }
		div.ovis-show-usercontent i { color: '.$button_bg_color.' !important; }
		div.ovis-show-usercontent i a { color: '.$button_bg_color.' !important; }';
	}

	$custom_css .= 'div.ovis-objecten li.object div.ovis-row.price div strong {
		color: '.$object_text_color.';
	}
	
	div.invalid-filter-message {
		background-color: '.$button_bg_color.' !important;
		color: '.$button_text_color.' !important;
		margin-top:10px;
		padding:10px; 
		box-sizing:border-box;
		font-size:13px !important;
		-webkit-border-radius: 3px;
		border-radius: 3px;
	}
	';

	if( isset( $custom_css_db ) && !empty( $custom_css_db ) ) {
		$custom_css .= stripslashes( $custom_css_db );
	}

	$styleName = OVIS_PLUGIN_DEV_MODE ? 'ovis_style_output' : 'ovis_style_global_bundle';
	wp_add_inline_style( $styleName, $custom_css );
}
add_action( 'wp_enqueue_scripts', 'load_ovis_plugin_css' );


function load_ovis_inline_css() {
	echo '<style id="ovis-critical-atf-style">';
	if( OVIS_PLUGIN_DEV_MODE ) {
		echo file_get_contents(dirname(__DIR__) . '../assets/css/ovis-atf.css');
	} else {
		echo file_get_contents(dirname(__DIR__) . '/dist/css/ovis-atf.min.css');
	}
	echo '</style>';
}
add_action( 'wp_head', 'load_ovis_inline_css', 0 );


/**
 * Parse year range
 *
 * @param string $range
 * @return bool
 */
function parse_year_range($sRange) {

    if(empty($sRange)) return false;

    $aParts = explode('-', $sRange);

    if(count($aParts) == 2 && $aParts[0] <= $aParts[1]) {
        $oYear = new stdClass();
        $oYear->from = (int)$aParts[0];
        $oYear->till = (int)$aParts[1];
        return $oYear;
    }

    return false;
}


/**
 * Parse category
 *
 * @param string $sCategory - Comma-separated input categories
 * @param string $sRealm
 * @return string
 */
function parse_category($sCategory, $sRealm) {

	if(!empty($sRealm) && is_string($sRealm)) $sRealm = trim( strtolower( $sRealm ) );
	
	if($sRealm === 'boten') {
		$aAllowedCategories = explode(',', str_replace(' ', '', OVIS_ALLOWED_BOATCATEGORIES));
		$translationMap = [
			'boot' => 'boat',
			'motor' => 'engine',
			'boottrailer' => 'boattrailer'
		];
	} else {
		$aAllowedCategories = explode(',', str_replace(' ', '', OVIS_ALLOWED_CATEGORIES));
		$translationMap = [
			'kampeerauto' => 'camper',
			'stacaravan' => 'mobilehome',
			'vouwwagen' => 'tenttrailer',
			'aanhangwagen' => 'trailer',
			'caravan' => 'caravan'
		];
	}
	
	if(empty($sCategory)) {
		$sCategory = implode(',', $aAllowedCategories);
	}

	$aInputCategories = array_filter(array_map('trim', explode(',', $sCategory)));
	$aValidCategories  = array_intersect($aInputCategories, $aAllowedCategories);

	$aTranslatedCategories = [];
	foreach($aValidCategories as $cat) {
		if(isset($translationMap[$cat])) {
			$aTranslatedCategories[] = $translationMap[$cat];
		}
	}

	if(empty($aTranslatedCategories)) {
		return 'invalid';
	}

	return implode(',', $aTranslatedCategories);
}


/**
 * Undocumented function
 *
 * @param array $aSortParameters
 * @return object
 */
function parse_sorting($aSortParameters) {

	$sSortField = 'brand';
	$sSortOrder = 'asc';

	if(!empty($aSortParameters[1])) {
		$sSortOrder = $aSortParameters[1] === 'aflopend' ? 'desc' : 'asc';
	}

	$sortableFields = [
		'merk'         => 'brand',
		'prijs'        => 'price',
		'bouwjaar'     => 'constructionYear',
		'gewicht'      => 'maxWeight',
		'slaapplaatsen'=> 'sleepingPlaces',
	];

	$directFields = [
		'categorie'     => 'category',
		'aanmaakdatum'  => 'creationDate',
		'willekeurig'   => 'random',
	];

	if(!empty($aSortParameters[0])) {

		$key = $aSortParameters[0];
	
		if(isset($sortableFields[$key])) {
			$sSortField = $sortableFields[$key] . ($sSortOrder === 'asc' ? '_up' : '_down');
		} elseif(isset($directFields[$key])) {
			$sSortField = $directFields[$key];
		}
	}
	
	$searchSorting = new \stdClass();
	$searchSorting->field = $sSortField;
	$searchSorting->order = $sSortOrder;

	return $searchSorting;
}


function parse_language($language) {

	$language = !empty($language) ? strtolower($language) : false;
	
	/**
	 * Check for retrieved language
	 */
	if(!empty($language)) { 
		
		$aFilteredTaal = array();
	
		$aAllowedLanguages = explode(',',str_replace(' ', '', OVIS_ALLOWED_LANGUAGES));
		$aSetLanguage = explode(',',str_replace(' ', '', $language));
		
		foreach($aSetLanguage as $value) {
			if(in_array($value, $aAllowedLanguages)) {
				$aFilteredTaal[] = $value;
			}
		}

		if(empty($aFilteredTaal)) {
			$aFilteredTaal[] = 'nl';
		}

		$language = $aFilteredTaal;
	}

	return $language;
}


function parse_condition($conditie) {
	
	$condition 		= 'all';
	$conditionSet 	= explode(',', str_replace(' ', '', $conditie));
	
	if(in_array('nieuw', $conditionSet) && !in_array('occasion', $conditionSet)) {
		$condition = 'new';
	} else if( !in_array('nieuw', $conditionSet) && in_array('occasion', $conditionSet) ) {
		$condition = 'occasion';
	}

	return $condition;
}


/**
 * Initialize shortcode OVIS output
 *
 * @param [type] $atts
 * @return void
 */
function display_output_shortcode($atts) {

	global $oOutput;

	$aDefaultAttributes = [
		'aanbieders' => 'nee',
		'anchor' => '',
		'beschikbaar' => 'inbegrepen',
		'bouwjaar' => '',
		'brandstof' => '',
        'btwmarge' => 'ja',
		'categorie' => '',
		'conditie' => 'nieuw, occasion',
		'dealer' => '',
		'dealerfooter' => 'ja',
		'deeplink' => '',
		'extrafilters' => 'dicht',
		'filters' => 'ja',
		'kalender' => 'show',
		'keyword' => '',
		'layout' => '',
		'filterlayout' => '',
		'merk' => '',
		'modeljaar' => '',
		'module' => 'ovis',
		'perrij' => '',
		'prijzen' => '',
		'scrollonload' => 'nee',
        'shopknop' => 'nee',
		'socialmedia' => 'ja',
		'sorteren' => '',
		'specificaties' => 'dicht',
		'status' => '',
		'subcategorie' => '',
		'taal' => 'nl',
		'toonnaw' => 'ja',
		'verbergfilters' => '',
		'verbergspecificaties' => '',
		'verhuur' => 'nee',
		'verkocht' => 'ja',
		'inruilfotos' => 'optioneel',
		'videopositie' => '',
		'calltoaction' => '',
		'volgordespecificaties' => ''
	];

	$aMergedAttributes = shortcode_atts($aDefaultAttributes, $atts);
	extract($aMergedAttributes);

	$availableMap = [
		'isoleren'   => 'only',
		'inbegrepen' => 'include'
	];
	$available = $availableMap[$beschikbaar] ? $availableMap[$beschikbaar] : 'exclude';

	// Keyword
	$keyword = !empty( $keyword) ? $keyword : false;

	// Layout
	$layout = !empty($layout) && $layout == 'blokken' ? 'grid' : (!empty($layout) && $layout == 'lijst' ? 'list' : false);

	// Filter layout
	$filterlayout = !empty($filterlayout) && $filterlayout == 'top' ? 'top' : (!empty($filterlayout) && $filterlayout == 'zijde' ? 'side' : false);

	// Condition
	$condition = parse_condition($conditie);

	// Category
	$category = parse_category($categorie, $module);

	// Subcategory
	$subcategory = !empty($subcategorie) ? $subcategorie : false;

	// Dealer
	$dealer = !empty($dealer) ? $dealer : false;

	// Deeplink
	$deeplink = !empty($deeplink) ? $deeplink : false;

	// BTW marge
	$showBtwMarge = strtolower($btwmarge) == 'nee' ? false : true;

	// Show sold
	$showSold = strtolower($verkocht) === 'nee' ? false : true;

	// Sold at end
	$bSoldAtEnd = strtolower($verkocht) === 'einde' ? true : false;

	// Rental
	$rental = strtolower($verhuur) === 'ja';

	// Scroll on load
	$scrollonload = strtolower($scrollonload) === 'ja';

	// Language
	$taal = parse_language($taal);

	// Shop
	$shop = strtolower($shopknop) == 'ja' ? true : false;

	// Price
	$prijzen = !empty($prijzen) ? strtolower($prijzen) : false;

	// Anchor
	$anchor = !empty($anchor) ? $anchor : false;
	
	// User
	$filterusers = strtolower($aanbieders) === 'ja';
	
	// Brand
	$brands = !empty($merk) ? $merk : false;
	
	// Construction year
	$bouwjaar = parse_year_range($bouwjaar);

	// Model year
	$modeljaar = parse_year_range($modeljaar);

	// Fuel
	$brandstof = !empty($brandstof) ? $brandstof : false;

	// Status
	$status = !empty($status) ? $status : false;

	// Filters
	$searchFilters = strtolower($filters) == 'nee' ? false : (strtolower($filters) == 'open' ? 'expanded' : true);

	// Calendar
	$showCalendar = strtolower($kalender) == 'nee' ? false : true;

	// Sorting
	$aSortParameters = explode(' ', $sorteren);

	// Trade-in pictures
	$inruilfotos = $inruilfotos == 'optioneel' ? 'optional' : ($inruilfotos == 'verplicht' ? 'required' : ($inruilfotos == 'uitgeschakeld' ? 'disabled' : 'optional'));

	// Video position
	if(!empty($videopositie)) {
		$videopositie = $videopositie == 'tweede' ? 'second' : ($videopositie == 'eerste' ? 'first' : ($videopositie == 'laatste' ? 'last' : 'tweede'));
	}

	// Call to action
	$calltoaction = !empty($calltoaction) ? $calltoaction : false;

	// Set condition new or occasion
	$sShowConditionNewOrOccasion = (!empty($condition) ? $condition : 'all');

	// Show 'more specifications' open or closed
	$sMoreSpecifications = (!empty($specificaties) && $specificaties == 'open' ? 'open' : 'closed');

	// Show 'extra filters' open or closed
	$sShowExtraFilters = (!empty($extrafilters) && $extrafilters == 'open' ? 'open' : 'closed');

	// Show 'contact address' on detailpage yes or no
	$sShowContactAddress = (!empty($toonnaw) && $toonnaw == 'ja' ? 'yes' : 'no');

	// Show 'contact social links' on detailpage yes or no
	$sShowSocials = (!empty($socialmedia) && $socialmedia == 'ja' ? 'yes' : 'no');

	// Show 'dealer footer' on detailpage yes or no
	$sShowDealerFooter = (!empty($dealerfooter ) && $dealerfooter == 'ja' ? 'yes' : 'no');
	
	/**
	 * Specification order
	 */
	$aSpecificationsOrder = [];
	$aSpecificationsOrderRaw = (!empty($volgordespecificaties) ? array_map('trim', explode(',', $volgordespecificaties ) ) : [] );
	$aSpecificationsAllowed = ['bouwjaar', 'slaapplaatsen', 'kilometerstand', 'transmissie', 'gordels', 'gewicht', 'lengte', 'laadvermogen', 'breedte', 'subcategorie', 'totalelengte', 'snelvarend', 'vermogen','romp'];
	
	if(!empty($aSpecificationsOrderRaw ) ) {
		foreach($aSpecificationsOrderRaw as $sSpecificationRaw ) {
			if(in_array($sSpecificationRaw, $aSpecificationsAllowed ) ) {
				$aSpecificationsOrder[] = $sSpecificationRaw;
			}
		}
	}

	// Hide filters on frontpage
	$aHideFilters = ( !empty( $verbergfilters ) ? array_map( 'trim', explode( ',', $verbergfilters ) ) : [] );

	// Hide specs
	$aHideSpecs = (!empty( $verbergspecificaties ) ? array_map( 'trim', explode( ',', $verbergspecificaties ) ) : [] );

	// Sorting
	$searchSorting = parse_sorting($aSortParameters);

	load_ovis_plugin_js();

	$oOutput->aLanguages = $taal;
	$oOutput->sShowPrices = $prijzen;

	$oOutput->setRealm($module);
	$oOutput->setCondition($condition);
	$oOutput->setCategory($category);
	$oOutput->setSubcategory($subcategory);
	$oOutput->setDealer($dealer);
	$oOutput->setRental($rental);
	$oOutput->setBrands($brands);
	$oOutput->setBouwjaar($bouwjaar);
	$oOutput->setModeljaar($modeljaar);
	$oOutput->setBrandstof($brandstof);
	$oOutput->setShowSold($showSold);
	$oOutput->setSoldAtEnd($bSoldAtEnd);
	$oOutput->setScrollonload($scrollonload);
	$oOutput->setSearchFilters($searchFilters);
	$oOutput->setShowCalendar($showCalendar);
	$oOutput->setSearchSorting($searchSorting);
	$oOutput->setSearchSortingRaw($sorteren);
	$oOutput->setFilterusers($filterusers);
	$oOutput->setDeeplink($deeplink);
	$oOutput->setAnchor($anchor);
	$oOutput->setPerrij($perrij);
	$oOutput->setShop($shop);
	$oOutput->setAvailable($available);
	$oOutput->setKeyword($keyword);
	$oOutput->setShowBtwMarge($showBtwMarge);
	$oOutput->setStatus($status);
	$oOutput->hideSpecs($aHideSpecs);
	$oOutput->hideFilters($aHideFilters);
	$oOutput->setSpecificationOrder($aSpecificationsOrder);
	$oOutput->showDealerFooter($sShowDealerFooter);
	$oOutput->showSocials($sShowSocials);
	$oOutput->showContactAddress($sShowContactAddress);
	$oOutput->showExtraFilters($sShowExtraFilters);
	$oOutput->showMoreSpecifications($sMoreSpecifications);
	$oOutput->showConditionNewOrOccasion($sShowConditionNewOrOccasion);
	$oOutput->setCallToAction($calltoaction);
	$oOutput->setTradeInPictures($inruilfotos);
	if(!empty($videopositie)) {
		$oOutput->setVideoPosition($videopositie);
	}
	$oOutput->setLayout($layout);
	$oOutput->setFilterLayout($filterlayout);

	return $oOutput->build_output();
}
add_shortcode( 'ovis-voorraad', 'display_output_shortcode' );


/**
 * Adjust color
 *
 * @param [type] $hex
 * @param [type] $steps
 */
function adjustBrightness( $hex, $steps ) {

	if(empty($hex)) return '';

    $steps = max( -255, min( 255, $steps ) );
	$hex = str_replace( '#', '', $hex );	

    if( strlen( $hex ) == 3 ) {
        $hex = str_repeat( substr( $hex, 0, 1 ), 2 ) . str_repeat( substr( $hex, 1, 1 ), 2 ) . str_repeat( substr( $hex, 2, 1 ), 2 );
    }

    $color_parts = str_split( $hex, 2 );
    $newHex = '#';

    foreach( $color_parts as $color ) {
        $color   = hexdec( $color ); 
        $color   = max( 0, min( 255, $color + $steps ) );
		$newHex .= str_pad( dechex( $color ), 2, '0', STR_PAD_LEFT );
	}
	
	return $newHex;
}


/**
 * MySQL error notice
 *
 * @return string
 */
function mysqli_query_error_notice() {
	
	$sHTML = '<section class="ovis-main">
		<article>
			<div class="content">
				<h2 class="ovis-subtitle">Er is een fout opgetreden</h2>
				<p>Neem contact op met de website beheerder.</p>
			</div>
		</article>
	</section>';

	return $sHTML;
}


function save_settings() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
}
add_action( 'wp_ajax_save_settings', 'save_settings' );


function flush_ovis_cache() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
} 
add_action( 'wp_ajax_flush_ovis_cache', 'flush_ovis_cache' );


function save_color() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
} 
add_action( 'wp_ajax_save_color', 'save_color' );


function user_content() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
} 
add_action( 'wp_ajax_user_content', 'user_content' );
add_action( 'wp_ajax_nopriv_user_content', 'user_content' );


function more_filters() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
} 
add_action( 'wp_ajax_more_filters', 'more_filters' );
add_action( 'wp_ajax_nopriv_more_filters', 'more_filters' );


function send_contact() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
} 
add_action( 'wp_ajax_send_contact', 'send_contact' );
add_action( 'wp_ajax_nopriv_send_contact', 'send_contact' );


function send_inruil() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
} 
add_action( 'wp_ajax_send_inruil', 'send_inruil' );
add_action( 'wp_ajax_nopriv_send_inruil', 'send_inruil' );


function send_verhuur() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
} 
add_action( 'wp_ajax_send_verhuur', 'send_verhuur' );
add_action( 'wp_ajax_nopriv_send_verhuur', 'send_verhuur' );


function blocked_days() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
} 
add_action( 'wp_ajax_blocked_days', 'blocked_days' );
add_action( 'wp_ajax_nopriv_blocked_days', 'blocked_days' );


function inruil_image() {
	global $wpdb;
	require_once plugin_dir_path( __FILE__ ) . 'inc_process.php';
	wp_die();
}
add_action( 'wp_ajax_inruil_image', 'inruil_image' );
add_action( 'wp_ajax_nopriv_inruil_image', 'inruil_image' );


/**
 * Enqueue CodeMirror files
 * 
 * This is used for the Custom CSS input on the admin page OVIS -> Appearance
 *
 * @param [type] $hook
 * @return void
 */
function codemirror_enqueue_scripts( $hook ) {
	
	$cm_settings['codeEditor'] = wp_enqueue_code_editor(array(
		'type' => 'text/css'
	));

	wp_localize_script( 'jquery', 'cm_settings', $cm_settings );
	wp_enqueue_script( 'wp-theme-plugin-editor' );
	wp_enqueue_style( 'wp-codemirror' );
}
add_action('admin_enqueue_scripts', 'codemirror_enqueue_scripts');


/**
 * Schedules a recurring cache cleaning event if it's not already scheduled.
 *
 * @return void
 */
function ovis_cache() {
	$args = array(false);
	if( !wp_next_scheduled( 'ovis_clean_cache' , $args ) ) {
		wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'ovis_clean_cache', $args );
    }
}
add_action('wp', 'ovis_cache');





/**
 * Clear the new OVIS cache
 * 
 * @param boolean $bStaleOnly
 * @return void
 */
function clean_new_ovis_cache($bStaleOnly = true) {
	if( !( is_dir( OVIS_PLUGIN_CACHE_DIR_PATH ) ) ) return;

	$iCurrentTime = time();

	foreach( scandir( OVIS_PLUGIN_CACHE_DIR_PATH ) as $file ) {

		if( $file === '.' || $file === '..' ) continue;
		
		$sFullFilePath = OVIS_PLUGIN_CACHE_DIR_PATH . $file;

		if( !( is_file( $sFullFilePath ) ) ) continue;

		if( $bStaleOnly ) {
			if( preg_match( '/_(\d+)_/', $file, $matches ) ) {
				$iDuration = (int)$matches[1];
			} else {
				$iDuration = 3600;
			}
	
			$iFileTime = filemtime( $sFullFilePath );
	
			if( ( $iCurrentTime - $iFileTime ) >= $iDuration ) {
				unlink( $sFullFilePath );
			}
		} else {
			unlink( $sFullFilePath );
		}
	}
}
add_action( 'ovis_clean_cache', 'clean_new_ovis_cache' );


add_action('wp_head', function () {
    echo '<link rel="dns-prefetch" href="https://images.caravans.nl">' . "\n";
	echo '<link rel="dns-prefetch" href="https://images.campersite.nl">' . "\n";
});


require_once 'process.ajax.php';
add_action('wp_ajax_ovis_plugin', 'ovis_plugin_ajax_handler');
add_action('wp_ajax_nopriv_ovis_plugin', 'ovis_plugin_ajax_handler');