<?php
/**
 * @package Layers
 */

/**
* Add define Layers constants to be used around Layers themes, plugins etc.
*/

/**
 * The current version of the theme. Use a random number for SCRIPT_DEBUG mode
 */
define( 'LAYERS_VERSION', '1.6.5' );
define( 'LAYERS_TEMPLATE_URI' , get_template_directory_uri() );
define( 'LAYERS_TEMPLATE_DIR' , get_template_directory() );
define( 'LAYERS_THEME_TITLE' , 'Layers' );
define( 'LAYERS_THEME_SLUG' , 'layers' );
define( 'LAYERS_BUILDER_TEMPLATE' , 'builder.php' );

/**
 * Set the content width based on the theme's design and stylesheet.
 */
if ( ! isset( $content_width ) )
	$content_width = 1080; /* pixels */

/**
 * Adjust the content width when the full width page template is being used
 */
function layers_set_content_width() {
	global $content_width;

	$left_sidebar_active = layers_can_show_sidebar( 'left-sidebar' );
	$right_sidebar_active = layers_can_show_sidebar( 'right-sidebar' );

	if( is_page_template( LAYERS_BUILDER_TEMPLATE ) ) {
		$content_width = 1080;
	} else if( is_page_template( 'template-both-sidebar.php' ) ||
		is_page_template( 'template-left-sidebar.php' ) ||
		is_page_template( 'template-right-sidebar.php' ) ){
		$content_width = 660;
	} elseif ( is_page_template( 'template-blog.php' ) ) {
		$content_width = 1080;
	} elseif( $left_sidebar_active || $right_sidebar_active ){
		$content_width = 660;
	}
}
add_action( 'template_redirect', 'layers_set_content_width' );

/*
 * Third Party Scripts
 */
require_once get_template_directory() . '/core/third-party/site-logo.php';

/*
 * Load Widgets
 */
require_once get_template_directory() . '/core/widgets/init.php';

/*
 * Load Customizer Support
 */
require_once get_template_directory() . '/core/customizer/init.php';

/*
 * Load Custom Post Meta
 */
require_once get_template_directory() . '/core/meta/init.php';

/*
 * Load Front-end helpers
 */
require_once get_template_directory() . '/core/helpers/color.php';
require_once get_template_directory() . '/core/helpers/controls.php';
require_once get_template_directory() . '/core/helpers/custom-fonts.php';
require_once get_template_directory() . '/core/helpers/extensions.php';
require_once get_template_directory() . '/core/helpers/post.php';
require_once get_template_directory() . '/core/helpers/post-types.php';
require_once get_template_directory() . '/core/helpers/sanitization.php';
require_once get_template_directory() . '/core/helpers/template.php';
require_once get_template_directory() . '/core/helpers/woocommerce.php';
if( !defined( 'LAYERS_DISABLE_INTERCOM' ) ){
	require_once get_template_directory() . '/core/helpers/intercom.php';
}

/*
 * Load Admin-specific files
 */
if( is_admin() ){
	// Include form item class
	require_once get_template_directory() . '/core/helpers/forms.php';

	// Include design bar class
	require_once get_template_directory() . '/core/helpers/design-bar.php';

	// Include API class
	require_once get_template_directory() . '/core/helpers/api.php';

	// Include widget export/import class
	require_once get_template_directory() . '/core/helpers/migrator.php';

	//Load Options Panel
	require_once get_template_directory() . '/core/options-panel/init.php';
}

if( ! function_exists( 'layers_setup' ) ) {
	function layers_setup(){
		global $pagenow;

		/**
		 * Add support for HTML5
		 */
		add_theme_support('html5');
		/**
		 * Add support for Title Tags
		 */
		add_theme_support('title-tag');

		/**
		 * Add support for widgets inside the customizer
		 */
		add_theme_support('widget-customizer');

		/**
		 * Add support for WooCommerce
		 */
		add_theme_support( 'woocommerce' );

		/**
		 * Add support for featured images
		 */
		add_theme_support( 'post-thumbnails' );

		// Set Large Image Sizes
		add_image_size( 'layers-square-large', 1000, 1000, true );
		add_image_size( 'layers-portrait-large', 720, 1000, true );
		add_image_size( 'layers-landscape-large', 1000, 720, true );

		// Set Medium Image Sizes
		add_image_size( 'layers-square-medium', 480, 480, true );
		add_image_size( 'layers-portrait-medium', 340, 480, true );
		add_image_size( 'layers-landscape-medium', 480, 340, true );

		/**
		 * Add text domain
		 */
		load_theme_textdomain('layerswp', get_template_directory() . '/languages');

		/**
		 * Add Site Logo Support
		 */

		// Custom Site Logo
		if( !function_exists( 'the_custom_logo' ) ){
			$logo_support = 'site-logo';
		} else {
			$logo_support = 'custom-logo';
		}
		add_theme_support( $logo_support, array(
			'header-text' => array(
				'sitetitle',
				'tagline',
			),
			'flex-width' => true,
			'size' => 'large',
		) );

		// Automatic Feed Links
		add_theme_support( 'automatic-feed-links' );

		// Add support for excerpts in pages
		add_post_type_support( 'page', 'excerpt' );

		/**
		 * Register nav menus
		 */
		register_nav_menus( array(
			LAYERS_THEME_SLUG . '-secondary-left' => __( 'Top Left Menu' , 'layerswp' ),
			LAYERS_THEME_SLUG . '-secondary-right' => __( 'Top Right Menu' , 'layerswp' ),
			LAYERS_THEME_SLUG . '-primary' => __( 'Header Menu' , 'layerswp' ),
			LAYERS_THEME_SLUG . '-primary-right' => __( 'Right Header Menu' , 'layerswp' ),
			LAYERS_THEME_SLUG . '-footer' => __( 'Footer Menu' , 'layerswp' ),
		) );

		/**
		* Welcome Redirect
		*/
		if( isset($_GET["activated"]) && $pagenow = "themes.php" ) { //&& '' == get_option( 'layers_welcome' )

			// Enable Intercom on activation
			if( FALSE === get_option( 'layers_enable_intercom' ) )
				update_option( 'layers_enable_intercom' , '1' );

			update_option( 'layers_welcome' , 1);

			wp_safe_redirect( admin_url('admin.php?page=' . LAYERS_THEME_SLUG . '-get-started'));
		}

		/**
		 * Add support for Partial Widget Refresh.
		 */
		add_theme_support( 'customize-selective-refresh-widgets' );

	} // function layers_setup
} // if !function layers_setup
add_action( 'after_setup_theme' , 'layers_setup', 100 );

