<?php
/**
 * @package U99RedesSociales
 */
/*
Plugin Name: U99 Redes Sociales
Plugin URI: http://bgarcia.com.uy/
Description: Agregar entradas de las redes sociales
Version: 1.0.0
Author: Bernardo García
Author URI: http://bgarcia.com.uy/
License: GPLv2 or later
Text Domain: u99redessociales
*/


// Make sure we don't expose any info if called directly
if ( !function_exists( 'add_action' ) ) {
	echo 'Hi there!  I\'m just a plugin, not much I can do when called directly.';
	exit;
}

define( 'U99REDESSOCIALES__PLUGIN_DIR', plugin_dir_path( __FILE__ ) );


register_activation_hook( __FILE__, array( 'U99RedesSociales', 'plugin_activation' ) );
register_deactivation_hook( __FILE__, array( 'U99RedesSociales', 'plugin_deactivation' ) );

require_once( U99REDESSOCIALES__PLUGIN_DIR . 'class.u99.redessociales.php' );

add_action( 'init', array( 'U99RedesSociales', 'init' ) );
add_action( 'init', 'u99_crear_redes_sociales_post_type' );

function u99_crear_redes_sociales_post_type() {
		
	$labels = array(
		'name'               => _x( 'Enlaces Redes Sociales', 'post type general name', 'u99RedesSociales' ),
		'singular_name'      => _x( 'Enlace Red Social', 'post type singular name', 'u99RedesSociales' ),
		'menu_name'          => _x( 'Redes Sociales', 'admin menu', 'u99RedesSociales' ),
		'name_admin_bar'     => _x( 'Enlace Red Social', 'add new on admin bar', 'u99RedesSociales' ),
		'add_new'            => __( 'Agreagr', 'u99RedesSociales' ),
		'add_new_item'       => __( 'Agregar nuevo Enlace', 'u99RedesSociales' ),
		'new_item'           => __( 'Nuevo Enlace', 'u99RedesSociales' ),
		'edit_item'          => __( 'Editar Enlace', 'u99RedesSociales' ),
		'view_item'          => __( 'Ver enlace', 'u99RedesSociales' ),
		'all_items'          => __( 'Todos los Enlaces', 'u99RedesSociales' ),
		'search_items'       => __( 'Buscar Enlace', 'u99RedesSociales' ),
		'parent_item_colon'  => __( 'Enlace padre', 'u99RedesSociales' ),
		'not_found'          => __( 'No se encontraron Enlaces.', 'u99RedesSociales' ),
		'not_found_in_trash' => __( 'No hay Enlaces en la papelera.', 'u99RedesSociales' )
	);

	$args = array(
		'labels'             => $labels,
		'description'        => __( 'Enlazar links de las redes sociales.', 'u99RedesSociales' ),
		'public'             => true,
		'publicly_queryable' => true,
		'show_ui'            => true,
		'show_in_menu'       => true,
		'query_var'          => true,
		'rewrite'            => array( 'slug' => 'u99redessociales' ),
		'capability_type'    => 'post',
		'has_archive'        => true,
		'hierarchical'       => false,
		'menu_position'      => 10,
		'supports'           => array( 'title', 'excerpt' ),
		'taxonomies' => array('u99_redes_sociales_taxonomy')
	);
	register_post_type( 'u99RedesSociales', $args );
}

/*add_action( 'init', 'u99_add_redes_sociales_taxonomy', 0 );
function u99_add_redes_sociales_taxonomy() {
    register_taxonomy('u99_redes_sociales_taxonomy', null, array(
    'hierarchical' => true,
    'labels' => array(
        'name' => _x( 'Tipo de enlaces', 'taxonomy general name' ),
        'singular_name' => _x( 'Tipo de enlace', 'taxonomy singular name' ),
        'search_items' =>  __( 'Buscar tipo de enlace' ),
        'all_items' => __( 'Todos los tipos de enlaces' ),
        'parent_item' => __( 'Tipo de enlace padre' ),
        'parent_item_colon' => __( 'Tipo de enlace padre:' ),
        'edit_item' => __( 'Editar tipo de enlace' ),
        'update_item' => __( 'Actualizar tipo de enlace' ),
        'add_new_item' => __( 'Agregar nuevo tipo de enlace' ),
        'new_item_name' => __( 'Agregar nuevo nombre de tipo de enlace' ),
        'menu_name' => __( 'Tipos de enlaces' ),
    ),
    'rewrite' => array(
        'slug' => 'u99-tipo-enlace',
        'with_front' => false,
        'hierarchical' => true
    ),
    ));
}*/

