<?php


//require_once (get_stylesheet_directory_uri() . '/include/short_code.php');

//include(locate_template('/include/short_code.php'));

// Enqueue Scrips and styles
function load_custom_wp_admin_style() {

	wp_enqueue_script( 'customjs', get_stylesheet_directory_uri().'/js/custom.js', array( 'jquery'), filemtime( get_stylesheet_directory() . '/js/custom.js') , true );
	
	wp_enqueue_script( 'bxslider', get_stylesheet_directory_uri().'/inc/bxslider/jquery.bxslider.min.js', array( 'jquery'), '1.0.0', true );
		
	//wp_enqueue_style( 'font-awesome', get_stylesheet_directory_uri().'/inc/font-awesome/css/font-awesome.min.css', array(), '1.0.0' );
	wp_enqueue_style( 'responsive', get_stylesheet_directory_uri().'/css/responsive.css', array('style_css'), filemtime( get_stylesheet_directory() . '/css/responsive.css') );
	
}

add_action( 'wp_enqueue_scripts', 'load_custom_wp_admin_style' );

// Create Post Type
add_action( 'init', 'create_posttype' );
function create_posttype() {
	
	register_post_type( 'excursii',
		array(
			'labels' => array(
				'name' => __( 'Excursii' ),
				'singular_name' => __( 'Excursie' )
			),
			'public' 			 => true,
			'has_archive'        => false,
			'query_var'          => true,
			'capability_type'    => 'post',
			'hierarchical'       => true,
			'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'page-attributes', 'custom-fields', 'revisions' )
		)
	);
	
	register_post_type( 'experiente',
		array(
			'labels' => array(
				'name' => __( 'Experiențe' ),
				'singular_name' => __( 'Experiență' )
			),
			'public' 			 => true,
			'has_archive'        => false,
			'query_var'          => true,
			'capability_type'    => 'post',
			'hierarchical'       => true,
			'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'page-attributes', 'custom-fields', 'revisions' )
		)
	);
	
		
	// taxonomyes
	register_taxonomy( 'destinatii', array('excursii','experiente'),  
		array(
			'hierarchical'      => true,
			'show_ui'           => true,
			'show_admin_column' => true,
			'query_var'         => true,
			//'rewrite'           => array( 'slug' => 'exc' ),
			'labels'            => array(
				'name'              => _x( 'Destinatii', 'theme' ),
				'singular_name'     => _x( 'Destinatie', 'theme' ),
			),
		)
	);
	
	register_taxonomy( 'status', 'excursii',  
		array(
			'hierarchical'      => true,
			'show_ui'           => true,
			'show_admin_column' => true,
			'query_var'         => true,
			'publicly_queryable'=> false,
			'rewrite'           => array( 'slug' => 'exc' ),
			'labels'            => array(
				'name'              => _x( 'Status', 'theme' ),
				'singular_name'     => _x( 'Status', 'theme' ),
			),
		)
	);
	

}

// Customize theme options
function theme_customize_register( $wp_customize ) {
	
	
	$wp_customize->add_setting( 'excursii_subscribe' ); 
	$wp_customize->add_control(
	    'excursii_subscribe',
	    array(
	        'label' => __( 'Excursii subscribe text', 'theme' ),
	        'section' => 'title_tagline',
	        'type' => 'textarea',
	    )
	);
	
    
}
add_action( 'customize_register', 'theme_customize_register' );


// Shortcodes

