<?php
#add_filter( 'x_redirect_by', '__return_false' );
if (!defined('ABSPATH')) die();

function ds_ct_enqueue_parent() { 
    wp_enqueue_style( 'parent-style', get_stylesheet_directory_uri() . '/style.css' ); 
}

function ds_ct_loadjs() {
	wp_enqueue_script( 'ds-theme-script', get_stylesheet_directory_uri() . '/ds-script.js',
        array( 'jquery' )
    );
}

add_action( 'wp_enqueue_scripts', 'ds_ct_enqueue_parent' );
add_action( 'wp_enqueue_scripts', 'ds_ct_loadjs' );


/*Add library items with shortcodes f*/

function showlibraryitem_shortcode($moduleid) {
extract(shortcode_atts(array('id' =>'*'),$moduleid)); 
return do_shortcode('[et_pb_section global_module="'.$id.'"][/et_pb_section]');
}
add_shortcode('showlibraryitem', 'showlibraryitem_shortcode');
//include('login-editor.php');

/* Criando uma area de widgets */
function widgets_novos_widgets_init() {
	register_sidebar( array(
		'name' => 'Newsletter Footer Artigos',
		'id' => 'campo-newsletter-pre-footer',
		'before_widget' => '<div>',
		'after_widget' => '</div>',
		'before_title' => '<h2>',
		'after_title' => '</h2>',
	) );
}
add_action( 'widgets_init', 'widgets_novos_widgets_init' );



/* formatanto o texto do resumo */

function get_excerpt(){
	$excerpt = get_the_content();
	$excerpt = preg_replace(" (\[.*?\])",'',$excerpt);
	$excerpt = strip_shortcodes($excerpt);
	$excerpt = strip_tags($excerpt);
	$excerpt = substr($excerpt, 0, 242);
	$excerpt = substr($excerpt, 0, strripos($excerpt, " "));
	$excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt));
	return $excerpt;
}

function ll_related_posts() {

	$cats = get_the_category($post->ID);
	if ( $cats[0]->cat_ID == 3273 ) { // id da categoria
	       unset($cats[0]);
	    }
	$cats = array_values($cats);
	

	$parent = get_category($cats[0]->category_parent);
	if (is_wp_error($parent)){
		$cat = get_category($cats[0]);
	}else{
		$cat = $parent;
	}

	$current_page_ids = array( get_the_ID() );

	$args = array(
		'post__not_in' => $current_page_ids,
		'posts_per_page' => 3,
		'category_name' => $cat->name,
		'ignore_sticky_posts' => 'true'
	);

	$the_query = new WP_Query( $args );

	while ( $the_query->have_posts() ) : $the_query->the_post();
?>

<div class="column col-4-custom row-<?php echo $cat->slug; ?>">

	<article class="et_pb_post">

		<?php if ( has_post_thumbnail() ) { ?> 
			<a href="<?php the_permalink(); ?>" class="entry-featured-image-url">
				<?php the_post_thumbnail( 'related-post' );?>
			</a>
		<?php } else { ?>
			<a href="<?php the_permalink(); ?>" class="entry-featured-image-url">
				<img src="<?php echo get_home_url()?>/img_fake.jpg" />
			</a>
		<?php } ?>

		<a href="<?php echo get_home_url() . "/" .$cat->slug;?>" style="background-color: <?php echo $cat->description; ?> ;" class="btn-categoria <?php echo $cat->slug; ?>">
			<?php echo $cat->name; ?>
		</a>

		<h3 class="entry-title">
			<a href="<?php the_permalink(); ?>">
				<?php the_title();?>
			</a>
		</h3>
		
		<div class="post-content">
			<?php 
			echo get_excerpt() . "...";
			?>
			<a href="<?php the_permalink(); ?>" class="more-link">ler mais</a>
		</div>

	</article>
</div>

<?php
		
	endwhile;

	wp_reset_postdata();
}

/*criando campo de banners CTA*/

