<?php


//--------------------------- CRON ---------------------------------------------------------

$path_log="C:\\log\\cron_log.log";

add_action( 'init', 'ainia_setup_daily_schedule' );
function ainia_setup_daily_schedule() {
	global $wpdb;
	wp_clear_scheduled_hook ('ainia_iwatch40_daily_event' );
	if ( ! wp_next_scheduled( 'ainia_iwatch_ecoembes_daily_event' ) ) {
		wp_schedule_event( 1606435200, 'daily', 'ainia_iwatch_ecoembes_daily_event');
	}
}

add_action( 'ainia_iwatch_ecoembes_daily_event', 'ainia_daily_actions' );
function ainia_daily_actions() {
	//ainia_update_conceptos_seguimiento();
		error_log(print_r($date.' ********************* INICIO ACTUALIZACIÓN CONCEPTOS SEGUIMIENTO ****************************
					', TRUE),3,"C:\\log\\cron_log.log");
//	ainia_set_alertas();
		ainia_update_conceptos_personalizados();
		ainia_send_newsletter_conc_personalizados();
}

function ainia_update_conceptos_seguimiento (){
	$date = date('m/d/Y h:i:s a', time());
	error_log(print_r($date.' ********************* INICIO ACTUALIZACIÓN CONCEPTOS SEGUIMIENTO ****************************
					', TRUE),3,"C:\\log\\cron_log.log");
	$categorias =	$terms = get_terms( 'category', array(
								'orderby'    => 'count',
								'hide_empty' => 0
							) );
	
	foreach( $categorias as $categoria ) {
		
			error_log(print_r('-------   INICIO---- CATEGORÍA-- '.$categoria->name.'----
					', TRUE),3,"C:\\log\\cron_log.log");
	
		ainia_update_conceptos_seguimiento_por_categoria ($categoria);
		error_log(print_r('--------------------------------------------------------------
			', TRUE),3,"C:\\log\\cron_log.log");
	}
	
	$date2 = date('m/d/Y h:i:s a', time());
	error_log(print_r($date2.'********************* FIN ACTUALIZACIÓN CONCEPTOS SEGUIMIENTO ****************************
					', TRUE),3,"C:\\log\\cron_log.log");
}

function ainia_update_conceptos_seguimiento_por_categoria ($categoria){
	//error_log(print_r('------------------  ainia_update_conceptos_seguimiento_por_categoría -------------------
	//		', TRUE),3,"C:\\log\\cron_log.log");
	$conceptos_seguimiento= ainia_get_conceptos_seguimiento_por_categoria($categoria->term_id);
	

	foreach( $conceptos_seguimiento as $concepto ) {
		//echo '---categoría---'.$categoria->name;
		//error_log("---categoría---".$categoria->name,3,"/log/php_error.log");
		ainia_update_conceptos_seguimiento_por_post ($concepto,$categoria->term_id);
	
	}

}

function ainia_get_conceptos_seguimiento_por_categoria($categoria_ID){
	error_log(print_r('-- Recuperando los conceptos de seguimiento para la categoría con ID '.$categoria_ID.'--
			', TRUE),3,"C:\\log\\cron_log.log");
	global $wpdb;
	$conceptos=null;
	
	$query_str='select * from wp_term_relationships cat_conc_seg inner join wp_terms conc_seg on cat_conc_seg.object_id= conc_seg.term_id inner join 
  wp_term_taxonomy ttax_cseg on ttax_cseg.term_id=conc_seg.term_id and taxonomy=\'concepto_seguimiento\' inner join wp_options op on 
  op.option_name= concat(\'concepto_seguimiento_eng_\',conc_seg.term_id)
  where  cat_conc_seg.term_taxonomy_id=%d';

//	error_log(print_r('-------ID CATEGORIA ---'.$categoria_ID.'--------------
//			', TRUE),3,"C:\\log\\cron_log.log");

	try {
		//error_log(print_r('-------------TRY------------------<br>', TRUE),3,"C:\\log\\cron_log.log");
		$conceptos = $wpdb->get_results($wpdb->prepare( $query_str,$categoria_ID));
		//error_log(print_r('-------------TRY 22------------------', TRUE),3,"C:\\log\\cron_log.log");
		//error_log(print_r($wpdb->last_query, TRUE),3,"C:\\log\\cron_log.log");
	} catch (Exception $e) {
		error_log(print_r('------------------------------CATCH-------------------------------
				', TRUE),3,"C:\\log\\cron_log.log");
		error_log(print_r($e, TRUE),3,"C:\\log\\cron_log.log");
		error_log(print_r('
			', TRUE),3,"C:\\log\\cron_log.log");
	}
	


	error_log(print_r('La categoría '.$categoria_ID.' tiene '.$wpdb->num_rows.' conceptos de seguimiento 
			', TRUE),3,"C:\\log\\cron_log.log");	
	
	return $conceptos;

}
	

function ainia_update_conceptos_seguimiento_por_post ($concepto,$categoria_id){
	global $wpdb;
	$conceptos=0;
	/*$query_str='insert into wp_term_relationships (select posts.ID,301,0 from wp_posts posts inner join wp_term_relationships rel_cat on rel_cat.object_id=posts.ID inner join wp_term_taxonomy ttax_cat
			on rel_cat.term_taxonomy_id=ttax_cat.term_taxonomy_id inner join wp_terms term_cat on term_cat.term_id=ttax_cat.term_id
			where posts.post_type=\'post\' and ttax_cat.taxonomy=\'category\' and term_cat.term_id=241 and posts.ID  not in (select object_id from wp_term_relationships where
					term_taxonomy_id=301) and (lower(post_content) like lower('%Acuicultura%') or lower (post_title) like lower('%Acuicultura%') or lower(post_content)
							like lower('%aquaculture%') or lower(post_title) like lower ('%Aquaculture%')) )'*/
	
	$query_str='insert into wp_term_relationships (select posts.ID,'.$concepto->object_id.',0 from wp_posts posts inner join wp_term_relationships rel_cat on rel_cat.object_id=posts.ID inner join wp_term_taxonomy ttax_cat
			on rel_cat.term_taxonomy_id=ttax_cat.term_taxonomy_id inner join wp_terms term_cat on term_cat.term_id=ttax_cat.term_id
			where posts.post_type=\'post\' and ttax_cat.taxonomy=\'category\' and term_cat.term_id=%d and posts.ID  not in (select object_id from wp_term_relationships where
					term_taxonomy_id=%d) and (lower(post_content) like lower(%s) or lower (post_title) like lower(%s) ';
	if (''!=$concepto->option_value)	{	
	$query_str=$query_str.'	or lower(post_content)
							like lower(%s) or lower(post_title) like lower (%s)';
	}						
	$query_str=$query_str.'	) )';									
									$concepto->name; /*Acuicultura*/
	if (''!=$concepto->option_value)	{
		$conceptos = $wpdb->query($wpdb->prepare( $query_str,$categoria_id,$concepto->object_id,'%'.$concepto->name.'%','%'.$concepto->name.'%','%'.$concepto->option_value.'%','%'.$concepto->option_value.'%'));
	} else{
		$conceptos = $wpdb->query($wpdb->prepare( $query_str,$categoria_id,$concepto->object_id,'%'.$concepto->name.'%','%'.$concepto->name.'%'));
	}
	error_log(print_r('-$categoria_id-'.$categoria_id.'
			-$concepto->object_id-'.$concepto->object_id.'
			-$concepto->name-'.$concepto->name.'
			-$concepto->option_value-'.$concepto->option_value.'
			', TRUE),3,"C:\\log\\cron_log.log");
	
	error_log(print_r('***************************************************************************
						'. $wpdb->last_query.'
			***************************************************************************
			', TRUE),3,"C:\\log\\cron_log.log");
	
	error_log(print_r('--------------------   POSTS ACTUALIZADOS:'.$conceptos .'------------
			', TRUE),3,"C:\\log\\cron_log.log");

	
}

/***************************************FUNCIONES PARA CREAR ALERTAS AUTOMÁTICAMENTE *********************/
function ainia_set_alertas(){
	$date2 = date('m/d/Y h:i:s a', time());
	error_log(print_r($date2 . '------------- ainia_set_alertas ----------------------
	', TRUE),3,"C:\\log\\cron_log.log");

	error_log(print_r('------------- ainia_set_alertas - ALERTAS SEGUIMIENTO ----------------------
	', TRUE),3,"C:\\log\\cron_log.log");
	ainia_set_alertas_por_tipo('alerta_seguimiento');
		error_log(print_r('------------- ainia_set_alertas - ALERTAS BUSQUEDA ----------------------
	', TRUE),3,"C:\\log\\cron_log.log");
	ainia_set_alertas_por_tipo('alerta_busqueda');
		
}

function ainia_set_alertas_por_tipo($tipo_alerta){
		error_log(print_r('------------- ainia_set_alertas_por_tipo ----------------------
		', TRUE),3,"C:\\log\\cron_log.log");
		
	$users=get_users();
	$date2 = date('m/d/Y h:i:s a', time());
	
	foreach($users as $user){
		error_log(print_r('
		', TRUE),3,"C:\\log\\cron_log.log");
		error_log(print_r($date2.'----------------------------------------------------------------------------------------------------------------------
		', TRUE),3,"C:\\log\\cron_log.log");
			error_log(print_r('/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		', TRUE),3,"C:\\log\\cron_log.log");
		error_log(print_r(' USUARIO '.$user->ID.'
		', TRUE),3,"C:\\log\\cron_log.log");
		
    	
    	if ('alerta_busqueda'==$tipo_alerta){
    				
    		$categories=get_user_categories2($user->ID);

    	}else{
    
    		$categories1=get_user_conceptos_seguimiento2($user->ID);
    		$categories=array();
    		foreach ($categories1 as $category) $categories[]=$category->term_id;
    		
    		error_log(print_r('---------- conceptos seguimiento para el usuario :'.$user->ID.' : '.implode(",",$categories).' 
    		 ', TRUE),3,"C:\\log\\cron_log.log");
    	
    	}
      	$conceptos_con_alerta=array();
    	$alertas =get_current_alerts_by_user($user->ID,$tipo_alerta);
    	foreach ($alertas as $alerta) $conceptos_con_alerta[]=$alerta->term_id;
    	
    	foreach ($categories as $category){
    			error_log(print_r('
    			///// CONCEPTO:'.$category.'  ', TRUE),3,"C:\\log\\cron_log.log");
    	
    		if(in_array($category,$conceptos_con_alerta)){
    				error_log(print_r('-- TIENE ALERTA'.'--
    							', TRUE),3,"C:\\log\\cron_log.log");
    		} else{
    			 	error_log(print_r('XX  NO TIENE ALERTA XX
    			 	', TRUE),3,"C:\\log\\cron_log.log");
    			 	crea_alerta($category,$user->ID,$tipo_alerta);
    			 	
    		}
    	}
    	limpia_alertas ($user->ID,$categories,$tipo_alerta);
    	
	
	}
}
function get_current_alerts_by_user($user_id,$alert_type){
	global $wpdb;
	 $wpdb->flush();
	$query_string='SELECT wp_posts.*,wp_terms.* FROM `wp_posts` 
	inner join wp_term_relationships on wp_posts.ID=wp_term_relationships.object_id 
	inner join wp_term_taxonomy on wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id 
	inner join wp_terms on wp_term_taxonomy.term_id=wp_terms.term_id WHERE post_type=\''.$alert_type.'\'
	 and post_author=%d';
	$resultado_alertas = $wpdb->query($wpdb->prepare( $query_string,$user_id));
	$resultado_alertas = $wpdb->last_result;
	return $resultado_alertas;
	
}
function crea_alerta($term_id,$user_id,$alert_type){
	global $wpdb;
	$date = date('Y-m-d H:i:s');	
	 $wpdb->flush();
	$query_string='INSERT into wp_posts (ID,post_author,post_title,post_status,post_name,post_parent,guid,post_modified, post_modified_gmt, 
	post_type, comment_count) select 0, %d, name, \'publish\', name, 0, \'guid\',%s,%s,%s,0 from wp_terms where term_id=%d';
	
	$wpdb->query( $wpdb->prepare($query_string,$user_id,$date,$date,$alert_type,$term_id ) );
	$lastid = $wpdb->insert_id;
	
		error_log(print_r('*********************************************************************************************
						'. $wpdb->last_query.'**** ID:'.$lastid.'
			************************************************************************************************************
			', TRUE),3,"C:\\log\\cron_log.log");
	$wpdb->flush();
	
	$query_term_relationship='insert into wp_term_relationships values(%d,%d,0)';
	$wpdb->query( $wpdb->prepare($query_term_relationship,$lastid,$term_id ) );
	
	$query_post_meta_ascenso='insert into wp_postmeta values(0,%d,\'umbral_ascenso\',0)';
	$wpdb->query( $wpdb->prepare($query_post_meta_ascenso,$lastid ) );
	
	$query_post_meta_descenso='insert into wp_postmeta values(0,%d,\'umbral_descenso\',0)';
	$wpdb->query( $wpdb->prepare($query_post_meta_descenso,$lastid ) );
	
		error_log(print_r(' ALERTA PARA: '.$term_id.' con  ID:'.$lastid.' CREADA ................
			', TRUE),3,"C:\\log\\cron_log.log");
		error_log(print_r('
		', TRUE),3,"C:\\log\\cron_log.log");
	$wpdb->flush();
	
}
function limpia_alertas ($user_id,$current_user_categories,$alert_type){
		global $wpdb;
	$query_limpieza='select ID from wp_posts where post_author=%d and post_type=%s and id not in
	 (SELECT object_id from wp_term_relationships where term_taxonomy_id in ('.implode(",",$current_user_categories).'))';
	$resultados=$wpdb->query( $wpdb->prepare($query_limpieza,$user_id,$alert_type) );
	$resultados = $wpdb->last_result;
	$res=array();
	foreach ($resultados as $resultado) $res[]=$resultado->ID;
	
	$query_term_relationships ='delete from wp_term_relationships where object_id in ('.implode(",",$res).')';
	$wpdb->query( $wpdb->prepare($query_term_relationships,''));
	$query_post_alerts ='delete from wp_posts where id in ('.implode(",",$res).')';
	$wpdb->query( $wpdb->prepare($query_post_alerts,''));
}