/**
 * Port Widgets between Layers Parent theme and Child themes
 */
function layers_backup_site( $value ){
	$theme = wp_get_theme();

	$widget_data = $value[ 'data' ];
	if( isset( $widget_data[ 'wp_inactive_widgets' ] ) ) unset( $widget_data[ 'wp_inactive_widgets' ] );

	update_option( 'layers_tm_backup', get_theme_mods() );
	update_option( 'layers_wgt_backup', $widget_data );

	layers_backup_sidebars_widgets();
}
add_action( 'pre_set_theme_mod_sidebars_widgets' , 'layers_backup_site' );

function layers_resore_site(){
	global $layers_widgets;

	$theme = wp_get_theme();
	$layers_tm_backup = get_option( 'layers_tm_backup' );
	$layers_wgt_backup = get_option( 'layers_wgt_backup' );

	if( $layers_tm_backup ) {
		update_option( 'theme_mods_' . $theme->stylesheet, $layers_tm_backup );
		delete_option ( 'layers_tm_backup' );
	}

	// If the last theme was activated via the themes.php screen, use that backup
	if( $layers_wgt_backup ) {
		update_option( 'sidebars_widgets', $layers_wgt_backup );
		delete_option ( 'layers_wgt_backup' );

	// If a user used the customizer to preview the last theme before activating, look for widgets having been backed up via the theme_mods
	} elseif( get_theme_mod( 'sidebars_widgets' ) ){
		$layers_wgt_backup = get_theme_mod( 'sidebars_widgets' );
		if( isset( $layers_wgt_backup[ 'data' ] ) ) {
			update_option( 'sidebars_widgets', $layers_wgt_backup );
			delete_theme_mod( 'sidebars_widgets' );
		}
	}

}
add_action( 'after_switch_theme' , 'layers_resore_site', 50 );


/**
*  Enqueue front end styles and scripts
*/
if( ! function_exists( 'layers_register_standard_sidebars' ) ) {
	function layers_register_standard_sidebars(){

		/**
		 * Register Standard Sidebars
		 */
		register_sidebar( array(
			'id'		=> LAYERS_THEME_SLUG . '-off-canvas-sidebar',
			'name'		=> __( 'Mobile Sidebar' , 'layerswp' ),
			'description'	=> __( 'This sidebar will only appear on mobile devices.' , 'layerswp' ),
			'before_widget'	=> '<aside id="%1$s" class="content widget %2$s">',
			'after_widget'	=> '</aside>',
			'before_title'	=> '<h5 class="section-nav-title">',
			'after_title'	=> '</h5>',
		) );

		register_sidebar( array(
			'id'		=> LAYERS_THEME_SLUG . '-left-sidebar',
			'name'		=> __( 'Left Sidebar' , 'layerswp' ),
			'before_widget'	=> '<aside id="%1$s" class="content well push-bottom-large widget %2$s">',
			'after_widget'	=> '</aside>',
			'before_title'	=> '<h5 class="section-nav-title">',
			'after_title'	=> '</h5>',
		) );

		register_sidebar( array(
			'id'		=> LAYERS_THEME_SLUG . '-right-sidebar',
			'name'		=> __( 'Right Sidebar' , 'layerswp' ),
			'before_widget'	=> '<aside id="%1$s" class="content well push-bottom-large widget %2$s">',
			'after_widget'	=> '</aside>',
			'before_title'	=> '<h5 class="section-nav-title">',
			'after_title'	=> '</h5>',
		) );

		/**
		 * Register Footer Sidebars
		 */
		for( $footer = 1; $footer < 5; $footer++ ) {
			register_sidebar( array(
				'id'		=> LAYERS_THEME_SLUG . '-footer-' . $footer,
				'name'		=> __( 'Footer ', 'layerswp' ) . $footer,
				'before_widget'	=> '<aside id="%1$s" class="widget %2$s">',
				'after_widget'	=> '</aside>',
				'before_title'	=> '<h5 class="section-nav-title">',
				'after_title'	=> '</h5>',
			) );
		} // for footers

		/**
		 * Register WooCommerce Sidebars
		 */
		if( class_exists( 'WooCommerce' ) ) {
			register_sidebar( array(
				'id'        => LAYERS_THEME_SLUG . '-left-woocommerce-sidebar',
				'name'      => __( 'Left Shop Sidebar' , 'layerswp' ),
				'description'   => __( '' , 'layerswp' ),
				'before_widget' => '<aside id="%1$s" class="content well push-bottom-large widget %2$s">',
				'after_widget'  => '</aside>',
				'before_title'  => '<h5 class="section-nav-title">',
				'after_title'   => '</h5>',
			) );
			register_sidebar( array(
				'id'        => LAYERS_THEME_SLUG . '-right-woocommerce-sidebar',
				'name'      => __( 'Right Shop Sidebar' , 'layerswp' ),
				'description'   => __( '' , 'layerswp' ),
				'before_widget' => '<aside id="%1$s" class="content well push-bottom-large widget %2$s">',
				'after_widget'  => '</aside>',
				'before_title'  => '<h5 class="section-nav-title">',
				'after_title'   => '</h5>',
			) );
		}

	}
}
add_action( 'widgets_init' , 'layers_register_standard_sidebars' , 50 );