add_filter( 'wp_insert_post_data' , 'u99RedesSociales_filter_post_data' , '99', 2 );

function u99RedesSociales_filter_post_data( $data , $postarr ) {
	//$data['post_title'] .= '_suffix';
	//print_r($postarr);
	//die();
	$post_id = $postarr['ID'];
	$meta_key = 'tipo';
	if($data['post_excerpt'] != ''){
		$excerpt = u99RedesSociales_limpiar_excerpt($data['post_excerpt']);
		$tipo = u99RedesSociales_get_tipo($excerpt);
		/*echo $excerpt;
		echo '<br>';
		echo $tipo;
		die();*/
		if($tipo != ''){
			$curr_value = get_post_meta( $post_id, $meta_key,true );
			/*print_r($curr_value);
			die();*/
			//check if old value exists and add if OLD NOT EXIST
			if($tipo && '' == $curr_value)
			{	
				add_post_meta( $post_id, $meta_key, $tipo, true );
			}
		
			//check if old value == new value and update if NEW NOT EQUAL
			elseif($tipo && $tipo != $curr_value)
			{
				update_post_meta( $post_id, $meta_key, $tipo);
			}
		
			//check if new value exists and delete if NEW NOT EXIST
			elseif('' == $tipo && $curr_value)
			{
				delete_post_meta( $post_id, $meta_key, $curr_value);
			}

		}
	}

    return $data;
}

function u99RedesSociales_limpiar_excerpt($excerpt){
	return $excerpt;
}

function u99RedesSociales_get_tipo($excerpt){
	$tipo = "";
	$soundcloud = strrpos($excerpt,'api.soundcloud.com');
	$spotify = strrpos($excerpt,'open.spotify.com');
	$facebook = strrpos($excerpt,'facebook.com');
	$youtube = strrpos($excerpt,'youtube.com');
	$youtubeBE = strrpos($excerpt,'youtu.be');
	$instagram = strrpos($excerpt,'instagram.com');
	$bandcamp = strrpos($excerpt,'bandcamp.com');
	$localMedia = strrpos($excerpt,get_site_url());

	if($soundcloud > -1){
		$tipo = 'soundcloud-';
		$soundcloudUser = strrpos($excerpt,'/users/');
		$soundcloudTrack = strrpos($excerpt,'/tracks/');
		if($soundcloudUser > -1){
			$tipo .= 'users';
		}elseif ($soundcloudTrack > -1) {
			$tipo .= 'tracks';
		}
	}elseif ($spotify > -1) {
		$tipo = 'spotify-';
		$spotifyPlaylist = strrpos($excerpt,'/playlist/');
		$spotifyTrack = strrpos($excerpt,'/track/');
		$spotifyAlbum = strrpos($excerpt,'/album/');
		if($spotifyPlaylist > -1){
			$tipo .= 'playlist';
		}elseif ($spotifyTrack > -1) {
			$tipo .= 'track';
		}elseif ($spotifyAlbum > -1) {
			$tipo .= 'album';
		}
	}elseif ($facebook > -1) {
		$tipo = 'facebook-';
		$facebookVideos = strrpos($excerpt,'/videos/');
		$facebookPhoto = strrpos($excerpt,'/photos/');
		if($facebookVideos > -1){
			$tipo .= 'videos';
		}elseif($facebookPhoto > -1){
			$tipo .= 'photos';
		}
	}elseif ($youtube > -1 || $youtubeBE > -1) {
		$tipo = 'youtube-';
		$youtubeList = strrpos($excerpt,'&list=');
		$youtubeVideo = strrpos($excerpt,'watch?v=');
		if($youtubeList > -1){
			$tipo .= 'list';
		}elseif($youtubeVideo > -1 || $youtubeBE > -1){
			$tipo .= 'video';
		}

	}elseif ($instagram > -1) {
		$tipo = 'instagram-';
		$instagramPost = strrpos($excerpt,'/p/');
		if($instagramPost > -1){
			$tipo .= 'post';
		}
	}elseif ($bandcamp > -1) {
		$tipo = 'bandcamp-';
		$instagramPost = strrpos($excerpt,'album');
		if($instagramPost > -1){
			$tipo .= 'album';
		}
	}elseif ($localMedia > -1) {
		$tipo = 'localmedia-';
		$extension = end(explode(".", $excerpt));
		switch ($extension) {
			case 'jpg':
			case 'png':
				$tipo .= 'img';
				break;
			default:
				# code...
				break;
		}
	}
	return $tipo;
}