function shortcodeExcursieVariatii( $atts ) {
		
	remove_filter('the_content', 'my_formatter', 99);  
	
	/*$shortClass = '';
	$shortID = '';
	$shortCategory = '';
	$shortLink = '';
	$shortCarousel = '';
	$shortTitle = '';
	
	if(is_array($atts)){
		$shortClass = isset($atts['xclass']) ? $atts['xclass'] : '';
		$shortID = isset($atts['xid']) ? $atts['xid'] : '';
		$shortCategory = isset($atts['category']) ? $atts['category'] : ''; // ID sau Slug
		$shortLink = isset($atts['link']) ? $atts['link'] : ''; // child for first child page link or BLANK for direct page link
		$shortCarousel = isset($atts['carousel']) ? $atts['carousel'] : ''; // true for carousel
		$shortTitle = isset($atts['title']) ? $atts['title'] : ''; 
	}*/
	
	ob_start();
	include(locate_template('inc/shortcode-excursie-variatii.php'));
	return ob_get_clean();
	
	add_filter('the_content', 'my_formatter', 99);  
}
add_shortcode('exc_variatii', 'shortcodeExcursieVariatii');

function shortcodeExcursii( $atts ) {
		
	remove_filter('the_content', 'my_formatter', 99);  
	
	/*$shortClass = '';
	$shortID = '';
	$shortCategory = '';
	$shortLink = '';
	$shortCarousel = '';
	$shortTitle = '';
	
	if(is_array($atts)){
		$shortClass = isset($atts['xclass']) ? $atts['xclass'] : '';
		$shortID = isset($atts['xid']) ? $atts['xid'] : '';
		$shortCategory = isset($atts['category']) ? $atts['category'] : ''; // ID sau Slug
		$shortLink = isset($atts['link']) ? $atts['link'] : ''; // child for first child page link or BLANK for direct page link
		$shortCarousel = isset($atts['carousel']) ? $atts['carousel'] : ''; // true for carousel
		$shortTitle = isset($atts['title']) ? $atts['title'] : ''; 
	}*/
	
	ob_start();
	include(locate_template('inc/shortcode-excursii.php'));
	return ob_get_clean();
	
	add_filter('the_content', 'my_formatter', 99);  
}
add_shortcode('exc', 'shortcodeExcursii'); 

function shortcodeDestinatii( $atts ) {
		
	remove_filter('the_content', 'my_formatter', 99);  
	ob_start();
	include(locate_template('inc/shortcode-destinatii.php'));
	return ob_get_clean();
	
	add_filter('the_content', 'my_formatter', 99);  
}
add_shortcode('destinatii', 'shortcodeDestinatii'); 


// Comments template

If (!function_exists('cs_comment')) :

     /**

     * Template for comments and pingbacks.

     *

     * To override this walker in a child theme without modifying the comments template

     * simply create your own cs_comment(), and that function will be used instead.

     *

     * Used as a callback by wp_list_comments() for displaying the comments.

     *

     */

	function cs_comment( $comment, $args, $depth ) {

	$GLOBALS['comment'] = $comment;

	$args['reply_text'] = 'răspunde';

 	switch ( $comment->comment_type ) :

		case '' :

	?>

	<li  <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">

 		<div class="thumblist" id="comment-<?php comment_ID(); ?>">

        	<ul>

                <li>

                    <figure>

                        <a href="#"><?php echo get_avatar( $comment, 50 ); ?></a>

                    </figure>

                     <div class="text">

                      <header>
							
                            <?php printf( __( '%s', 'WeStand' ), sprintf( '<h5>%s</h5>', get_comment_author_link() ) ); ?>

                            <?php

                            	/* translators: 1: date, 2: time */

                                printf( __( '<time>%1$s</time>', 'WeStand' ), get_comment_date().' - '.get_comment_time()); ?>

                            <?php if ( $comment->comment_approved == '0' ) : ?>

                                <div class="comment-awaiting-moderation colr"><?php _e( 'Your comment is awaiting moderation.', 'WeStand' ); ?></div>

                            <?php endif; ?>

                      </header>

                      <?php comment_text(); ?>
                      
						<?php
						if(function_exists('like_counter_c')) { like_counter_c(''); }
						?>
						<?php
						if(function_exists('dislike_counter_c')) { dislike_counter_c(''); }
						?>
						
						<?php edit_comment_link( __( '(Edit)', 'WeStand' ), ' ' );?>

						<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>

                    </div>

                </li>

            </ul>

        </div>

     </li>

	<?php

		break;

		case 'pingback'  :

		case 'trackback' :

	?>

	<li class="post pingback">

		<p><?php comment_author_link(); ?><?php edit_comment_link( __( '(Edit)', 'WeStand' ), ' ' ); ?></p>

	<?php

		break;

		endswitch;

	}

 	endif;