function create_form_custom_field($post) {

	$utm_campaign_blog = get_post_meta($post->ID, 'utm_campaign_blog', true);
	
	$img_fundo_cta1 = get_post_meta($post->ID, 'img_fundo_cta1', true);
	$titulo_cta1 = get_post_meta($post->ID, 'titulo_cta1', true);
	$texto_cta1 = get_post_meta($post->ID, 'texto_cta1', true);
	$btn_cta1 = get_post_meta($post->ID, 'btn_cta1', true);
	$link_cta1 = get_post_meta($post->ID, 'link_cta1', true);

	$img_fundo_cta2 = get_post_meta($post->ID, 'img_fundo_cta2', true);
	$titulo_cta2 = get_post_meta($post->ID, 'titulo_cta2', true);
	$texto_cta2 = get_post_meta($post->ID, 'texto_cta2', true);
	$btn_cta2 = get_post_meta($post->ID, 'btn_cta2', true);
	$link_cta2 = get_post_meta($post->ID, 'link_cta2', true);

	$img_fundo_cta3 = get_post_meta($post->ID, 'img_fundo_cta3', true);
	$titulo_cta3 = get_post_meta($post->ID, 'titulo_cta3', true);
	$texto_cta3 = get_post_meta($post->ID, 'texto_cta3', true);
	
	$html = '<label>UTM CAMPAIGN DO POST: </label>';
	$html .= '<input type="text" name="utm_campaign_blog" value="'.$utm_campaign_blog.'" style="width:100%; height: 40px; padding: 15px;" /><br><br>';
	$html .= '<br><strong style="font-size:16px;">- Banner com texto a direita</strong><br><br>';
    $html .= '<label>Imagem de fundo: </label>';
	$html .= '<input type="text" name="img_fundo_cta1" placeholder="Ex: '. get_home_url().'/wp-content/uploads/2018/09/imagem_fundo.jpg" value="'.$img_fundo_cta1.'" style="width:100%; height: 40px; padding: 15px;" />';
	$html .= '<em>Para pegar o endereço da imagem, <a href="' . get_home_url() . '/wp/wp-admin/upload.php" target="blank">clique aqui!</a></em><br><br>';
	$html .= '<label>Título: </label>';
	$html .= '<input type="text" name="titulo_cta1" value="'.$titulo_cta1.'" style="width:100%; height: 40px; padding: 15px;" /><br><br>';
	$html .= '<label>Texto: </label>';
	$html .= '<textarea name="texto_cta1" style="width:100%; height: 100px; padding: 15px;" />'.$texto_cta1.'</textarea><br><br>';
	$html .= '<label>Texto do botão: </label>';
	$html .= '<input type="text" name="btn_cta1" value="'.$btn_cta1.'" style="width:100%; height: 40px; padding: 15px;" /><br><br>';
	$html .= '<label>Link do botão: </label>';
	$html .= '<input type="text" name="link_cta1" value="'.$link_cta1.'" style="width:100%; height: 40px; padding: 15px;" />';
	$html .= '<hr>';
	
	$html .= '<br><br><strong style="font-size:16px;">- Banner com texto a esquerda</strong><br><br>';
    $html .= '<label>Imagem de fundo: </label>';
	$html .= '<input type="text" name="img_fundo_cta2" placeholder="Ex: '. get_home_url().'/wp-content/uploads/2018/09/imagem_fundo.jpg" value="'.$img_fundo_cta2.'" style="width:100%; height: 40px; padding: 15px;" />';
	$html .= '<em>Para pegar o endereço da imagem, <a href="' . get_home_url() . '/wp/wp-admin/upload.php" target="blank">clique aqui!</a></em><br><br>';
	$html .= '<label>Título: </label>';
	$html .= '<input type="text" name="titulo_cta2" value="'.$titulo_cta2.'" style="width:100%; height: 40px; padding: 15px;" /><br><br>';
	$html .= '<label>Texto: </label>';
	$html .= '<textarea name="texto_cta2"  style="width:100%; height: 100px; padding: 15px;" />'.$texto_cta2.'</textarea><br><br>';
	$html .= '<label>Texto do botão: </label>';
	$html .= '<input type="text" name="btn_cta2" value="'.$btn_cta2.'" style="width:100%; height: 40px; padding: 15px;" /><br><br>';
	$html .= '<label>Link do botão: </label>';
	$html .= '<input type="text" name="link_cta2" value="'.$link_cta2.'" style="width:100%; height: 40px; padding: 15px;" />';
	$html .= '<hr>';
	
	$html .= '<br><br><strong style="font-size:16px;">- Banner com formulário de captura de e-mails</strong><br><br>';
    $html .= '<label>Imagem de fundo: </label>';
	$html .= '<input type="text" name="img_fundo_cta3" placeholder="Ex: '. get_home_url().'/wp-content/uploads/2018/09/imagem_fundo.jpg" value="'.$img_fundo_cta3.'" style="width:100%; height: 40px; padding: 15px;" />';
	$html .= '<em>Para pegar o endereço da imagem, <a href="' . get_home_url() . '/wp/wp-admin/upload.php" target="blank">clique aqui!</a></em><br><br>';
	$html .= '<label>Título: </label>';
	$html .= '<input type="text" name="titulo_cta3" value="'.$titulo_cta3.'" style="width:100%; height: 40px; padding: 15px;" /><br><br>';
	$html .= '<label>Texto: </label>';
	$html .= '<textarea name="texto_cta3"  style="width:100%; height: 100px; padding: 15px;" />'.$texto_cta3.'</textarea>';
	

    echo $html;
}

