<?php


if(!class_exists('WP_List_Table')){
    require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}

class Extended_User_Relations_List_Table extends WP_List_Table 
{
	var $user_id = null;
		
    function __construct($the_user_id){
        global $status, $page;
       
	    $this->user_id = $the_user_id;
		
		
        //Set parent defaults
        parent::__construct( array(
            'singular'  => 'user_relation',     //singular name of the listed records
            'plural'    => 'user_relations',    //plural name of the listed records
            'ajax'      => false        //does this table support ajax?
        ) );
        
		
    }
	
//--- COLUMNS --------------------------------------------------------------------------------	
    
	
	function column_date($item){

		$actions = array();
		
		switch($item['object_type'])
		{
			//Lectura en Popup
			case "email"		:
			case "email_from"	:
			case "email_to"		:$actions = array('view'=> '<a class="dialog_link" href="#dialog'.$item['relationship_id'].'" >'.__("Fast View").'</a>');		
						
			case "login"		:break;
						
			case "post"			:$actions = array(
									'view'		=> '<a class="dialog_link" href="#dialog'.$item['relationship_id'].'" >'.__("Fast View").'</a>',											
									'edit'      => '<a href="post.php?action=edit&post='.$item['object_id'].'">'.__("Edit").'</a>',																		
									'permalink' => '<a target="_blank" href="'.get_permalink($item['object_id']).'">'.__("Link").'</a>',	
								);break;
								
								
			case "recommend"	:
			case "recommended"	:
			case "categorize"	:
			case "favorite"		:$actions = array(
									'permalink' => '<a target="_blank" href="'.get_permalink($item['object_id']).'">'.__("Link").'</a>',	
								);break;				
						
			case "comment"		:$mycomment = get_comment($item['object_id']); 								 
								 if($mycomment) $actions = array(
										'view'	=> '<a class="dialog_link" href="#dialog'.$item['relationship_id'].'" >'.__("Fast View").'</a>',											
										'edit'  => '<a href="edit-comments.php?p='.$mycomment->comment_post_ID.'">'.__("Edit").'</a>',										
										);
								break;
								
			case "user"			:$actions = array(								
									'edit'=> '<a href="user-edit.php?user_id='.$item['object_id'].'">'.__("Edit").'</a>',																										
								);break;
			
			//Editar y borrar		
			case "note"			:
			case "phone_call"	:
			case "meeting"		:$actions = array('edit'	=> '<a class="dialog_link" href="#dialog'.$item['relationship_id'].'" >'.__("Edit").'</a>');
								 break;
			
			case "rss_import"	:break;
			
			//Pendientes de implementar
			case "form"			:$actions = array('view'=> '<a class="dialog_link" href="#dialog'.$item['relationship_id'].'" >'.__("Fast View").'</a>');		
			case "product"		:break;
			
			
			case "newsletter"	:$actions = array(
									'view'		=> '<a class="dialog_link" href="#dialog'.$item['relationship_id'].'" >'.__("Fast View").'</a>',											
								);break;
								
			default				:break;
		}
		
        //Build row actions
		return sprintf('%1$s %2$s', $item['date'], $this->row_actions($actions));
    }
	
	
	function column_type($item){	
		$icono = $this->get_icon($item['object_type']);
		return sprintf('%1$s %2$s', $icono['icon'],$icono['title']);
	}
	
	
//**************************************************** CONTENIDOS ****************************************************************************	
	
	
	function get_icon($icon_type)
	{
		switch($icon_type)
		{
			case "email_from"	:$icon='mail-closed';$title=__('E-mail from','ainia');break;
			case "email_to"		:$icon='mail-closed';$title=__('E-mail to','ainia');break;			
			case "note"			:$icon='pencil';$title=__('Note','ainia');break;
			case "phone_call"	:$icon='phone';$title=__('Phone call','ainia');break;			
			case "meeting"		:$icon='lightbulb';$title=__('Meeting','ainia');break;
			case "login"		:$icon='locked';$title=__('Log-in','ainia');break;//89
			case "form"			:$icon='clipboard';$title=__('Form','ainia');break;
			case "comment"		:$icon='comment';$title=__('Comment','ainia');break;
			case "post"			:$icon='script';$title=__('Post','ainia');break;
			case "user"			:$icon='person';$title=__('User','ainia');break;
			case "product"		:$icon='cart';$title=__('Product','ainia');break;
			case "browse"		:$icon='newwin';$title=__('Browse','ainia');break;
			
			case "recommend"	:$icon='arrowstop-1-e';$title=__('Recommend','ainia');break;
			case "recommended"	:$icon='arrowstop-1-w';$title=__('Receive Recommendation','ainia');break;
			case "categorize"	:$icon='tag';$title=__('Categorize','ainia');break;
			case "favorite"		:$icon='star';$title=__('Favorite','ainia');break;
			case "rss_import"	:$icon='signal-diag';$title=__('RSS Import','ainia');break;
			case "newsletter"	:$icon='circle-arrow-e';$title=__('Newsletter','ainia');break;
			
			default				:$icon='notice';$title=__('Unknown','ainia');break;
		}
		return array('icon' => '<span title="id:'.$title.'" class="left-icon ui-icon ui-icon-'.$icon.'"></span>',
					 'title' => $title,
					 'icon_id' => $icon,
					 );
	
	}
	