// Custom excerpt function 
if ( ! function_exists( 'cs_get_the_excerpt' ) ) { 
	function cs_get_the_excerpt($limit,$readmore = '') {
	
		global $cs_theme_option;
	
		$get_the_excerpt = trim(preg_replace('/<a[^>]*>(.*)<\/a>/iU', '', get_the_excerpt()));
	
		echo substr($get_the_excerpt, 0, "$limit");
	
		if (strlen($get_the_excerpt) > "$limit") {
	
			if($readmore == "true"){
					
				global $post;
				if($post->post_type != 'discutii'){
				
					echo '... <a href="' . get_permalink() . '" class="cs-read-more colr">' .$cs_theme_option['trans_read_more'] . '</a>';
				}
			}
		}
	}

}

// display post page title
if (!function_exists('cs_post_page_title')) {

    function cs_post_page_title() {

        if (is_author()) {

            global $author;

            $userdata = get_userdata($author);

            echo __('Arhiva autorului', 'WeStand') . ": " . $userdata->display_name;
        } elseif (is_tag() || is_tax('event-tag') || is_tax('cs_cause-tag')) {

            echo __('Arhiva tag', 'WeStand') . ": " . single_cat_title('', false);
        } elseif (is_category() || is_tax('event-category') || is_tax('cs_cause-category')) {

            echo __('Arhiva categorie', 'WeStand') . ": " . single_cat_title('', false);
        } elseif (is_search()) {

            printf(__('Rezultatele căutării %1$s %2$s', 'WeStand'), ': ', '<span>' . get_search_query() . '</span>');
        } elseif (is_day()) {

            printf(__('Daily Archives: %s', 'WeStand'), '<span>' . get_the_date() . '</span>');
        } elseif (is_month()) {

            printf(__('Monthly Archives: %s', 'WeStand'), '<span>' . get_the_date(_x('F Y', 'monthly archives date format', 'WeStand')) . '</span>');
        } elseif (is_year()) {

            printf(__('Yearly Archives: %s', 'WeStand'), '<span>' . get_the_date(_x('Y', 'yearly archives date format', 'WeStand')) . '</span>');
        } elseif (is_404()) {

            _e('Error 404', 'WeStand');
		} elseif (is_post_type_archive()) {

            printf(post_type_archive_title());
        } elseif (!is_page()) {

            _e('Arhiva', 'WeStand');
        }
    }

}

// Home slider