/**
*  Enqueue front end styles and scripts
*/
if( ! function_exists( 'layers_scripts' ) ) {
	function layers_scripts(){

		/**
		* Front end Scripts
		*/

		wp_enqueue_script(
			LAYERS_THEME_SLUG . '-plugins' ,
			get_template_directory_uri() . '/assets/js/plugins.js',
			array(
				'jquery',
			),
			LAYERS_VERSION
		); // Sticky-Kit

		wp_enqueue_script(
			LAYERS_THEME_SLUG . '-framework' ,
			get_template_directory_uri() . '/assets/js/layers.framework.js',
			array(
				'jquery',
			),
			LAYERS_VERSION
		); // Framework

		wp_localize_script( LAYERS_THEME_SLUG . '-framework', 'layers_script_settings', array(
			'header_sticky_breakpoint' => apply_filters( 'layers_sticky_header_breakpoint', 270 ),
		) );

		if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
			wp_enqueue_script( 'comment-reply' );
		} // Comment reply script

		// Google Maps
		wp_register_script(
			LAYERS_THEME_SLUG . '-map-api',
			'//maps.googleapis.com/maps/api/js?key=' . layers_get_theme_mod( 'google-maps-api' )
		);
		wp_register_script(
			LAYERS_THEME_SLUG . '-map-trigger',
			get_template_directory_uri().'/core/widgets/js/maps.js',
			array( 'jquery' ),
			LAYERS_VERSION
		);

		/**
		* Front end Styles
		*/

		wp_enqueue_style(
			LAYERS_THEME_SLUG . '-framework' ,
			get_template_directory_uri() . '/assets/css/framework.css',
			array() ,
			LAYERS_VERSION
		);

		wp_enqueue_style(
			LAYERS_THEME_SLUG . '-components',
			get_template_directory_uri() . '/assets/css/components.css',
			array(),
			LAYERS_VERSION
		); // Compontents

		wp_enqueue_style(
			LAYERS_THEME_SLUG . '-responsive',
			get_template_directory_uri() . '/assets/css/responsive.css',
			array(),
			LAYERS_VERSION
		); // Responsive

		wp_enqueue_style(
			LAYERS_THEME_SLUG . '-icon-fonts',
			get_template_directory_uri() . '/assets/css/layers-icons.css',
			array(),
			LAYERS_VERSION
		); // Icon Font

		if( class_exists( 'WooCommerce' ) ) {
			wp_enqueue_style(
				LAYERS_THEME_SLUG . '-woocommerce',
				get_template_directory_uri() . '/assets/css/woocommerce.css',
				array(),
				LAYERS_VERSION
			); // Woocommerce
		}

		if( is_admin_bar_showing() ) {
			wp_enqueue_style(
				LAYERS_THEME_SLUG . '-admin',
				get_template_directory_uri() . '/core/assets/icons.css',
				array(),
				LAYERS_VERSION
			); // Admin CSS
		}

		wp_register_style(
			LAYERS_THEME_SLUG . '-font-awesome',
			get_template_directory_uri() . '/core/assets/plugins/font-awesome/font-awesome.min.css',
			array(),
			LAYERS_VERSION
		); // Font Awesome


		// Swiper Slider
		wp_register_script(
			LAYERS_THEME_SLUG . '-slider-js',
			get_template_directory_uri() . '/core/widgets/js/swiper.js',
			array( 'jquery' ),
			LAYERS_VERSION
		);
		wp_register_style(
			LAYERS_THEME_SLUG . '-slider',
			get_template_directory_uri() . '/core/widgets/css/swiper.css',
			array(),
			LAYERS_VERSION
		);

		// Layers Masonry.
		wp_register_script(
			LAYERS_THEME_SLUG . '-layers-masonry-js',
			get_template_directory_uri() . '/assets/js/layers.masonry.js',
			array(
				'jquery',
				'masonry', // Wordpress Masonry
			),
			LAYERS_VERSION
		);

	}
}
add_action( 'wp_enqueue_scripts' , 'layers_scripts' );

/**
*  Enqueue Layers stylesheet last
*/
if( ! function_exists( 'layers_stylesheet' ) ) {
	function layers_stylesheet(){
		wp_enqueue_style(
			LAYERS_THEME_SLUG . '-style' ,
			get_stylesheet_uri(),
			array() ,
			LAYERS_VERSION
		);

		do_action( 'layers_enqueue_stylesheet' );
	}
}
add_action( 'wp_enqueue_scripts' , 'layers_stylesheet', 100 );
/**
*  Enqueue admin end styles and scripts
*/
if( ! function_exists( 'layers_admin_scripts' ) ) {
	function layers_admin_scripts(){
		global $pagenow, $wp_customize;

		/**
		 * Tip-Tip (renamed to layerTip )
		 */
		wp_enqueue_style(
			LAYERS_THEME_SLUG . '-tip-tip' ,
			get_template_directory_uri() . '/core/assets/plugins/tip-tip/jquery.tipTip.css',
			array(),
			LAYERS_VERSION
		);
		wp_enqueue_script(
			LAYERS_THEME_SLUG . '-tip-tip' ,
			get_template_directory_uri() . '/core/assets/plugins/tip-tip/jquery.tipTip.js',
			array( 'jquery' ),
			LAYERS_VERSION,
			true
		);

		/**
		 * LayersSlct2 (also enqueued by Storekit and WooCommerce).
		 */
		wp_enqueue_style(
			'layersSlct2',
			get_template_directory_uri() . '/core/assets/plugins/select2/layersSlct2.css',
			array(),
			LAYERS_VERSION
		);
		wp_enqueue_style(
			'layersSlct2-skins',
			get_template_directory_uri() . '/core/assets/plugins/select2/layersSlct2-skins.css',
			array(),
			LAYERS_VERSION
		);
		wp_enqueue_script(
			'layersSlct2',
			get_template_directory_uri() . '/core/assets/plugins/select2/layersSlct2.js',
			array( 'jquery' ),
			LAYERS_VERSION
		);

		/**
		 * FontAwesome
		 */
		wp_enqueue_style(
			LAYERS_THEME_SLUG . '-admin-font-awesome',
			get_template_directory_uri() . '/core/assets/plugins/font-awesome/font-awesome.min.css',
			array(),
			LAYERS_VERSION
		);


		/**
		 * Main Admin CSS's
		 */
		wp_enqueue_style(
			LAYERS_THEME_SLUG . '-global',
			get_template_directory_uri() . '/core/assets/layers-global.css',
			array(),
			LAYERS_VERSION
		);

		if ( isset( $wp_customize ) ) {

			/**
			 * Admin Customizer (only)
			 */
			wp_enqueue_style(
				LAYERS_THEME_SLUG . '-customizer',
				get_template_directory_uri() . '/core/assets/layers-customizer.css',
				array(),
				LAYERS_VERSION
			);
		}
		else {

			/**
			 * Admin Dashboard (only)
			 */
			wp_enqueue_style(
				LAYERS_THEME_SLUG . '-admin',
				get_template_directory_uri() . '/core/assets/layers-admin.css',
				array(),
				LAYERS_VERSION
			);
		}


		/**
		 * Admin Editor
		 */
		wp_enqueue_style(
			LAYERS_THEME_SLUG . '-admin-editor',
			get_template_directory_uri() . '/core/assets/plugins/froala/editor.css',
			array(),
			LAYERS_VERSION
		);
		wp_enqueue_script(
			LAYERS_THEME_SLUG . '-admin-editor' ,
			get_template_directory_uri() . '/core/assets/plugins/froala/editor.min.js' ,
			array( 'jquery' ),
			LAYERS_VERSION,
			true
		);


		/**
		 * Admin Migrator
		 */
		wp_enqueue_script(
			LAYERS_THEME_SLUG . '-admin-migrator' ,
			get_template_directory_uri() . '/core/assets/migrator.js' ,
			array(
				'media-upload'
			),
			LAYERS_VERSION,
			true
		);
		wp_localize_script(
			LAYERS_THEME_SLUG . '-admin-migrator',
			'migratori18n',
			array(
				'loading_message' => __( 'Be patient while we import the widget data and images.' , 'layerswp' ),
				'complete_message' => __( 'Import Complete' , 'layerswp' ),
				'importing_message' => __( 'Importing Your Content' , 'layerswp' ),
				'duplicate_complete_message' => __( 'Edit Your New Page' , 'layerswp' )
			)
		);
		wp_localize_script(
			LAYERS_THEME_SLUG . '-admin-migrator',
			"layers_migrator_params",
			array(
					'duplicate_layout_nonce' => wp_create_nonce( 'layers-migrator-duplicate' ),
					'import_layout_nonce' => wp_create_nonce( 'layers-migrator-import' ),
					'preset_layout_nonce' => wp_create_nonce( 'layers-migrator-preset-layouts' ),
				)
		);


		/**
		 * Discover More Photos
		 */
		wp_enqueue_script(
			LAYERS_THEME_SLUG . '-media-views' ,
			get_template_directory_uri() . '/core/assets/media-views.js',
			array(
				'media-views'
			),
			LAYERS_VERSION
		);


		/**
		 * Admin Onboarding
		 */
		wp_enqueue_script(
			LAYERS_THEME_SLUG . '-admin-onboarding' ,
			get_template_directory_uri() . '/core/assets/onboarding.js',
			array(
					'jquery'
				),
			LAYERS_VERSION,
			true
		);
		wp_localize_script(
			LAYERS_THEME_SLUG . '-admin-onboarding' ,
			"layers_onboarding_params",
			array(
				'preset_layout_nonce' => wp_create_nonce( 'layers-migrator-preset-layouts' ),
				'update_option_nonce' => wp_create_nonce( 'layers-onboarding-update-options' ),
				'set_theme_mod_nonce' => wp_create_nonce( 'layers-onboarding-set-theme-mods' ),
			)
		);
		wp_localize_script(
			LAYERS_THEME_SLUG . '-admin-onboarding' ,
			'onboardingi18n',
			array(
				'step_saving_message' => __( 'Saving...' , 'layerswp' ),
				'step_done_message' => __( 'Done!' , 'layerswp' )
			)
		);


		/**
		 * Admin JS
		 */
		wp_enqueue_script(
			LAYERS_THEME_SLUG . '-admin' ,
			get_template_directory_uri() . '/core/assets/admin.js',
			array(
				'jquery',
				'jquery-ui-sortable',
				'wp-color-picker',
			),
			LAYERS_VERSION,
			true
		);
		wp_localize_script(
			LAYERS_THEME_SLUG . '-admin' ,
			'layers_admin_params',
			array(
				'backup_pages_nonce' => wp_create_nonce( 'layers-backup-pages' ),
				'backup_pages_success_message' => __('Your pages have been successfully backed up!', 'layerswp' ),
				'nonce_layers_widget_linking' => wp_create_nonce( 'nonce_layers_widget_linking' ),
			)
		);

		wp_enqueue_media();

	}
}