	function content_line($item,$field_name,$field_key,$separator=false,$word_limit=false)
	{	
		$cont = get_user_relation_meta($item['relationship_id'],$field_key,true);				
		if($word_limit) $cont = $this->word_limiter($cont,$word_limit);
			 if($separator) return sprintf("<hr size='1'/> %s",$cont);
		else if($field_name)return sprintf("<em style='display:inline-block;width:100px;'>%s:</em> %s<br/>",$field_name,$cont);
				       else return $cont."<br/>";
	}
		
	function word_limiter($str, $limit = 50, $end_char = '&#8230;')
    {
		if(strlen($str)<=$limit)return $str;
		while(substr($str,$limit,1)!=" " && $limit<strlen($str))$limit++;
		return substr($str,0,$limit)." ...";
    }
	
	function relation_base_content($item)
	{
	
		$buffer='';		
		switch($item['object_type'])
		{
			case "email_from"	:$buffer.= "<strong>".$this->content_line($item,'','from')."</strong>";
								 $buffer.= $this->content_line($item,'','subject');								 								 
								 break;
								 
			case "email_to"		:$buffer.= "<strong>".$this->content_line($item,'','to')."</strong>";
								 $buffer.= $this->content_line($item,'','subject');								 
								 break;
								 
			case "phone_call"	:
			case "meeting"		:
			case "note"			:$buffer.= $this->content_line($item,'','text',false,50);
								 break;
								 			
			case "login"		:$buffer.= "IP <strong>".$this->content_line($item,'','ip')."</strong>";			
								 break;
			
			case "rss_import"	:$buffer.= get_user_relation_meta($item['relationship_id'],'log',true);			
								 break;
						
			case "comment"		:$mycomment = get_comment($item['object_id']); 
								 if($mycomment) {
									$mypost = get_post($mycomment->comment_post_ID); 
									$buffer.= '<em>'.__('Comment to','ainia').':</em> <strong>'.$mypost->post_title.'</strong><br/>' ;								 												 
									$buffer.=$this->word_limiter(strip_tags($mycomment->comment_content));
								 }
								 break;
			
			case "post"			:$mypost = get_post($item['object_id']); 
								 if($mypost) {
									$buffer.= '<strong>'.$mypost->post_title.'</strong><br/>' ;								 												 
									if($mypost->post_excerpt)$buffer.=$this->word_limiter(strip_tags($mypost->post_excerpt));
									else $buffer.=$this->word_limiter(strip_tags($mypost->post_content));
								 }
								 break;
								 
			case "recommend"	:$mypost = get_post($item['object_id']); 
								 if($mypost) {						
									$user_id = get_user_relation_meta($item['relationship_id'],'to',true);
									$user = get_userdata($user_id);
									$buffer.= sprintf(__('You have recommended <a target="_blank" href="%s">%s</a> to %s','ainia'), get_permalink($mypost->ID), $mypost->post_title, $user->display_name); 								 												 
								 }break;
			
			case "recommended"	:$mypost = get_post($item['object_id']); 
								 if($mypost) {						
									$user_id = get_user_relation_meta($item['relationship_id'],'by',true);
									$user = get_userdata($user_id);
									$buffer.= sprintf(__('%s has recommended <a target="_blank" href="%s">%s</a> to you','ainia'), $user->display_name, get_permalink($mypost->ID), $mypost->post_title); 
								 }break;
			
			case "categorize"	:$mypost = get_post($item['object_id']); 
								 if($mypost) {						
									$cat_id = get_user_relation_meta($item['relationship_id'],'cat',true);
									$term = get_term($cat_id,'category');
									$buffer.= sprintf(__('You have categorized <a target="_blank" href="%s">%s</a> in %s','ainia'), get_permalink($mypost->ID), $mypost->post_title, $term->name); 
								 }break;
			
			case "favorite"		:$mypost = get_post($item['object_id']); 
								 if($mypost) {															
									$buffer.= sprintf(__('You have selected <a target="_blank" href="%s">%s</a> as favorite','ainia'), get_permalink($mypost->ID), $mypost->post_title); 
								 }break;
					 
								 
			case "user"			:$myuser = get_userdata($item['object_id']);  
								if($myuser) {
									$buffer.= '<strong>'.$myuser->display_name.'</strong><br/>' ;								 												 
									$buffer.= $myuser->user_email.'<br/>' ;								 												 
								}
								
			//Pendientes					
			case "form"			:$p = json_decode(get_user_relation_meta($item['relationship_id'],'text',true));
								 $buffer.= $p->Formulario;
								 break;
								 
			case "browse"		:$tit = explode("::",get_user_relation_meta($item['relationship_id'],'text',true));
								 $url = get_user_relation_meta($item['relationship_id'],'url',true);
								 $buffer = $tit[0].": <a target='_blank' href='".$url."'>".$tit[1]."</a>";								 
								 break;					 
			
			case "newsletter"	:$posts = explode(",",get_user_relation_meta($item['relationship_id'],'posts',true));								 
								 $buffer = sprintf(__('Sent %s posts in the newsletter','ainia'),count($posts));								 
								 break;					
								 
			case "product"		:break;
			
			default				:break;
		}
		return $buffer;
	}
	