if ( ! function_exists( 'cs_post_slider' ) ) {

	function cs_post_slider($cs_slider_blog_cat,$blog_no_posts){
		global $post, $cs_theme_option;
		if (empty($_GET['page_id_all'])) $_GET['page_id_all'] = 1;
		$args = array('posts_per_page' => "$blog_no_posts", 'paged' => $_GET['page_id_all'], /*'category_name' => "$cs_slider_blog_cat",*/ 'post_type' => 'home-slider', 'order' => "DESC");
		
		$custom_query = new WP_Query($args);
		$post_count = $custom_query->post_count;
		if($custom_query->have_posts()):
		
		$slider_pagination = array();
				echo '<div id="sliderbanner">';
					echo '<div class="cycle-slideshow" 
								data-cycle-fx=fade
								data-cycle-timeout=7000
								data-cycle-auto-height=container
								data-cycle-slides="article"
								
								data-cycle-random=false
								data-cycle-pager="#banner-pager"
								data-cycle-pager-template="">';
							while ($custom_query->have_posts()) : $custom_query->the_post();
								$image_url_full = cs_get_post_img_src($post->ID, '' ,'');
								if($image_url_full <> ''){
								$slider_pagination[] = get_the_title();
								?>
									<article class="<?php echo $post->ID; ?>" <?php if($image_url_full <> ''){?>style="background-image: url('<?php echo $image_url_full;?>')"<?php }?>>
                                               <div class="caption">
                                                	<h2><?php the_title();?></h2>
                                               		<p><?php  the_excerpt();  //cs_get_the_excerpt('113',false);?></p>
                                                	<a href="<?php the_field('slider_link'); ?>" target="_blank" class="btn cs-bgcolrhvr"><?php if($cs_theme_option['trans_switcher'] == "on"){ _e('Continue Reading','WeStand');}else{ echo $cs_theme_option['trans_read_more']; }?></a>
                                               </div> 
                                    </article>
                                <?php
								}
							endwhile;
				echo '</div>';
			echo '</div>';
			
			
			if(isset($cs_theme_option['show_slider_pagination']) && $cs_theme_option['show_slider_pagination'] == 'on'){
				$pagination_no = 0;
				echo '<div id="sliderpagination">
				<div class="container">
					<ul id="banner-pager">';
					
							
								foreach($slider_pagination as $slider){
									$pagination_no++;
									$slider_title = substr($slider,0,30); if ( strlen($slider) > 30) $slider_title .= "...";
									echo '<li>
											<div class="pager-desc">
												<span class="cs-number">'.str_pad($pagination_no, 2, "0", STR_PAD_LEFT).'</span>
												<span class="cs-desc">'.$slider_title.'</span>
											</div>
										</li>';
								}
								
							
					echo '</ul>
				</div>
			</div>';
			}
			cs_cycleslider_script();
		endif;
		wp_reset_query();
		
	}
}

// search varibales start

function cs_get_search_results2($query) {

    if (!is_admin() && ( $query->is_search)) {

        $query->set('post_type', array('post', 'page'/*, 'subiect', 'discutii'*/));

        remove_action('pre_get_posts', 'cs_get_search_results');
    }
}
add_action( 'wp_loaded', 'overwrite_search_results' );
function overwrite_search_results(){
	add_action('pre_get_posts', 'cs_get_search_results2');
}


// Languages
function my_child_theme_setup() {
	load_child_theme_textdomain( 'WeStand', get_stylesheet_directory() . '/languages' );
}
add_action( 'after_setup_theme', 'my_child_theme_setup' );


// Page Sub header title and subtitle //

function get_subheader_title_child() {

    global $post, $wp_query, $cs_theme_option;

    $get_title = '';
    $header_banner_style = '';
    if (is_page() || is_single()) {
        if (is_page()) {
            $cs_xmlObject = cs_meta_page('cs_page_builder');
            $header_banner_style = $cs_xmlObject->header_banner_style;
            if (isset($cs_xmlObject)) {
                $subtitle = $cs_xmlObject->page_sub_title;
            }
            $get_title = '<h1 class="cs-page-title">' . get_the_title() . '</h1>';
        } elseif (is_single()) {
            $post_type = get_post_type($post->ID);
            if ($post_type == "events") {
                $post_type = "cs_event_meta";
            } else if ($post_type == "cs_cause") {
                $post_type = "cs_cause_meta";
            } else if ($post_type == "teams") {
                $post_type = "cs_team";
            } else {
                $post_type = "post";
            }
            $post_xml = get_post_meta($post->ID, $post_type, true);
            if ($post_xml <> "") {
                $cs_xmlObject = new SimpleXMLElement($post_xml);
            }
            $header_banner_style = $cs_xmlObject->header_banner_style;
            if (isset($cs_xmlObject) && $cs_xmlObject->page_sub_title <> "") {
                $subtitle = $cs_xmlObject->page_sub_title;
            }
            $get_title = '<h1 class="cs-page-title">' . get_the_title() . '</h1>';
        }

        echo $get_title;

        if (isset($header_banner_style) && $header_banner_style == 'default_header') {
            if (isset($cs_theme_option['page_sub_title_default']))
                $subtitle = $cs_theme_option['page_sub_title_default'];
            if (isset($subtitle) && $subtitle <> '') {
                echo '<p>' . $subtitle . '</p>';
            }
        } else {
            if (isset($subtitle) && $subtitle <> '') {
                echo '<p>' . $subtitle . '</p>';
            }
        }
    } elseif(is_tax()) {
    	echo '<h1 class="cs-page-title">'.get_queried_object()->name.'</h1>';
	} else {
        if (isset($cs_theme_option['page_sub_title']) && $cs_theme_option['page_sub_title'] <> '') {
            $page_sub_title = $cs_theme_option['page_sub_title'];
        } else {
            $page_sub_title = '';
        }
        ?>
        <h1 class="cs-page-title"><?php cs_post_page_title(); ?></h1>
        <?php
        if (isset($page_sub_title) && $page_sub_title <> '') {
            echo '<p>' . $page_sub_title . '</p>';
        }
    }
}