function add_custom_meta_box() {
    add_meta_box(
            'custom-field-code',
            'Banners Call To Action',
            'create_form_custom_field',
            'post'
        );
}

add_action( 'add_meta_boxes', 'add_custom_meta_box');

function save_form_custom_field($post_id) {

	if( isset($_POST['utm_campaign_blog'] ) ) {
        update_post_meta( $post_id, 'utm_campaign_blog', sanitize_text_field( $_POST['utm_campaign_blog'] ) );
	}
	
	
    if( isset($_POST['img_fundo_cta1'] ) ) {
        update_post_meta( $post_id, 'img_fundo_cta1', sanitize_text_field( $_POST['img_fundo_cta1'] ) );
	}
	if( isset($_POST['titulo_cta1'] ) ) {
        update_post_meta( $post_id, 'titulo_cta1', sanitize_text_field( $_POST['titulo_cta1'] ) );
	}
	if( isset($_POST['texto_cta1'] ) ) {
        update_post_meta( $post_id, 'texto_cta1', sanitize_text_field( $_POST['texto_cta1'] ) );
	}
	if( isset($_POST['btn_cta1'] ) ) {
        update_post_meta( $post_id, 'btn_cta1', sanitize_text_field( $_POST['btn_cta1'] ) );
	}
	if( isset($_POST['link_cta1'] ) ) {
        update_post_meta( $post_id, 'link_cta1', sanitize_text_field( $_POST['link_cta1'] ) );
	}


	if( isset($_POST['img_fundo_cta2'] ) ) {
        update_post_meta( $post_id, 'img_fundo_cta2', sanitize_text_field( $_POST['img_fundo_cta2'] ) );
	}
	if( isset($_POST['titulo_cta2'] ) ) {
        update_post_meta( $post_id, 'titulo_cta2', sanitize_text_field( $_POST['titulo_cta2'] ) );
	}
	if( isset($_POST['texto_cta2'] ) ) {
        update_post_meta( $post_id, 'texto_cta2', sanitize_text_field( $_POST['texto_cta2'] ) );
	}
	if( isset($_POST['btn_cta2'] ) ) {
        update_post_meta( $post_id, 'btn_cta2', sanitize_text_field( $_POST['btn_cta2'] ) );
	}
	if( isset($_POST['link_cta2'] ) ) {
        update_post_meta( $post_id, 'link_cta2', sanitize_text_field( $_POST['link_cta2'] ) );
	}


	if( isset($_POST['img_fundo_cta3'] ) ) {
        update_post_meta( $post_id, 'img_fundo_cta3', sanitize_text_field( $_POST['img_fundo_cta3'] ) );
	}
	if( isset($_POST['titulo_cta3'] ) ) {
        update_post_meta( $post_id, 'titulo_cta3', sanitize_text_field( $_POST['titulo_cta3'] ) );
	}
	if( isset($_POST['texto_cta3'] ) ) {
        update_post_meta( $post_id, 'texto_cta3', sanitize_text_field( $_POST['texto_cta3'] ) );
	}
}

add_action( 'save_post', 'save_form_custom_field');

/* shortcode para os artigos */

