<?php

if ( !defined( 'ABSPATH' ) ) exit;

if ( !function_exists( 'add_user_relation' ) ) {
function add_user_relation( $user_id = 0, $user_ip = 0, $object_id, $object_type ) {
	
	if ( !test_user_relation_data( $user_id, $user_ip, $object_id, $object_type )) return false;
	
	global $wpdb;

	$table = $wpdb->prefix . 'user_relations';

	// A logged in user_id trumps an anonymous IP address. 
	
	if("browse"==$object_type)
		$relationship = null;
	else if ( $user_id && $object_id )
		$relationship = $wpdb->get_var( $wpdb->prepare( "SELECT relationship_id FROM {$table} WHERE user_id = %d AND object_id = %d AND object_type = '%s'", $user_id, $object_id, mysql_real_escape_string($object_type) ) );
	else if ($object_id)
		$relationship = $wpdb->get_var( $wpdb->prepare( "SELECT relationship_id FROM {$table} WHERE user_ip = %d AND object_id = %d AND object_type = '%s'", $user_ip, $object_id, mysql_real_escape_string($object_type) ) );
	else 
	    $relationship = null;
				
	// Relationship already exists; add fails.
	if ( $relationship ) {		
		return $relationship;
	} else {
		$result = $wpdb->insert(
			$wpdb->prefix . 'user_relations',
			array(
				'user_id' => $user_id,
				'user_ip' => $user_ip,
				'object_id' => $object_id,
				'object_type' => $object_type
			) );
		if ( !$result )	{	
			echo "fallida";
			return false;
		}
		else{			
			return $wpdb->insert_id;
		}
	}
} }

if ( !function_exists( 'count_user_relation' ) ) {
function count_user_relation( $user_id = 0 ) {
	
	global $wpdb;
	$table = $wpdb->prefix . 'user_relations';		
	if($user_id) $q= $wpdb->prepare("SELECT object_type, count(object_type) number FROM {$table} WHERE user_id = %d GROUP BY object_type",$user_id) ;
			else $q= $wpdb->prepare("SELECT object_type, count(object_type) number FROM {$table} GROUP BY object_type",null );
	
	return $wpdb->get_results($q,ARRAY_A);
} }

if ( !function_exists( 'test_user_relation_data' ) ) {
function test_user_relation_data( $user_id , $user_ip , $object_id, $object_type ) 
{
	if ( !$object_type )	return false;
	if ( !( $user_id == 0 || $user_id = absint( $user_id ) ) ) 	return false;
	if ( !( $user_ip == 0 || $user_ip = absint( $user_ip ) ) )	return false;		
	if ( !($object_id == absint( $object_id ) ) )	return false;		
	if ( !($object_type == trim( $object_type ) ) )	return false;
	return true;
} }


if ( !function_exists( 'delete_user_relation' ) ) {
function delete_user_relation( $relationship_id ) {
	global $wpdb;
	$table = $wpdb->prefix . 'user_relations';	
	if ( $relationship_id ) {					
			$result2 = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}user_relationsmeta WHERE user_relations_id = %d", $relationship_id ) );			
			$result = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}user_relations WHERE relationship_id = %d", $relationship_id ) );			
			return $result ? true: false;
	} else return false;
	
} }

if ( !function_exists( 'update_user_relation' ) ) {
function update_user_relation( $relationship_id ) {
	global $wpdb;
	$table = $wpdb->prefix . 'user_relations';	
	if ( $relationship_id ) {								
			$result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->prefix}user_relations SET date = NOW(), count = count+1 WHERE relationship_id = %d", $relationship_id ) );			
			return $result ? true: false;
	} else return false;	
} }


if ( !function_exists( 'get_user_relation_id' ) ) {
function get_user_relation_id( $user_id = 0, $user_ip = 0, $object_id, $object_type ) {
	
	if ( !test_user_relation_data( $user_id, $user_ip, $object_id, $object_type )) return false;

	$key = "extended_user_relation_{$user_id}_{$user_ip}_{$object_id}_{$object_type}";
	$relationship = wp_cache_get( $key, 'extended_user_relation' );
	if ( $relationship === false ) {
		global $wpdb;

		$table = $wpdb->prefix . 'user_relations';
		if ( $user_id > 0 )
			$relationship = $wpdb->get_var( $wpdb->prepare( "SELECT relationship_id FROM {$table} WHERE user_id = %d AND object_id = %d AND object_type = '%s'", $user_id, $object_id, mysql_real_escape_string($object_type) ) );
		else
			$relationship = $wpdb->get_var( $wpdb->prepare( "SELECT relationship_id FROM {$table} WHERE user_ip = %d AND object_id = %d AND object_type = '%s'", $user_ip, $object_id, mysql_real_escape_string($object_type) ) );
		wp_cache_set( $key, $relationship, 'extended_user_relation' );
	}
	return $relationship;
} }