	function relation_extended_content($item)
	{
	
		$buffer='';		
		$edit=false;	
		switch($item['object_type'])
		{
			case "email_from"	:$buffer.= $this->content_line($item,__("From",'ainia')	,'from');
								 $buffer.= $this->content_line($item,__("Subject",'ainia')	,'subject');								 
								 $buffer.= $this->content_line($item,__("Date",'ainia')	,'date');
								 $buffer.= $this->content_line($item,__("Body",'ainia')	,'body',true);			
								 break;
								 
			case "email_to"		:$buffer.= $this->content_line($item,__("To",'ainia')		,'to');
								 $buffer.= $this->content_line($item,__("Subject",'ainia')	,'subject');								 
								 $buffer.= $this->content_line($item,__("Date",'ainia')	,'date');
								 $buffer.= $this->content_line($item,__("Body",'ainia')	,'body',true);			
								 break;
								 
			case "phone_call"	:
			case "meeting"		:
			case "note"			:
								 $buffer .= "<textarea class='relation_textarea'>";								 	
								 $buffer .= get_user_relation_meta($item['relationship_id'],'text',true);
								 $buffer .= "</textarea><br/>";
								 break;
			
			case "post"			:$mypost = get_post($item['object_id']); 
								 if($mypost) {
									$buffer.= '<h3>'.$mypost->post_title.'</h3><br/>' ;								 												 
									//$buffer.= apply_filters('the_content',$mypost->post_content);
								 }
								 break;

			case "rss_import"	:								 
			case "recommend"	:
			case "recommended"	:
			case "favorite"		:
			case "categorize"	:$buffer = $this->relation_base_content($item);
								 break;
			
			
			case "comment"		:$mypost = get_post($item['object_id']); 
								 if($mypost) {
									$buffer.= '<strong>'.$mypost->post_title.'</strong><br/>' ;								 												 
									if($mypost->post_excerpt)$buffer.=$this->word_limiter($mypost->post_excerpt);
									else $buffer.=$this->word_limiter($mypost->post_content);
								 }break;
		  //Pendientes							
			case "form"			:$p = json_decode(get_user_relation_meta($item['relationship_id'],'text',true));
								 $buffer.="<table width='100%' border='0'>";
								 foreach($p as $key => $value)
								 {
								  $s=explode('-',$key);if(is_array($s))$s=$s[0];
								  $buffer.=sprintf("<tr><td><em>%s</em></td><td>&nbsp;:&nbsp;</td><td>%s</td></tr>",$s,$value);								 
								  if($s=="ID")$buffer.="<tr><td colspan='3'><hr size='1'/></td></tr>";
								 }
								 $buffer.="</table>";
								 break;
								 
			case "browse"		 :	$tit = explode("::",get_user_relation_meta($item['relationship_id'],'text',true));
									$url = get_user_relation_meta($item['relationship_id'],'url',true);
								    $buffer = $tit[0].": <a target='_blank' href='".$url."'>".$tit[1]."</a>";
								 break;
								 
			case "newsletter"	:$buffer='';
								 $posts = explode(",",get_user_relation_meta($item['relationship_id'],'posts',true));								 
								 foreach($posts as $post_id)
								  $buffer .= "<a href='".get_permalink($post_id)."'>".get_the_title($post_id)."-</a><br/>";
								 break;					
								 
			case "product"		:break;
		}
		return $buffer;
	}
	