function ShotcodeBannerCTADireita($atts, $content=null){

	if($img_fundo_cta1 = get_post_meta(get_the_ID(), 'img_fundo_cta1', true)) :
		$cta_direita1 = $img_fundo_cta1;
	endif;
	if($titulo_cta1 = get_post_meta(get_the_ID(), 'titulo_cta1', true)) :
		$cta_direita2 = $titulo_cta1;
	endif;
	if($texto_cta1 = get_post_meta(get_the_ID(), 'texto_cta1', true)) :
		$cta_direita3 = $texto_cta1;
	endif;
	if($btn_cta1 = get_post_meta(get_the_ID(), 'btn_cta1', true)) :
		$cta_direita4 = $btn_cta1;
	endif;
	if($link_cta1 = get_post_meta(get_the_ID(), 'link_cta1', true)) :
		$cta_direita5 = $link_cta1;
	endif;

	return '<div class="linha_banner_cta" style="background-image: url('.$cta_direita1.');"><div class="linha_banner_email_cta"></div><div class="linha_banner_title_text text-cta-right"><h6>'.$cta_direita2.'</h6><p>'.$cta_direita3.'</p><a href="'.$cta_direita5.'" class="cta-post-link" target="blank">'.$cta_direita4.'</a></div></div>';
}

add_shortcode('BannerCTADireita', 'ShotcodeBannerCTADireita');


function ShotcodeBannerCTAEsquerda($atts, $content=null){
	
	if($img_fundo_cta2 = get_post_meta(get_the_ID(), 'img_fundo_cta2', true)) :
		$cta_esquerda1 = $img_fundo_cta2;
	endif;
	if($titulo_cta2 = get_post_meta(get_the_ID(), 'titulo_cta2', true)) :
		$cta_esquerda2 = $titulo_cta2;
	endif;
	if($texto_cta2 = get_post_meta(get_the_ID(), 'texto_cta2', true)) :
		$cta_esquerda3 = $texto_cta2;
	endif;
	if($btn_cta2 = get_post_meta(get_the_ID(), 'btn_cta2', true)) :
		$cta_esquerda4 = $btn_cta2;
	endif;
	if($link_cta2 = get_post_meta(get_the_ID(), 'link_cta2', true)) :
		$cta_esquerda5 = $link_cta2;
	endif;

	return '<div class="linha_banner_cta" style="background-image: url('.$cta_esquerda1.');"><div class="linha_banner_title_text text-cta-left"><h6>'.$cta_esquerda2.'</h6><p>'.$cta_esquerda3.'</p><a href="'.$cta_esquerda5.'" class="cta-post-link" target="blank">'.$cta_esquerda4.'</a></div><div class="linha_banner_email_cta"></div></div>';
}

add_shortcode('BannerCTAEsquerda', 'ShotcodeBannerCTAEsquerda');


function ShotcodeBannerCTAcomEmail($atts, $content=null){
	if($img_fundo_cta3 = get_post_meta(get_the_ID(), 'img_fundo_cta3', true)) :
		$cta_comEmail1 = $img_fundo_cta3;
	endif;
	if($titulo_cta3 = get_post_meta(get_the_ID(), 'titulo_cta3', true)) :
		$cta_comEmail2 = $titulo_cta3;
	endif;
	if($texto_cta3 = get_post_meta(get_the_ID(), 'texto_cta3', true)) :
		$cta_comEmail3 = $texto_cta3;
	endif;

	return '<div class="linha_banner_cta" style="background-image: url('.$cta_comEmail1.');"><div class="linha_banner_title_text"><h6>'.$cta_comEmail2.'</h6><p>'.$cta_comEmail3.'</p></div><div class="linha_banner_email_cta">' . do_shortcode('[contact-form-7 id="3083" title="form interno artigo"]'). '</div></div>';
}

add_shortcode('BannerCTAcomEmail', 'ShotcodeBannerCTAcomEmail');

//
// function CTAFaleComConsultor($atts, $content=null){
// 	return '<div class="cta-consultor"><div class="cta-consultor-header"><h6>Fale com um consultor</h6><p>Preencha o formulário abaixo e um dos nossos especialistas entrará em contato com você o mais breve possível</p></div><div class="cta-consultor-body">' . do_shortcode('[contact-form-7 id="17100" title="Fale com um consultor"]'). '</div></div>';
// }

// add_shortcode('CTAFaleComConsultor', 'CTAFaleComConsultor');