if ( !function_exists( 'add_user_relation_meta' ) ) {
function add_user_relation_meta( $relation_id, $meta_key, $meta_value, $unique =false ) 
{
	if(!$relation_id)return false;
	return add_metadata('user_relations', $relation_id, $meta_key, $meta_value, $unique);
}}

if ( !function_exists( 'update_user_relation_meta' ) ) {
function update_user_relation_meta( $relation_id, $meta_key, $meta_value, $unique =false  ) 
{   
	return update_metadata('user_relations', intval($relation_id), $meta_key, $meta_value, $unique);
}}


if ( !function_exists( 'delete_user_relation_meta' ) ) {
function delete_user_relation_meta( $relation_id, $meta_key, $meta_value = ''  ) 
{
	return delete_metadata('user_relations', $relation_id, $meta_key, $meta_value);
}}

if ( !function_exists( 'get_user_relation_meta' ) ) {
function get_user_relation_meta( $relation_id, $meta_key, $single = true ) 
{
	return get_metadata('user_relations', $relation_id, $meta_key, $single);
}}


//---CREATE DIFFERENT ELEMENTS -----------------------------------------------------------------------------------

function add_extended_user_read_rss ($user_id=1,$msg='?')  
{	
	$rel=add_user_relation($user_id,current_user_ip(),0,"rss_import");	
	add_user_relation_meta($rel,"log",$msg);				
	return $rel;
}

function add_extended_user_categorize ($post_id,$category_id,$user_id=0)  
{
	if(!$user_id)$user_id = current_user_id(); 
	$rel=add_user_relation($user_id,current_user_ip(),$post_id,"categorize");
	add_user_relation_meta($rel,"cat",$category_id);				
	return $rel;
}


function add_extended_user_recommend ($post_id,$to,$user_id=0)  
{
	if(!$user_id)$user_id = current_user_id(); 
	$rel=add_user_relation($user_id,current_user_ip(),$post_id,"recommend");	
	add_user_relation_meta($rel,"to",$to);				
	return $rel;
}

function add_extended_user_recommended ($post_id,$user_to,$user_from)  
{
	$rel=add_user_relation($user_to,0,$post_id,"recommended");	
	add_user_relation_meta($rel,"by",$user_from);				
	return $rel;
}

function add_extended_user_favorite ($post_id,$user_id=0)  
{
	if(!$user_id)$user_id = current_user_id(); 
	$rel=add_user_relation($user_id,current_user_ip(),$post_id,"favorite");
	return $rel;
}

function add_extended_user_newsletter_sent($user_id,$post_ids)
{
	$rel=add_user_relation($user_id,current_user_ip(),0,"newsletter");
	add_user_relation_meta($rel,"posts",implode(",",$post_ids));
	return $rel;
}

function add_extended_user_email_from ($user_id,$date,$from,$subject,$body)  
{
	$rel=add_user_relation($user_id,current_user_ip(),0,"email_from");
	add_user_relation_meta($rel,"date"		,$date);
	add_user_relation_meta($rel,"from"		,$from);
	add_user_relation_meta($rel,"subject"	,$subject);
	add_user_relation_meta($rel,"body"		,$body);	
	return $rel;
}

function add_extended_user_email_to   ($user_id,$date,$to,$subject,$body)
{
	$rel=add_user_relation($user_id,current_user_ip(),0,"email_to");
	add_user_relation_meta($rel,"date"		,$date);
	add_user_relation_meta($rel,"to"		,$to);
	add_user_relation_meta($rel,"subject"	,$subject);
	add_user_relation_meta($rel,"body"		,$body);	
	return $rel;
}

function add_extended_user_note($user_id,$text)
{
	$rel=add_user_relation($user_id,current_user_ip(),0,"note");
	add_user_relation_meta($rel,"text",$text);
	return $rel;
}

function add_extended_user_phone_call ($user_id,$text)
{
	$rel=add_user_relation($user_id,current_user_ip(),0,"phone_call");
	add_user_relation_meta($rel,"text"		,$text);		
	return $rel;
}

function add_extended_user_meeting    ($user_id,$text)
{
	$rel=add_user_relation($user_id,current_user_ip(),0,"meeting");
	add_user_relation_meta($rel,"text"		,$text);		
	return $rel;
}

function add_extended_user_form	      ($user_id,$text)
{
	$rel=add_user_relation($user_id,current_user_ip(),0,"form");
	add_user_relation_meta($rel,"text"		,$text);		
	return $rel;
}