	function column_content($item)
	{	
		
		$buffer ='';
		$buffer.= '<div id="contentdialog'.$item['relationship_id'].'">'.$this->relation_base_content($item,false)."</div>";						
		$buffer.= $this->dialog_html($item);			
		return $buffer;
	}
		
    function dialog_html($item)
	{	
		$dialog_id=$item['relationship_id'];		
		switch($item['object_type'])
		{
		  case "note":$dialog_class='dialog_note';break;
		  case "meeting":$dialog_class='dialog_meeting';break;
		  case "phone_call":$dialog_class='dialog_phone_call';break;
		  default:$dialog_class='dialog';break;
		}
		$icon = $this->get_icon($item['object_type']);				
		//$buffer.='<div id="dialog'.$dialog_id.'" class="'.$dialog_class.'" title="<span class=\'left-icon ui-icon ui-icon-'.$icon['icon_id'].'\'></span>  '.$icon['title'].'">';
		//$buffer.='<div id="dialog'.$dialog_id.'" class="'.$dialog_class.'" title="<span class=\'left-icon ui-icon ui-icon-'.$icon['icon_id'].'\'></span>  '.$icon['title'].'">';
		$buffer.='<div id="dialog'.$dialog_id.'" class="'.$dialog_class.'" title="'.$icon['title'].'">';
		$buffer.='<img class="loading_image" src="'.plugins_url("images/ajax-loader.gif", plugin_basename(__FILE__) ).'"/>';
		
		$buffer.='<input type="hidden" id="dialog'.$dialog_id.'_relationship_id" 	name="dialog'.$dialog_id.'_relationship_id" 	value="'.$item['relationship_id'].'">';
		$buffer.='<input type="hidden" id="dialog'.$dialog_id.'_user_id" 	 	 	name="dialog'.$dialog_id.'_user_id" 	 		value="'.$item['user_id'].'">';
		$buffer.='<input type="hidden" id="dialog'.$dialog_id.'_user_ip" 	 	 	name="dialog'.$dialog_id.'_user_ip" 	 		value="'.$item['user_ip'].'">';
		$buffer.='<input type="hidden" id="dialog'.$dialog_id.'_object_id" 	 		name="dialog'.$dialog_id.'_object_id" 	 		value="'.$item['object_id'].'">';
		$buffer.='<input type="hidden" id="dialog'.$dialog_id.'_object_type" 	 	name="dialog'.$dialog_id.'_object_type" 		value="'.$item['object_type'].'">';		
		$buffer.=$this->relation_extended_content($item);
		$buffer.='</div>';
		return $buffer;
	}
	