//Ccustom Header Styles 

if ( ! function_exists( 'cs_get_header' ) ) { 
	function cs_get_header() {
		global $post, $cs_theme_option;
	?>
		<!-- Header Start -->
    <header id="header">
	    <div class="header-top">
	        <div class="container">
	        	<!-- Left Header Start -->
	        	<div class="left-header">
	            	<div class="logo"><?php cs_logo();?></div>
	                <!-- Navigation -->
	                <nav class="navigation">
	                	<a class="cs-click-menu"><i class="fa fa-bars"></i></a>                                                            
	                    <?php cs_navigation('main-menu'); ?>
	                </nav>
	                <!-- Navigation Close -->
	            </div>
	            <!-- Left Header End -->
	            <div class="right-header">
	            <?php /*
	            <button id="search-header-button" class="btn cs-bgcolr search-btn" onclick="searchFocus()" type="button" data-toggle="collapse" data-target="#search-form" aria-expanded="true" aria-controls="search-form">
					<i class="fa fa-search" aria-hidden="true"></i> Căutare
				</button>
	            <script>
	            	
	            	function searchFocus(){
	            		setTimeout(function(){
            				jQuery("#search-form input[type=text]").focus();
            			}, 300);
	            	}
	            </script>
	            */ ?>
	            <?php /*if(isset($cs_theme_option['header_donation_button']) && $cs_theme_option['header_donation_button'] == 'on'){?>
	            <a href="#" class="btn cs-bgcolr" data-toggle="modal" data-target="#myModal"><?php if($cs_theme_option['trans_switcher'] == "on"){ _e('Support us','WeStand');}else{ echo $cs_theme_option['donation_btn_title']; } ?></a>
	            <?php }?>
	            <?php if ( function_exists('icl_object_id') ) {?>
	                    <div class="language-sec">
	                        <!-- Wp Language Start -->
	                         <?php 
	                         if(isset($cs_theme_option['header_languages'])){
	                             if(isset($cs_theme_option['header_languages']) && $cs_theme_option['header_languages'] == 'on'){
	                                do_action('icl_language_selector');
	                             }
	                         }
	                        ?>
	                    </div>
	                  <?php 
					}
					if ( function_exists( 'is_woocommerce' ) ){
						if(!isset($cs_theme_option['header_cart'])){ $cs_theme_option['header_cart'] = '';}
	
						if($cs_theme_option['header_cart'] == 'on'){ cs_woocommerce_header_cart(); }
					}*/
					?>
	            </div>
	            
	        </div>
        </div>
        <div id="search-form" class="collapse" >
			<div class="container">
				<div class="widget_search"><?php get_search_form(); ?> </div>
			</div>
		</div>
    </header>
    
	<!-- Header Close -->
	<?php
	}
}