add_action( 'customize_controls_print_footer_scripts' , 'layers_admin_scripts' );
add_action( 'admin_enqueue_scripts' , 'layers_admin_scripts' );

/**
*  Make sure that all excerpts have class="excerpt"
*/
if( !function_exists( 'layers_excerpt_class' ) ) {
	function layers_excerpt_class( $excerpt ) {
		return str_replace( '<p', '<p class="excerpt"', $excerpt );
	}
} // layers_excerpt_class
add_filter( "the_excerpt", "layers_excerpt_class" );
add_filter( "get_the_excerpt", "layers_excerpt_class" );


/*add_filter( 'nav_menu_link_attributes', 'wpse156165_menu_add_class', 10, 3 );

function wpse156165_menu_add_class( $atts, $item, $args ) {
    $class = 'page-scroll'; // or something based on $item
    $atts['class'] = $class;
    return $atts;
}
*/

/***********************************************************************************************************************************************************************************************************************************************************************************************************************************************************/

//CLIENT ACCOUNT
define('API_KEY','6c6rgc2gags6fqa373mujx4h');
define('API_SECRET','j5WPuQMS37');



$signature = hash("sha256", API_KEY.API_SECRET.time());
define('SIGNATURE',$signature);

//hotel image path
define('NORMAL_IMAGE_PATH','http://photos.hotelbeds.com/giata/'); //(320px)
define('BIG_IMAGE_PATH','http://photos.hotelbeds.com/giata/bigger/'); //(800px)
define('MEDIUM_IMAGE_PATH','http://photos.hotelbeds.com/giata/medium/'); //(117px)
define('SMALL_IMAGE_PATH','http://photos.hotelbeds.com/giata/small/');//(74px)


//table names
$hotels_tbl = $wpdb->prefix.'hotels';
$accommodation_tbl = $wpdb->prefix.'accommodations';
$chains_tbl = $wpdb->prefix.'chains';
$categories_tbl = $wpdb->prefix.'categories';
$facilities_tbl = $wpdb->prefix.'facilities';
$facility_group_tbl = $wpdb->prefix.'facility_group';
$boards_tbl = $wpdb->prefix.'boards';
$segments_tbl = $wpdb->prefix.'segments';
$terminals_tbl = $wpdb->prefix.'terminals';
$destinations_tbl = $wpdb->prefix.'destinations';
$countries_tbl = $wpdb->prefix.'countries';
$issues_tbl = $wpdb->prefix.'issues';
$promotions_tbl = $wpdb->prefix.'promotions';
$image_types_tbl = $wpdb->prefix.'image_types';
$group_categories_tbl = $wpdb->prefix.'group_categories';
$currencies_tbl = $wpdb->prefix.'currencies';
$languages_tbl = $wpdb->prefix.'languages';