	function column_default($item, $column_name)
	{
        switch($column_name){
            case 'date':
                return $item[$column_name];
			case 'count':
                return $item[$column_name];
            default:
                return print_r($item,true); //Show the whole array for troubleshooting purposes
        }
    }
	
	function column_user($item)
	{	
		$myuser = get_userdata($item['user_id']);  
		$buffer="";
		if($myuser) {
			$buffer.= '<strong>'.$myuser->display_name.'</strong><br/>' ;								 												 
			$buffer.= $myuser->user_email.'<br/>' ;								 												 
		}    
		return $buffer;
    }
	
	function column_cb($item)
	{
        return sprintf(
            '<input type="checkbox" name="%1$s[]" value="%2$s" />',
            /*$1%s*/ $this->_args['singular'],  //Let's simply repurpose the table's singular label ("movie")
            /*$2%s*/ $item['relationship_id']                //The value of the checkbox should be the record's id
        );
    }
    
    
    function get_columns()
	{
	
		if($this->user_id)
			$columns = array(
				'cb'        => '<input type="checkbox" />',  			
				'date'     => __('Date','ainia'),
				'type'     => __('Type','ainia'),								
				'content'  => __('Content','ainia'),
				'count'    => __('Count','ainia'),
				
			);
		else
			$columns = array(
				'cb'        => '<input type="checkbox" />',  
				'date'     => __('Date','ainia'),
				'user'     => __('User','ainia'),			
				'type'     => __('Type','ainia'),				
				'content'  => __('Content','ainia'),				
				'count'    => __('Count','ainia'),				
			);
		
		
        return $columns;
    }
	
	//$this->user_id
    
    function get_sortable_columns() 
	{
        $sortable_columns = array(
            'date'     => array('date',false),     //true means it's already sorted
			'user'     => array('user_id',false),     //true means it's already sorted
            'type'    => array('object_type',false)            
        );
        return $sortable_columns;
    }

	//---- AYUDAS-------------------------------------------
	
	
	function display_tablenav( $which )
	{		
		//sobrecarga a la original para evitar incluir el _wpnonce
		$this->extra_tablenav( $which );
		?>		
		<div class="tablenav <?php echo esc_attr( $which ); ?>">
			<div class="alignleft actions">
				<?php $this->bulk_actions(); ?>
			</div>
		<?php
			
			$this->pagination( $which );
		?>
			<br class="clear" />
		</div>
		<?php
	}
	