function wporg_add_custom_box()
{
    $screens = ['u99RedesSociales'];
    foreach ($screens as $screen) {
        add_meta_box(
            'u99RedesSociales_previsualizar',           // Unique ID
            'Previsualizar',  // Box title
            'u99RedesSociales_previsualizar_html',  // Content callback, must be of type callable
            $screen                   // Post type
        );
    }
}
add_action('add_meta_boxes', 'wporg_add_custom_box');

function u99RedesSociales_previsualizar_html()
{
	$html  = '';
	$html .= '<div id="publishing-action">';
	$html .= '<input type="submit" accesskey="p" tabindex="5" value="Previsualizar" class="button-primary" id="publish" name="publish">';
	$html .= '</div>';
	echo $html;
	echo printContentIframe(get_the_ID(),get_the_excerpt(),null);
	$categories = get_post_meta( get_the_ID(), 'tipo',true );
	if(isset($categories)){
		if($categories==="facebook-videos"){
			echo '<div id="fb-root"></div>';
		}
	}
}

function printContentIframe($id,$my_excerpt,$altoIframe){
	//echo get_the_id();
	$categories = get_post_meta( $id, 'tipo',true );
	//print_r($categories);
	$return = "";
	if(isset($categories)){
		switch ($categories) {
			case 'facebook-videos':
				$return = '<div class="fb-video" data-href="'.$my_excerpt.'" data-width="auto" data-height="'.$altoIframe.'" data-show-text="true"></div>';
				break;
			case 'facebook-photos':
				$return = '<div class="fb-post" data-href="'.$my_excerpt.'" data-width="auto"  data-show-text="true"></div>';
				break;
			case 'youtube-video':
				$youtubeBE = strrpos($my_excerpt,'youtu.be');
				if($youtubeBE > -1){
					$my_excerpt = str_replace("https://youtu.be/","https://www.youtube.com/embed/",$my_excerpt);
				}else{
					$my_excerpt = str_replace("/watch?v=","/embed/",$my_excerpt);
				}
				$return = '<iframe width="100%" height="'.$altoIframe.'" src="'.$my_excerpt.'"
					frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
					allowfullscreen>
				</iframe>';
				break;
			case 'youtube-list':
				$my_excerpt = str_replace("/watch?v=","/embed/",$my_excerpt);
				$end = strrpos($my_excerpt,"&list=");
				$my_excerpt = substr($my_excerpt,$end+1);
				$my_excerpt = 'https://www.youtube.com/embed/videoseries?'.$my_excerpt;
				$return = '<iframe width="100%" height="'.$altoIframe.'" src="'.$my_excerpt.'"
					frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
					allowfullscreen>
				</iframe>';
				break;
			case 'spotify-track':
			case 'spotify-playlist':
			case 'spotify-album':
				$end = strrpos($my_excerpt,"?");
				$my_excerpt = substr($my_excerpt,0,$end);
				$my_excerpt = str_replace("https://open.spotify.com/","https://open.spotify.com/embed/",$my_excerpt);
				$return = '<iframe src="'.$my_excerpt.'"
					width="100%" height="'.$altoIframe.'px" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>';
				break;
			case 'soundcloud-users':
			case 'soundcloud-tracks':
				$return = '<iframe width="100%" height="'.$altoIframe.'px" scrolling="no" frameborder="no" allow="autoplay"
				src="https://w.soundcloud.com/player/?url='.$my_excerpt.'&color=%234caf50&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"></iframe>';
				break;	

			case 'instagram-post':
				$end = strrpos($my_excerpt,"?");
				$my_excerpt = substr($my_excerpt,0,$end);
				$return = '<blockquote class="instagram-media" data-instgrm-permalink="'.$my_excerpt.'"
				data-instgrm-version="12" style=" background:#FFF; border:0; border-radius:3px; box-shadow:0 0 1px 0 rgba(0,0,0,0.5),0 1px 10px 0 rgba(0,0,0,0.15); margin: 0px; max-width:100%; min-width:326px; padding:0; width:100%; width:-webkit-calc(100% - 0px); width:calc(100% - 0px);">
				</blockquote>';
				break;
			case 'bandcamp-album':
				$end = strrpos($my_excerpt,"album=");
				$my_excerpt = substr($my_excerpt,$end+6);
				$return = '<iframe class="bandcamp-album" style="border: 0; width: 100%; height: 100%;" src="https://bandcamp.com/EmbeddedPlayer/album='.$my_excerpt.'/size=large/bgcol=ffffff/linkcol=0687f5/artwork=small/transparent=true/" seamless></iframe>';
				break;
			case 'localmedia-img':
				
				break;
			default:
				# code...
				break;
		}
	}
	return $return;
}