//CTA Fale com consultor - Banner
function CTAFaleComConsultor($atts, $content=null){
	$utm_cta = "blog-doity_426";
	if($utm_campaign_blog = get_post_meta(get_the_ID(), 'utm_campaign_blog', true)) :
		$utm_cta = $utm_campaign_blog;
	endif;
	return '<a href="https://materiais.doity.com.br/orcamento-organizadores?utm_source=blog_doity&utm_medium=cta_banner&utm_campaign='.$utm_cta.'" class="link" target="blank"><div class="linha_banner_cta consultor" id="consultor">
	<div class="linha_banner_title_text consultor_linha_title_text"><h6>Encontre as melhores soluções para a gestão do seu evento!</h6>
	<div class="linha_content_text">
	<div class="list">
	<span class="list__bullet"></span>
	<span class="list__item">Crie o site e comece a vender em 5 minutos</span>
	</div>
	<div class="list">
	<span class="list__bullet"></span>
	<span class="list__item">Mais de 300 mil eventos em 9 países</span>
	</div>
	<div class="list">
	<span class="list__bullet"></span>
	<span class="list__item">Mais de 22 milhões de inscrições</span>
	</div>
	</div><button class="cta-post-link" target="blank">Fale com um consultor</button></div><div class="linha_banner_email_cta consultor_linha_note"><img src="https://doity.com.br/blog/app/uploads/2020/04/banner_email.png" /></div></div></a>';
}

add_shortcode('CTAFaleComConsultor', 'CTAFaleComConsultor');

//CTA Doity Play - Banner
function CTAConsultorDoityPlay($atts, $content=null){
	$utm_cta = "blog-doity_426";
	if($utm_campaign_blog = get_post_meta(get_the_ID(), 'utm_campaign_blog', true)) :
		$utm_cta = $utm_campaign_blog;
	endif;
	return '<a href="https://doity.com.br/doity-play-ambiente-virtual-para-eventos-online?utm_source=blog_doity&utm_medium=banner&utm_campaing='.$utm_cta.'" class="link" target="blank">
	<div class="linha_banner_cta doityplay" id="doityplay">
	<div class="linha_banner_title_text doityplay_linha_title_text">
	<h6>Doity Play: o ambiente virtual perfeito para o seu evento online</h6>
	<div class="linha_content_text">
	<div class="list">
	<span class="list__bullet"></span>
	<span class="list__item">Link exclusivo para transmissão</span>
	</div>
	<div class="list">
	<span class="list__bullet"></span>
	<span class="list__item">Transmissão via mobile</span>
	</div>
	<div class="list">
	<span class="list__bullet"></span>
	<span class="list__item">Chat para interação dos participantes</span>
	</div>
	</div>
	<button class="cta-post-link" target="blank">TESTE GRÁTIS AGORA</button>
	</div>
	<div class="linha_banner_email_cta doityplay_linha_note">
	<img src="https://i.imgur.com/NylHzd6.png" /></div>
	</div>
	</a>';
}

add_shortcode('CTAConsultorDoityPlay', 'CTAConsultorDoityPlay');

//
add_action('rest_api_init', function () {
  register_rest_route( 'post-site/v1', '/(?P<category_id>\d+)',array(
                'methods'  => 'GET',
                'callback' => 'get_latest_posts_by_category'
      ));
});

function get_latest_posts_by_category($request) {

    $args = array(
            'category' => $request['category_id']
    );

    $posts = get_posts($args);	
    $array = array();

    foreach ($posts as &$value) {
	    $titulo = $value->post_title;
	    $image = wp_get_attachment_image_src(get_post_thumbnail_id($value->ID), 'slider_capa' )[0];
	    // $image = get_post_thumbnail_id($value->ID);
	    $link = get_permalink($value->ID);

	    array_push($array, array(
	    		"titulo" => $titulo,
	    		"image" => $image,
	    		"link" => $link
	    	)
	    );	
	}
    if (empty($posts)) {
    return new WP_Error( 'empty_category', 'Nao existe post nesta categoria', array('status' => 404) );

    }
    $response = new WP_REST_Response($array);
    $response->set_status(200);
    return $response;
}

function my_get_the_categories( $categories ) {
    if ( $categories[0]->term_id == '3273') { // id da categoria
	       unset($categories[0]);
	    }
    $categories = array_values($categories);
    return $categories;
}
add_filter( 'get_the_categories', 'my_get_the_categories' );


//FILTRO DE POSTS DA MESMA CATEGORIA. UTILIZADO NA SIDEBAR DA SINGLE.
function filtra_posts_relacionados_sidebar_single( $query ) {
	global $post;
	$category = get_the_category($post->ID);

	if (!is_array($category) || count($category) < 1) {
		return;
	}

	$query->set( 'category__in', array($category[0]->term_id) );
	$query->set( 'post__not_in', array($post->ID) );
}

add_action( 'elementor/query/relacionados-single', 'filtra_posts_relacionados_sidebar_single', 10, 2  );

?>