$hotels_boards_tbl = $wpdb->prefix.'hotels_boards';
$hotels_segments_tbl = $wpdb->prefix.'hotels_segments';
$hotels_phones_tbl = $wpdb->prefix.'hotels_phones';
$hotels_rooms_tbl = $wpdb->prefix.'hotels_rooms';
$hotels_rooms_stays_tbl = $wpdb->prefix.'hotels_rooms_stays';
$hotels_facilities_tbl = $wpdb->prefix.'hotels_facilities';
$hotels_terminals_tbl = $wpdb->prefix.'hotels_terminals';
$hotels_interest_points_tbl = $wpdb->prefix.'hotels_interest_points';
$hotels_images_tbl = $wpdb->prefix.'hotels_images';


$hotels_view = $wpdb->prefix.'hotels_view';


//initiate session
function init_session()
{
  ob_start();
  session_start();
}
add_action('init', 'init_session', 1);

//print a variable or array inside '<pre>' tags
function pr($var){
	if(is_array($var) || is_object($var)){
		echo '<pre>';
		print_r($var);
		echo '</pre>';
	}
	else{
		echo '<pre>';
		echo $var;
		echo '</pre>';
	}
}

//get coordinates
function get_coordinates($address){

  $address = str_replace(" ", "+", $address);

  $url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  $response = curl_exec($ch);
  curl_close($ch);
  $response_a = json_decode($response);
  $lat = $response_a->results[0]->geometry->location->lat;
  $long = $response_a->results[0]->geometry->location->lng;
  return $lat.'|'.$long;
}


//insert hotels in database
function insert_hotels(){

	global $wpdb,
	$hotels_tbl,
	$accommodation_tbl,
	$chains_tbl,
	$categories_tbl,
	$facility_group_tbl,
	$boards_tbl,
	$segments_tbl,
	$terminals_tbl,
	$hotels_boards_tbl,
	$hotels_segments_tbl,
	$hotels_phones_tbl,
	$hotels_rooms_tbl,
	$hotels_rooms_stays_tbl,
	$hotels_facilities_tbl,
	$hotels_terminals_tbl,
	$hotels_interest_points_tbl,
	$countries_tbl,
	$destinations_tbl,
	$hotels_images_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/hotels?fields=all&language=CAS&from=1&to=10";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';



	/*
	foreach($response->hotels as $hotel){

		$exists = $wpdb->get_results("
			SELECT `code`
			FROM `$hotels_tbl`
			WHERE `code`= $hotel->code
		");
		$countryname = $wpdb->get_results("
			SELECT `name`
			FROM `$countries_tbl`
			WHERE `code`= '$hotel->countryCode'
		");
		
		$destinationname = $wpdb->get_results("
			SELECT `name`
			FROM `$destinations_tbl`
			WHERE `code`= '$hotel->destinationCode'
		");
		
		if(empty($exists)){

		    //insert in hotels table
		    $hotel_data = array(
		        'code'                  => $hotel->code,
		        'name'                  => $hotel->name->content,
		        'description'           => $hotel->description->content,
		        'countryCode'           => $hotel->countryCode,
		        'destinationCode'       => $hotel->destinationCode,
		        'zoneCode'              => $hotel->zoneCode,
		        'longitude'             => $hotel->coordinates->longitude,
		        'latitude'              => $hotel->coordinates->latitude,
		        'categoryCode'          => $hotel->categoryCode,
		        'categoryGroupCode'     => $hotel->categoryGroupCode,
		        'chainCode'             => $hotel->chainCode,
		        'accommodationTypeCode' => $hotel->accommodationTypeCode,
		        'address'               => $hotel->address->content,
		        'postalCode'            => $hotel->postalCode,
		        'city'                  => $hotel->city->content,
		        'email'                 => $hotel->email,
		        'license'               => $hotel->license,
		        'web'                   => $hotel->web,
		        'S2C'                   => $hotel->S2C,
		        'hotel_search'			=> $hotel->code.'|'.$hotel->name->content,
		        'destination_search'	=> $destinationname[0]->name.'|'.$hotel->city->content.'|'.$countryname[0]->name
		    );
		    $wpdb->insert($hotels_tbl,$hotel_data);
		    //print_r($hotel_data);
		    $hotel_id = $wpdb->insert_id;

		    
		    //insert in hotel boards table
		    foreach ($hotel->boardCodes as $board) {
		    	$board_data = array(
			        'hotel_id'     => $hotel_id,
			        'board_codes'  => $board
			    );
			    //$wpdb->insert($hotels_boards_tbl,$board_data);
		    }

		    //insert in hotel segment table
		    foreach ($hotel->segmentCodes as $segment) {
		    	$segment_data = array(
			        'hotel_id'       => $hotel_id,
			        'segment_codes'  => $segment
			    );
			    $wpdb->insert($hotels_segments_tbl,$segment_data);
		    }

		    //insert in hotel phones table
		    foreach ($hotel->phones as $phone) {
		    	$phone_data = array(
			        'hotel_id'      => $hotel_id,
			        'phone_no'  	=> $phone->phoneNumber,
			        'phone_type'    => $phone->phoneType
			    );
			    $wpdb->insert($hotels_phones_tbl,$phone_data);
		    }

		    //insert in hotel rooms table
		    foreach ($hotel->rooms as $room) {
		    	$room_data = array(
			        'hotel_id'      	 => $hotel_id,
			        'roomCode'  		 => $room->roomCode,
			        'roomType'    		 => $room->roomType,
			        'characteristicCode' => $room->characteristicCode
			    );
			    $wpdb->insert($hotels_rooms_tbl,$room_data);
			    $room_id = $wpdb->insert_id;

			    //insert in hotel rooms stays table
			    foreach ($room->roomStays as $stays) {
			    	$stay_data = array(
				        'hotel_id'      	=> $hotel_id,
				        'hotel_room_id'  	=> $room_id,
				        'stayType'    		=> $stays->stayType,
				        'stay_order' 		=> $stays->order,
				        'description' 		=> $stays->description
				    );
				    $wpdb->insert($hotels_rooms_stays_tbl,$stay_data);
			    }
		    }


		    //insert in hotel facilities table
		    foreach ($hotel->facilities as $facility) {
		    	$facility_data = array(
			        'hotel_id'      	=> $hotel_id,
			        'facilityCode'  	=> $facility->facilityCode,
			        'facilityGroupCode' => $facility->facilityGroupCode,
			        'facility_order'    => $facility->order,
			        'indFee'    		=> $facility->indFee,
			        'indYesOrNo'    	=> $facility->indYesOrNo
			    );
			    $wpdb->insert($hotels_facilities_tbl,$facility_data);
		    }


		    //insert in hotel terminals table
		    foreach ($hotel->terminals as $terminal) {
		    	$terminal_data = array(
			        'hotel_id'      	=> $hotel_id,
			        'terminalCode'  	=> $terminal->terminalCode,
			        'distance' 			=> $terminal->distance
			    );
			    $wpdb->insert($hotels_terminals_tbl,$terminal_data);
		    }

		    //insert in hotel interestPoints table
		    foreach ($hotel->interestPoints as $interest) {
		    	$interest_data = array(
			        'hotel_id'      	=> $hotel_id,
			        'facilityCode'  	=> $interest->facilityCode,
			        'facilityGroupCode' => $interest->facilityGroupCode,
			        'interest_order'	=> $interest->order,
			        'poiName' 			=> $interest->poiName,
			        'distance' 			=> $interest->distance
			    );
			    $wpdb->insert($hotels_interest_points_tbl,$interest_data);
		    }

		    //insert in hotel images table
		    foreach ($hotel->images as $image) {
		    	$images_data = array(
			        'hotel_id'      	=> $hotel_id,
			        'imageTypeCode'  	=> $image->imageTypeCode,
			        'path' 				=> $image->path,
			        'image_order'		=> $image->order
			    );
			    $wpdb->insert($hotels_images_tbl,$images_data);
		    }
		}
	}*/

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}