	function extra_tablenav( $which )
	{
	
	    if ( $which == "top" ){
			$cuantos=0;
	        //The code that goes before the table is here						
			?>
			<ul class="subsubsub user-relations-filters">
			   <?php foreach(count_user_relation($this->user_id) as $tipo){
					  $icon = $this->get_icon($tipo['object_type']);					
					  $cuantos+=intval($tipo['number']);
			   ?>
				<li>
					<a href="<?php echo add_query_arg('object_type',$tipo['object_type']);?>" 						
						<?php if($tipo['object_type']==$_REQUEST['object_type'])echo 'class="current"'?>>
						<?php echo $icon['icon']; ?><?php _e($icon['title']); ?> 
						<span class="count">(<?php echo $tipo['number']; ?>)</span>
					</a> &nbsp; | &nbsp;&nbsp;
				</li>						
				<?php }?>
				<a href="<?php echo remove_query_arg('object_type');?>" 
						<?php if(!$_REQUEST['object_type'])echo 'class="current"'?>>
						<?php _e("All"); ?> 
						<span class="count">(<?php echo $cuantos ?>)</span>
				</a> 
			</ul>
			
			<?php
	        
	    }
	    if ( $which == "bottom" ){
	        //The code that goes after the table is there
	        
	
	    }
	}
	
	
	//---- PROCESOS ---------------------------------------------------------------------------------------------------------
    
    function get_bulk_actions() 
	{
        $actions = array(
            'delete'    => 'Delete'
        );
        return $actions;
    }
    
    
    function process_bulk_action()
	{
        
        //Detect when a bulk action is being triggered...
        if( 'delete'===$this->current_action() ) {		
			$contador=0;
			foreach($_REQUEST['user_relation'] as $relationship_id)
			 if(delete_user_relation($relationship_id))
			  $contador++;
            
			if($contador)
			     echo '<br/><div id="ok_message" style="display:block" class="ui-state-highlight ui-corner-all"><strong>'. __('Ok','ainia').'. </strong>'.$contador ." ". __('Items deleted','ainia').'</div>	';
			else echo '<br/><div id="ko_message" style="display:block" class="ui-state-error ui-corner-all"><strong>'. __('Error','ainia').'. </strong> 0 '. __('Items deleted','ainia').'</div>';	
        }
        
    }
    
    
    function prepare_items() 
	{
        
		global $wpdb; //This is used only if making any database queries
				
		$per_page = $this->get_items_per_page('user_relations_per_page', 15);
		        
		$columns = $this->get_columns();
        
		$hidden = array();
        
		$sortable = $this->get_sortable_columns();
		
		$current_page = $this->get_pagenum();
        
		$this->_column_headers = array($columns, $hidden, $sortable);
        		
		$this->process_bulk_action();
				
		$query = "SELECT * FROM $wpdb->user_relations WHERE 1";
					
		if($this->user_id)$query = $wpdb->prepare($query." AND user_id=%d",$this->user_id);
		
		if($_REQUEST['object_type'])$query = $wpdb->prepare($query." AND object_type=%s",$_REQUEST['object_type']);
				
		if($_REQUEST['orderby']=='object_type'||$_REQUEST['orderby']=='user_id')$orderby=$_REQUEST['orderby'];else $orderby='date';			
		$order = $_REQUEST['order']=='asc' ? 'ASC' : 'DESC'; //If no order, default to asc			
		if(!empty($orderby) & !empty($order)) $query .= ' ORDER BY '.$orderby.' '.$order;
		
			
		$total_items = $wpdb->query($query); 
				
		 //Page Number
		if(empty($current_page) || !is_numeric($current_page) || $current_page<=0 ){ $current_page=1; }
		$total_pages = ceil($total_items/$per_page);
		if(!empty($current_page) && !empty($per_page)){
			$offset=($current_page-1)*$per_page;
			$query.=' LIMIT '.(int)$offset.','.(int)$per_page;
		}
		
		$this->items = $wpdb->get_results($query, ARRAY_A);				
		        
		$this->set_pagination_args( array(
            'total_items' => $total_items,                  //WE have to calculate the total number of items
            'per_page'    => $per_page,                     //WE have to determine how many items to show on a page
            'total_pages' => ceil($total_items/$per_page)   //WE have to calculate the total number of pages
        ) );
		
		
    }
    
}