//Services Shortcode
function cs_shortcode_pb_services($atts, $content = "") {
	
	
    $content = str_replace("[service-item", "<service-item", $content);
    $content = str_replace("[/service-item", "</service-item", $content);
    $content = str_replace("[content", "<content", $content);
    $content = str_replace("[/content", "</content", $content);
	$content = str_replace(']', ">", $content);
    $content = str_replace("<br />", "", $content);
    $content = str_replace('&nbsp;=""', "", $content);
    $content = str_replace("<p>", "", $content);
    $content = str_replace("</p>", "", $content);
    $content = "<services>" . $content . "</services>";
    
	$html = "";
	$content = htmlspecialchars(stripslashes($content));
	
	$content = str_replace('&', '', $content);
	
	$content = str_replace(array('quot;', 'amp;#8221;', 'amp;#8243;', 'lt;', 'gt;'), array('"', '"', '"', '<', '>'), $content);
	
    $cs_xmlObject = simplexml_load_string($content);
    $services_count = 0;

    foreach ($cs_xmlObject as $cs_node) {
		$services_count++;
        if (!isset($cs_node["icon"])){ $cs_node["icon"] = '';}
		if (!isset($cs_node["numbers"])){ $cs_node["numbers"] = '';}
        if (!isset($cs_node["title"])){ $cs_node["title"] = '';}
        if (!isset($cs_node["link"])){ $cs_node["link"] = '#';}
		
		$item_f_class = "";
		if($services_count == 4){
			$item_f_class = " listitem4";
		}
        
		$html .= '<article class="service-v2'.$item_f_class.'">';
			if($cs_node["icon"] <> ""){
				$html .= '<figure><i class="fa '.$cs_node["icon"].'"></i></figure>';
			}
			if($cs_node["numbers"] <> ""){
				$html .= '<h5 class="cs-time-counter" data-from="0" data-to="'.$cs_node["numbers"].'" data-speed="'.$cs_node["numbers"].'"></h5>';
			}
			
			if($cs_node["title"] <> ""){
				if($cs_node["link"] == '#'){
					$html .= '<span><h5>'.$cs_node["title"].'</h5></span>';
				}else{
					$html .= '<a href="'.$cs_node["link"].'" target="_blank"><h5>'.$cs_node["title"].'</h5></a>';
				}
			}
			$html .= '<p>' . $cs_node->content . '</p>';
		$html .= '</article>';
    }
    $html = '<div class="services">' . $html . '</div>';

    return do_shortcode($html) . '<div class="clear"></div>';
	
}
add_shortcode('services', 'cs_shortcode_pb_services');
//Services Shortcode end


add_action('init', 'remove_plugin_image_sizes');
function remove_plugin_image_sizes() {
	remove_image_size('cs_media_1');
	remove_image_size('cs_media_2');
	remove_image_size('cs_media_3');
	remove_image_size('cs_media_4');
	remove_image_size('cs_media_5');
	remove_image_size('cs_media_6');
	remove_image_size('cs_media_7');
	remove_image_size('cs_media_8');
}


function acf_update_term_meta($value, $post_id, $field) {
	$term_id = intval(filter_var($post_id, FILTER_SANITIZE_NUMBER_INT));
	if($term_id > 0)
		update_term_meta($term_id, $field['name'], $value);
	return $value;
}
add_filter('acf/update_value/name=destinatie_ascunde', 'acf_update_term_meta', 10, 3);

function acf_load_term_meta($value, $post_id, $field) {
	$term_id = intval(filter_var($post_id, FILTER_SANITIZE_NUMBER_INT));
	if($term_id > 0)
		$value = get_term_meta($term_id, $field['name'], true);
	return $value;
}
add_filter('acf/load_value/name=destinatie_ascunde', 'acf_load_term_meta', 10, 3);