function printContentIframeCalendario(){
	$facebookLink = get_option( 'u99_rs_facebook', true );
	return '<div class="fb-page" data-href="'.$facebookLink.'" data-tabs="events" data-width="500" data-height="" data-small-header="true" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="false">';
}

function printContentIframeNoticias($fuente,$altoIframe){
	if($altoIframe === null){
		$altoIframe = 550;
	}
	if($fuente === 'facebook'){
		return '<div class="fb-page" data-href="'.get_option( 'u99_rs_facebook', true ).'" data-tabs="timeline" data-width="550" data-height="'.$altoIframe.'" data-small-header="true" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="false"></div>';
		//return '<div class="fb-page" data-href="https://www.instagram.com/eldelagente/" data-tabs="timeline" data-width="550" data-height="'.$altoIframe.'" data-small-header="true" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="false"></div>';
	}elseif ($fuente === 'twitter') {
		return '<a class="twitter-timeline" data-height="550" data-theme="light" href="'.get_option( 'u99_rs_twitter', true ).'?ref_src=twsrc%5Etfw"></a>';
	}
	return '';
}

/*add_action('admin_init', 'u99RedesSocialesFacebookScript');
function u99RedesSocialesFacebookScript() {
	?>
	<script async defer crossorigin="anonymous" src="https://connect.facebook.net/es_LA/sdk.js#xfbml=1&version=v3.3"></script>
	<script async src="//www.instagram.com/embed.js"></script>
	<?php
}*/
function u99RedesSociales_admin_inline_js(){
	?>
	<script async defer crossorigin="anonymous" src="https://connect.facebook.net/es_LA/sdk.js#xfbml=1&version=v3.3"></script>
	<script async src="//www.instagram.com/embed.js"></script>
	<?php
}
add_action( 'admin_print_scripts', 'u99RedesSociales_admin_inline_js' );

/*add_action( 'post_submitbox_misc_actions', 'custom_button' );
function custom_button(){
        $html  = '<div id="major-publishing-actions" style="overflow:hidden">';
        $html .= '<div id="publishing-action">';
        $html .= '<input type="submit" accesskey="p" tabindex="5" value="Customize Me!" class="button-primary" id="custom" name="publish">';
        $html .= '</div>';
        $html .= '</div>';
        echo $html;
}*/


add_filter('admin_init', 'u99_redessociales_general_settings_register_fields_youtube');
 
function u99_redessociales_general_settings_register_fields_youtube()
{
	$redes = ['mail','bandcamp','spotify','youtube','facebook','instagram','twitter','soundcloud','contacto','logo','fondo'];
	foreach ($redes as $slug) {
		register_setting('general', 'u99_rs_'.$slug, 'esc_attr');
    	add_settings_field('u99_rs_'.$slug, '<label for="u99_rs_".$slug>'.__($slug , 'u99_rs_'.$slug ).'</label>' , 'u99_redessociales_general_settings_register_fields_general_html', 'general', 'default',$slug );
	}
    
}
 
function u99_redessociales_general_settings_register_fields_youtube_html()
{
    echo u99_redessociales_general_settings_register_fields_general_html('youtube');
}

function u99_redessociales_general_settings_register_fields_general_html($slug)
{
    $value = get_option( 'u99_rs_'.$slug, '' );
    echo  '<input type="text" id="u99_rs_'.$slug.'" name="u99_rs_'.$slug.'" value="' . $value . '" />';
}


/*$redes['youtube'] = 'fa-youtube-play';
				$redes['facebook'] = 'fa-facebook';
				$redes['instagram'] = 'fa-instagram';
				$redes['twitter'] = 'fa-twitter';
				$redes['soundcloud'] = 'fa-soundcloud';*/