function add_extended_user_user($user_id,$user_id2,$text)
{
	$rel=add_user_relation($user_id,current_user_ip(),$user_id2,"user");
	add_user_relation_meta($rel,"text",$text);		
	return $rel;
}

//--- COUNT ELEMENTS AND DO STATISTIC -------------------------------------------------------------------------------


if ( !function_exists( 'get_last_date_of_user_relation' ) ) {
function get_last_date_of_user_relation( $user_id, $object_type ) {
	global $wpdb;
	$table = $wpdb->prefix . 'user_relations';		
	$sql = $wpdb->prepare( "SELECT date FROM {$table} WHERE user_id = %d AND object_type = '%s' ORDER BY date desc", $user_id, mysql_real_escape_string($object_type) );
	return $wpdb->get_var( $sql ) ;		
} }


if ( !function_exists( 'get_object_ids_of_user_relation' ) ) {
function get_object_ids_of_user_relation( $user_id, $object_type ) {
	global $wpdb;
	$table = $wpdb->prefix . 'user_relations';		
	$sql = $wpdb->prepare( "SELECT object_id FROM {$table} WHERE user_id = %d AND object_type = '%s'", $user_id, mysql_real_escape_string($object_type) );
	$results = $wpdb->get_results( $sql ) ;	
	$ids = array();
	foreach($results as $result)
	 $ids[]=$result->object_id;
	return $ids;
} }

if ( !function_exists( 'get_objects_of_user_relation' ) ) {
function get_objects_of_user_relation( $user_id, $object_type ) {
	global $wpdb;
	$table = $wpdb->prefix . 'user_relations';		
	$sql = $wpdb->prepare( "SELECT object_id,count,date FROM {$table} WHERE user_id = %d AND object_type = '%s'", $user_id, mysql_real_escape_string($object_type) );
	return $wpdb->get_results( $sql ) ;
} }

if ( !function_exists( 'get_count_of_user_relation' ) ) {
function get_count_of_user_relation( $user_id, $object_type ) {
	global $wpdb;
	$table = $wpdb->prefix . 'user_relations';		
	$sql = $wpdb->prepare( "SELECT SUM(count) AS total FROM {$table} WHERE user_id = %d AND object_type = '%s' ", $user_id, mysql_real_escape_string($object_type) );
/*	Franco para que realice la cuenta de los objetos correctamente
	$sql = $wpdb->prepare( "SELECT SUM(count) AS total FROM {$table} WHERE user_id = %d AND object_type = '%s' GROUP BY object_id ORDER BY total DESC", $user_id, mysql_real_escape_string($object_type) );
*/
	return $wpdb->get_var( $sql ) ;	
} }

if ( !function_exists( 'get_count_of_object_by_user_relation' ) ) {
function get_count_of_object_by_user_relation( $object_id , $object_type) {
	global $wpdb;
	$table = $wpdb->prefix . 'user_relations';		
	$sql = $wpdb->prepare( "SELECT SUM(count) AS total FROM {$table} WHERE object_id = %d AND object_type = '%s' GROUP BY object_id ", $object_id, mysql_real_escape_string($object_type) );
	return $wpdb->get_var( $sql ) ;	
} }



//--- AJAX CALLBACKS  ------------------------------------------------------------------------------------

function save_note_meeting_call_callback() 
{
	global $wpdb; // this is how you get access to the database

	$data = array(
		'dialog' =>  $_REQUEST['dialog'] ,
		'relationship_id' =>  $_REQUEST['relationship_id'] ,
		'user_id' =>  $_REQUEST['user_id'] ,
		'user_ip' =>  $_REQUEST['user_ip'] ,
		'object_id' =>  $_REQUEST['object_id'] ,
		'object_type' =>  $_REQUEST['object_type'] ,
		);
	
	$success= false;
	$reload = false;		
	$relation_id = intval($data['relationship_id']);
	if(!$relation_id){
		$relation_id = add_user_relation( $data['user_id'], $data['user_ip'], $data['object_id'], $data['object_type']);
		$reload=true;
		}
	
	if($relation_id)
	switch($data['object_type'])
	{
		case 'note':
		case 'meeting':
		case 'phone_call':
				  $text = $_REQUEST['text'];
				  if($reload) $success = add_user_relation_meta($relation_id,"text",$text);
				  else   	  $success = update_user_relation_meta($relation_id,"text",$text);				  
	}
		
	if($success)
			$message =  __('<strong>Ok</strong> Element was saved','ainia');			
	else 	$message =  __('<strong>Error</strong> Element was not saved','ainia');
		
	$response = array(
		"dialog"  => $data['dialog'],
		"reload"  => $reload,
		"result"  => $relation_id ? "true":"false",
		"message"  => $message,
		"content"  => $text,
		);	
	
	echo json_encode($response);

	die(); // this is required to return a proper result
}

?>