//insert accommodation in database
function insert_accommodation(){

	global $wpdb,$accommodation_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/accommodations?fields=all&language=CAS&from=1&to=1000";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	/*echo '<pre>';
	print_r($response);
	echo '</pre>';*/

	foreach($response->accommodations as $hotel){

	    $data = array(
	        'code'  	   => $hotel->code,
	        'name'  	   => $hotel->typeMultiDescription->content,
	        'description'  => $hotel->typeDescription
	    );
	    $wpdb->insert($accommodation_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}


//insert categories in database
function insert_chains(){

	global $wpdb,$chains_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/chains?fields=all&language=CAS&from=2001&to=3000";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->chains as $chain){

	    $data = array(
	        'code'  	   => $chain->code,
	        'content'  	   => $chain->description->content
	    );
	    $wpdb->insert($chains_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}


//insert categories in database
function insert_categories(){

	global $wpdb,$categories_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/categories?fields=all&language=CAS&from=1&to=1000";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->categories as $category){

	    $data = array(
	        'code'  	   		 => $category->code,
	        'simpleCode'  	   	 => $category->simpleCode,
	        'accommodationType'  => $category->accommodationType,
	        'category_group'  	 => $category->group,
	        'description'  	   	 => $category->description->content
	    );
	    $wpdb->insert($categories_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}


//insert boards in database
function insert_boards(){

	global $wpdb,$boards_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/boards?fields=all&language=CAS&from=1&to=1000";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->boards as $board){

	    $data = array(
	        'code'  	   		 => $board->code,
	        'description'  	   	 => $board->description->content,
	        'multiLingualCode'  => $board->multiLingualCode
	    );
	    $wpdb->insert($boards_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}

//insert segments in database
function insert_segments(){

	global $wpdb,$segments_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/segments?fields=all&language=CAS&from=1&to=100";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->segments as $segment){

	    $data = array(
	        'code'  	   		 => $segment->code,
	        'description'  	   	 => $segment->description->content
	    );
	    $wpdb->insert($segments_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}

//insert segments in database
function insert_terminals(){

	global $wpdb,$terminals_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/terminals?fields=all&language=CAS&from=1001&to=2000";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->terminals as $terminal){

	    $data = array(
	        'code'  	   		 => $terminal->code,
	        'type'  	   		 => $terminal->type,
	        'country'  	   		 => $terminal->country,
	        'name'  	   		 => $terminal->name->content,
	        'description'  	   	 => $terminal->description->content
	    );
	    $wpdb->insert($terminals_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}

//insert issues in database
function insert_issues(){

	global $wpdb,$issues_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/issues?fields=all&language=CAS&from=1&to=100";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->issues as $issue){

	    $data = array(
	        'code'  	   		 => $issue->code,
	        'type'  	   		 => $issue->type,
	        'description'  	   	 => $issue->description->content,
	        'name'  	   		 => $issue->name->content,
	        'alternative'  	   	 => $issue->alternative
	    );
	   $wpdb->insert($issues_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}


//insert promotions in database
function insert_promotions(){

	global $wpdb,$promotions_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/promotions?fields=all&language=CAS&from=1&to=100";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->promotions as $promotion){

	    $data = array(
	        'code'  	   		 => $promotion->code,
	        'description'  	   	 => $promotion->description->content,
	        'name'  	   		 => $promotion->name->content
	    );
	    $wpdb->insert($promotions_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}

//insert image types in database
function insert_image_types(){

	global $wpdb,$image_types_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/imagetypes?fields=all&language=CAS&from=1&to=100";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->imageTypes as $imagetype){

	    $data = array(
	        'code'  	   		 => $imagetype->code,
	        'description'  	   	 => $imagetype->description->content
	    );
	    $wpdb->insert($image_types_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}

//insert groupcategories in database
function insert_groupcategories(){

	global $wpdb,$group_categories_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/groupcategories?fields=all&language=CAS&from=1&to=100";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->groupCategories as $groupCategory){

	    $data = array(
	        'code'  	   		 => $groupCategory->code,
	        'order'  	   		 => $groupCategory->order,
	        'name'  	   		 => $groupCategory->name->content,
	        'description'  	   	 => $groupCategory->description->content
	    );
	    $wpdb->insert($group_categories_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}


//insert currencies in database
function insert_currencies(){

	global $wpdb,$currencies_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/currencies?fields=all&language=CAS&from=1&to=200";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->currencies as $currency){

	    $data = array(
	        'code'  	   		 => $currency->code,
	        'description'  	   	 => $currency->description->content,
	        'currencyType'  	 => $currency->currencyType
	    );
	    $wpdb->insert($currencies_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}


//insert languages in database
function insert_languages(){

	global $wpdb,$languages_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/languages?fields=all&language=CAS&from=1&to=200";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	foreach($response->languages as $language){

	    $data = array(
	        'code'  	   		 => $language->code,
	        'name'  	 		 => $language->name,
	        'description'  	   	 => $language->description->content,
	        
	    );
	    $wpdb->insert($languages_tbl,$data);

	}

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}


//insert ratecomments in database
function insert_ratecomments(){

	global $wpdb,$languages_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/types/ratecomments?fields=all&language=CAS&from=1&to=10";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	echo '<pre>';
	print_r($response);
	echo '</pre>';

	/*foreach($response->languages as $language){

	    $data = array(
	        'code'  	   		 => $language->code,
	        'name'  	 		 => $language->name,
	        'description'  	   	 => $language->description->content,
	        
	    );
	    //$wpdb->insert($languages_tbl,$data);

	}*/

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}


//insert segments in database
function get_single_hotel_detail($id){

	global $wpdb,$terminals_tbl;

	$url = "https://api.test.hotelbeds.com/hotel-content-api/1.0/hotels/$id?language=CAS";   
	$header[] = "Api-Key: ".API_KEY;
	$header[] = "X-Signature: ".SIGNATURE;
	//$header[] = "Content-Type: application/json";
	$header[] = "Accept: application/json";
	//$header[] = "Accept-encoding: Gzip";

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );  

	//print_r(curl_exec($ch));
	$response = json_decode(curl_exec($ch));
	/*echo '<pre>';
	print_r($response);
	echo '</pre>';*/
	return $response;

	if(!curl_exec($ch)){
	    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
	}
}

//search hotels
function search_hotels($conditions=array()){

	global $wpdb,
	$accommodation_tbl,
	$facilities_tbl,
	$destinations_tbl,
	$hotels_tbl,
	$countries_tbl,
	$hotels_terminals_tbl,
	$hotels_facilities_tbl,
	$categories_tbl,
	$chains_tbl,
	$hotels_view;

	$limit =10;
	$page_no = (isset($conditions['page_no']))?$conditions['page_no']:1;
	$offset = ($page_no-1)*$limit;

	/******************* GET TOTAL COUNT RECORDS *****************/
	/*$count = '';
	$count .= "
	  SELECT 
	    COUNT(*) AS `total_records`
	  FROM `$hotels_view`
	";

	if($conditions['hotel_id']!='0'){
	    $count .= "
	       WHERE 
	       (
		      `$hotels_view`.`hotel_id` = ".$conditions['hotel_id']."
	      )
	    ";
	}else if($conditions['destination']!='0'){
	    $count .= "
	       WHERE 
	       (
		      `$hotels_view`.`destination_name` = '".$conditions['destination']."'
	      )
	    ";
	}else{
	    $count .= "
	       WHERE 
	       (
		      `$hotels_view`.`hotel_search` LIKE '%".$conditions['search_keyword']."%' OR 		      
		      `$hotels_view`.`destination_search` LIKE '%".$conditions['search_keyword']."%'
	      )
	    ";
	}


	if(!empty($conditions['category'])){

	    $count .= "
	       AND `$hotels_view`.`categoryCode` IN ('".implode("','",$_POST['category'])."')
	    ";
	}

	if(!empty($conditions['accomodation'])){

	    $count .= "
	       AND `$hotels_view`.`accommodationTypeCode` IN ('".implode("','",$_POST['accomodation'])."')
	    ";
	}

	if(!empty($conditions['facility'])){
	    
	    $count .= "
	       AND `$hotels_view`.`hotel_id` IN (
	       	SELECT `hotel_id` 
	       	FROM `$hotels_facilities_tbl` 
	       	WHERE `facilityCode` IN ('".implode("','",$_POST['facility'])."')
	    )
	    ";
	}

	if(!empty($conditions['city'])){
	    
	    $count .= "
	       AND `$hotels_view`.`city` IN ('".implode("','",$_POST['city'])."')
	    ";
	}

	$count_rows = $wpdb->get_results($count);*/

	/************* GET ALL ROWS *****************/
	$sql = '';
//($count) AS `total_records`,
	$sql .= "
	  SELECT 
	  	
	    `$hotels_view`.*
	  FROM `$hotels_view`
	";

	if($conditions['hotel_id']!='0'){
	    $sql .= "
	       WHERE 
	       (
		      `$hotels_view`.`hotel_id` = ".$conditions['hotel_id']."
	      )
	    ";
	}else if($conditions['destination']!='0'){
	    $sql .= "
	       WHERE 
	       (
		      `$hotels_view`.`destination_name` = '".$conditions['destination']."'
	      )
	    ";
	}else{
	    $sql .= "
	       WHERE 
	       (
		      `$hotels_view`.`hotel_search` LIKE '%".$conditions['search_keyword']."%' OR 		      
		      `$hotels_view`.`destination_search` LIKE '%".$conditions['search_keyword']."%'
	      )
	    ";
	}

	/******************** Advanced Filters ***********************/

	if(!empty($conditions['category'])){

	    $sql .= "
	       AND `$hotels_view`.`categoryCode` IN ('".implode("','",$_POST['category'])."')
	    ";
	}

	if(!empty($conditions['accomodation'])){

	    $sql .= "
	       AND `$hotels_view`.`accommodationTypeCode` IN ('".implode("','",$_POST['accomodation'])."')
	    ";
	}

	if(!empty($conditions['facility'])){
	    
	    $sql .= "
	       AND `$hotels_view`.`hotel_id` IN (
	       	SELECT `hotel_id` 
	       	FROM `$hotels_facilities_tbl` 
	       	WHERE `facilityCode` IN ('".implode("','",$_POST['facility'])."')
	    )
	    ";
	}

	if(!empty($conditions['city'])){
	    
	    $sql .= "
	       AND `$hotels_view`.`city` IN ('".implode("','",$_POST['city'])."')
	    ";
	}

	/******************** Advanced Filters ***********************/

	$sql .= " LIMIT $offset,$limit";

	//echo $sql;
	$hotels = $wpdb->get_results($sql);
	//$hotels['total_records'] = $count_rows[0]->total_records;
	/*echo '<pre>';
	print_r($hotels);	
	echo '</pre>';
	exit();*/
	return $hotels;
}



/**
* for resizing of images
* @param image source, height, width
* @return resizable image source url
*/
function itg_timthumb_image($src, $h = 50, $w = 50) {
    //set your timthumb url
    $timthumb_url = get_bloginfo('wpurl') . '/timthumb.php';
    //check for multisite
    if(is_multisite()) {
        //get rid of the www part from the HTTP_HOST
        $host = preg_replace('/^www\./i', '', $_SERVER['HTTP_HOST']);
        if(preg_match('/https?:\/\/(?:www\.)?' . $host . '/i', $src)) { //check if internal
            //is it a request for directory wp-content?
            if(preg_match('/\/wp-content\//', $src)) {
                $src_parts = explode('/wp-content/', $src);
                $src = '/wp-content/' . $src_parts[1];
            }
            //is it a request for /files/ virtual directory
            else if(preg_match('/\/files\//', $src)) {
                $src_parts = explode('/files/', $src);
                $src = '/blogs.dir/' . get_current_blog_id() . '/files/' . $src_parts[1];
            }
        }
    }
    return $timthumb_url . '?src=' . urlencode($src) . '&amp;h=' . $h . '&amp;w=' . $w . '&amp;zc=1';
}

/**
* crete a hotel link with alredy passed parameters
* @param hotel id
* @return url
*/
function create_hotel_link($hotel_id){
	  $new_url = '';
	  foreach($_GET as $getkey => $getvalue){
	    $new_url .= $getkey.'='.$getvalue.'&';
	  }
	  $new_url = site_url('hotel/?'.$new_url.'hotel_id='.$hotel_id);
	  return $new_url;
}

/**
* get specific hotel detail
* @param hotel id
* @return array
*/
function get_hotel_details($hotel_id){
	global $wpdb,
	$hotels_view;

	$sql = '';
	$sql .= "
	  SELECT *
	  FROM `$hotels_view`
	  WHERE `hotel_id`=$hotel_id
	";
	//echo $sql;
	$hotel = $wpdb->get_results($sql);
	return $hotel[0];
}


/**
* get hotel images
* @param hotel id
* @return array
*/
function get_hotel_images($hotel_id){
	global $wpdb,
	$hotels_images_tbl;
	
	$images = $wpdb->get_results("
		SELECT * 
		FROM `$hotels_images_tbl`
		WHERE `hotel_id`=$hotel_id
	");
	return $images;
}


/**
* get hotel facilities
* @param hotel id
* @return array
*/
function get_hotel_facilities($hotel_id,$group_code,$limit=''){
	global $wpdb,
	$facilities_tbl,
	$hotels_facilities_tbl;
	
	$sql = "";
	$sql = "SELECT $facilities_tbl.* 
			FROM `$facilities_tbl`,`$hotels_facilities_tbl`
			WHERE 
			`$hotels_facilities_tbl`.`facilityCode`=`$facilities_tbl`.`code` AND
			`$hotels_facilities_tbl`.`facilityGroupCode`=`$facilities_tbl`.`facilityGroupCode` AND
			`$hotels_facilities_tbl`.`facilityGroupCode`=$group_code AND
			`$hotels_facilities_tbl`.`hotel_id`=$hotel_id";

	if(!empty($limit)){
		$sql .= " LIMIT $limit";
	}

	$facilities = $wpdb->get_results($sql);

	return $facilities;
}

/**
* get hotel terminals
* @param hotel id
* @return array
*/
function get_hotel_terminals($hotel_id){
	global $wpdb,
	$terminals_tbl,
	$hotels_terminals_tbl;
	
	$terminals = $wpdb->get_results("
		SELECT 
			`$terminals_tbl`.`name`,
			`$terminals_tbl`.`description` AS `type`,
			`$hotels_terminals_tbl`.`distance` 
		FROM `$terminals_tbl`,`$hotels_terminals_tbl`
		WHERE 
		`$hotels_terminals_tbl`.`terminalCode`=`$terminals_tbl`.`code` AND
		`$hotels_terminals_tbl`.`hotel_id`=$hotel_id
	");
	

	return $terminals;
}

/**
* get hotel points of interests
* @param hotel id
* @return array
*/
function get_hotel_poi($hotel_id){
	global $wpdb,
	$hotels_interest_points_tbl;
	
	$interests = $wpdb->get_results("
		SELECT 
			`$hotels_interest_points_tbl`.`poiName`,
			`$hotels_interest_points_tbl`.`distance` 
		FROM `$hotels_interest_points_tbl`
		WHERE 
		`$hotels_interest_points_tbl`.`hotel_id`=$hotel_id
	");
	
	return $interests;
}


/**
* get hotel room details
* @param hotel id
* @return array
*/
function get_hotel_rooms($hotel_id){
	global $wpdb,
	$hotels_rooms_tbl,
	$hotels_rooms_stays_tbl;
	
	$rooms = $wpdb->get_results("
		SELECT 
			`$hotels_interest_points_tbl`.`poiName`,
			`$hotels_interest_points_tbl`.`distance` 
		FROM `$hotels_interest_points_tbl`
		WHERE 
		`$hotels_interest_points_tbl`.`hotel_id`=$hotel_id
	");
	
	return $interests;
}


//search hotels
function create_hotel_view(){

	global $wpdb,
	$accommodation_tbl,
	$facilities_tbl,
	$destinations_tbl,
	$hotels_tbl,
	$countries_tbl,
	$hotels_terminals_tbl,
	$hotels_facilities_tbl,
	$categories_tbl,
	$chains_tbl;

	$sql = "CREATE OR REPLACE VIEW `wpdj_hotels_view` as 
			  SELECT 
			    `$hotels_tbl`.hotel_id,
			    `$hotels_tbl`.code,
			    `$hotels_tbl`.name,
			    `$hotels_tbl`.description,
			    `$hotels_tbl`.address,
			    `$hotels_tbl`.city,
			    `$hotels_tbl`.postalCode,
			    `$hotels_tbl`.categoryCode,
			    `$hotels_tbl`.accommodationTypeCode,
			    `$hotels_tbl`.hotel_search,
			    `$hotels_tbl`.destination_search,
			    `$countries_tbl`.`name` AS `country_name`,
			    `$destinations_tbl`.`name` AS `destination_name`, 
			    `$accommodation_tbl`.`name` AS `accommodation_type`, 
			    `$categories_tbl`.`description` AS `category_description`,
			    `$chains_tbl`.`content` AS `chain_description`
			  FROM `$hotels_tbl`
			  LEFT JOIN `$countries_tbl`
			  ON `$hotels_tbl`.`countryCode` = `$countries_tbl`.`code`
			  LEFT JOIN `$destinations_tbl`
			  ON `$hotels_tbl`.`destinationCode` = `$destinations_tbl`.`code`
			  LEFT JOIN `$accommodation_tbl`
			  ON `$hotels_tbl`.`accommodationTypeCode` = `$accommodation_tbl`.`code`
			  LEFT JOIN `$categories_tbl`
			  ON `$hotels_tbl`.`categoryCode` = `$categories_tbl`.`code`
			  LEFT JOIN `$chains_tbl`
			  ON `$hotels_tbl`.`chainCode` = `$chains_tbl`.`code`";

	return $wpdb->query($sql);
}