<?php
/**
 * Custom Functions
 *
 * @package WordPress
 * @subpackage Charity
 * @since Charity 1.0
 */

/*-----------------------------------------------------------
	Format money
-----------------------------------------------------------*/

if ( ! function_exists( 'wplook_format_money' ) ) {
	// echo wplook_format_money(1050); # 1,050
	// echo wplook_format_money(1321435.4, true); # 1,321,435.40
	function wplook_format_money($number, $fractional=false) {
		if ($fractional) {
			return number_format($number, 2, '.', ',');
		} else {
			return number_format($number, 0, '.', ',');
		}
	}
}

/*-----------------------------------------------------------------------------------*/
/*	Enable svg support
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_add_svg_mime_types' ) ) {
	/**
	 * @param $mimes - MIME file type
	 * @return mixed
	 */
	function wplook_add_svg_mime_types( $mimes ) {
		if ( is_super_admin() ) {
			$mimes['svg'] = 'image/svg+xml';
		}
		return $mimes;
	}
	add_filter( 'upload_mimes', 'wplook_add_svg_mime_types' );
}

/*-----------------------------------------------------------------------------------*/
/*	Trim excerpt
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_short_excerpt' ) ) {
	function wplook_short_excerpt($limit) {
		$excerpt = explode(' ', get_the_excerpt(), $limit);
		if (count($excerpt)>=$limit) {
			array_pop($excerpt);
			$excerpt = implode(" ",$excerpt).'...';
		} else {
			$excerpt = implode(" ",$excerpt);
		}
		$excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
		return $excerpt;
	}
}

/*-----------------------------------------------------------------------------------*/
/*	Return donations raised amount by ID
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_donations_raised' ) ) {
	function wplook_donations_raised( $id ) {
		global $wpdb;
		$args_pledge = array(
				'cache_results' => false,
				'fields' => 'ids',
				'meta_key'=>'wpl_pledge_cause',
				'meta_value'=> $id,
				'no_found_rows' => true,
				'post_status' => 'publish',
				'post_type' => 'post_pledges',
				'posts_per_page' => -1,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'meta_query' => array(
					array(
						'key' => 'wpl_pledge_payment_status',
						'value' => 'completed',
						'compare' => 'IN',
					),
				)
			);
		$meta_key = 'wpl_pledge_donation_amount';
		$my_pledge = null;

		// Check for transient. If none, then execute WP_Query
		if ( false === ( $my_pledge = get_transient( 'wpl_pledges_for_cause_'.$id ) ) ) {
			$my_pledge = new WP_Query( $args_pledge );
			// Put the results in a transient.
			set_transient( 'wpl_pledges_for_cause_'.$id, $my_pledge, 4 * WEEK_IN_SECONDS );
		}

		$wplook_donations_raised = 0;
		$wplook_donations_number = count( $my_pledge->posts ) ;
		if ( !empty( $my_pledge->posts ) ) {
			$post_ids = implode( ',', $my_pledge->posts );
			$wplook_donations_raised = $wpdb->get_var( $wpdb->prepare(
				"
					SELECT SUM(meta_value)
					FROM $wpdb->postmeta
					WHERE post_id IN ($post_ids)
					AND meta_key = %s
				",
				$meta_key
			) );
		}
		return array( $wplook_donations_number, $wplook_donations_raised );
	}
}
/*------------------------------------------------------------
	Delete cause cache if causes or pledges was added, updated or deleted
============================================================*/
function wplook_delete_cause_transients( $pid ) {
    $local_post = get_post( $pid );

    if( !$local_post ) {
    	return;
    }

	switch ( $local_post->post_type ) {
		case 'post_causes':
			$id = $local_post->ID;
			break;
		case 'post_pledges':
			$id = get_post_meta( $local_post->ID, 'wpl_pledge_cause', true );
			break;
		default:
			return;
	}

	if ( $id > 0 ) {
		delete_transient( 'wpl_pledges_for_cause_'.$id );
	}
}
add_action( 'save_post', 'wplook_delete_cause_transients' );
add_action( 'save_post_post_pledges', 'wplook_delete_cause_transients' );
add_action( 'save_post_post_causes', 'wplook_delete_cause_transients' );
add_action( 'before_delete_post', 'wplook_delete_cause_transients' );
add_action( 'trash_post', 'wplook_delete_cause_transients' );
add_action( 'untrash_post', 'wplook_delete_cause_transients' );

/*-----------------------------------------------------------------------------------*/
/*	Custom CSS
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_custom_css' ) ) {
	function wplook_custom_css() {
		$wpl_css = ot_get_option( 'wpl_css' );
		echo "<style>".$wpl_css."</style>";
	}
	add_action( 'wp_head', 'wplook_custom_css' );
}

/*-----------------------------------------------------------------------------------*/
/*	BE Dashbord Widget
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_dashboard_widgets' ) ) {
	function wplook_dashboard_widgets() {
		global $wp_meta_boxes;
		unset(
			$wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins'],
			$wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary'],
			$wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']
		);
			wp_add_dashboard_widget( 'dashboard_custom_feed', '<a href="'.esc_url( 'https://wplook.com?utm_source=Our-Themes&utm_medium=rss&utm_campaign=Charity' ).'">'.__('WPlook News', 'charity-wpl').'</a>' , 'dashboard_custom_feed_output' );
	}
	add_action('wp_dashboard_setup', 'wplook_dashboard_widgets');
}

if ( ! function_exists( 'dashboard_custom_feed_output' ) ) {
	function dashboard_custom_feed_output() {
		echo '<div class="rss-widget rss-wplook">';
		wp_widget_rss_output(array(
			'url' => esc_url('http://feeds.feedburner.com/wplook'),
			'title' => '',
			'items' => 5,
			'show_summary' => 1,
			'show_author' => 0,
			'show_date' => 1
			));
		echo '</div>';
	}
}

if ( ! function_exists( 'wplook_bar_menu' ) ):
	function wplook_bar_menu() {
		global $wp_admin_bar;
		if ( !is_super_admin() || !is_admin_bar_showing() )
			return;
		$admin_dir = get_admin_url();
		$wp_admin_bar->add_menu(
			array(
				'id' => 'custom_menu',
				'title' => __( 'WPlook Panel', 'charity-wpl' ),
				'href' => FALSE,
				'meta' => array('title' => __('WPlook Options Panel', 'charity-wpl' ), 'class' => 'wplookpanel')
			)
		);
		$wp_admin_bar->add_menu(
			array(
				'id' => 'wpl_to',
				'parent' => 'custom_menu',
				'title' => __( 'Theme Options', 'charity-wpl' ),
				'href' => $admin_dir .'themes.php?page=ot-theme-options',
				'meta' => array('title' => __('Theme Option', 'charity-wpl' ) )
			)
		);
		$wp_admin_bar->add_menu(
			array(
				'id' => 'wpl_sp',
				'parent' => 'custom_menu',
				'title' => __( 'Support', 'charity-wpl' ),
				'href' => esc_url('https://wplook.com/docs/?utm_source=Support&utm_medium=link&utm_campaign=Charity'),
				'meta' => array('title' => __('Support', 'charity-wpl' ) )
			)
		);
		$wp_admin_bar->add_menu(
			array(
				'id' => 'wpl_wt',
				'parent' => 'custom_menu',
				'title' => __( 'Our Themes', 'charity-wpl' ),
				'href' => esc_url('https://wplook.com/wordpress/themes/?utm_source=Our-Themes&utm_medium=link&utm_campaign=Charity'),
				'meta' => array('title' => __('Our Themes', 'charity-wpl' ) )
				)
		);
		$wp_admin_bar->add_menu(
			array(
				'id' => 'wpl_fb',
				'parent' => 'custom_menu',
				'title' => __( 'Become our fan on Facebook', 'charity-wpl' ),
				'href' => esc_url('http://www.facebook.com/wplookthemes'),
				'meta' => array('target' => 'blank', 'title' => __('Become our fan on Facebook', 'charity-wpl' ) )
			)
		);
		$wp_admin_bar->add_menu(
			array(
				'id' => 'wpl_tw',
				'parent' => 'custom_menu',
				'title' => __( 'Follow us on Twitter', 'charity-wpl' ),
				'href' => esc_url('http://twitter.com/#!/wplook'),
				'meta' => array('target' => 'blank', 'title' => __('Follow us on Twitter', 'charity-wpl' ) )
			)
		);
	}
	add_action('admin_bar_menu', 'wplook_bar_menu', '1000');
endif;


/*-----------------------------------------------------------------------------------*/
/*	Manage columns for pledges
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_add_new_pledge_columns' ) ) {
	function wplook_add_new_pledge_columns($columns) {
		$columns = array(
			'cb' => '<input type="checkbox" />',
			'title' => __( 'Transaction ID', 'charity-wpl' ),
			'wpl_pledge_cause' => __( 'Cause', 'charity-wpl' ),
			'wpl_pledge_first_name' => __( 'First Name', 'charity-wpl' ),
			'wpl_pledge_last_name' => __( 'Last Name', 'charity-wpl' ),
			'wpl_pledge_donation_amount' => __( 'Donation amount', 'charity-wpl' ),
			'wpl_pledge_payment_source' => __( 'Payment Source', 'charity-wpl' ),
			'wpl_pledge_payment_Status' => __( 'Payment Status', 'charity-wpl' ),
			'date' => __( 'Date', 'charity-wpl' )
		);
	return $columns;
	}
	add_filter("manage_edit-post_pledges_columns", "wplook_add_new_pledge_columns");
	// Add to admin_init function
}
 if ( ! function_exists( 'wplook_pledge_columns' ) ) {
	function wplook_pledge_columns( $column, $post_id ) {

		switch ($column) {

			/*-----------------------------------------------------------
				Case: Cause
			-----------------------------------------------------------*/
			case 'wpl_pledge_cause' :
			$wpl_pledge_cause = get_post_meta( $post_id, 'wpl_pledge_cause', true );
			if ( empty( $wpl_pledge_cause ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				echo get_the_title( $wpl_pledge_cause );
			break;
			/*-----------------------------------------------------------
				Case: First Name
			-----------------------------------------------------------*/
			case 'wpl_pledge_first_name' :
			$wpl_pledge_first_name = get_post_meta( $post_id, 'wpl_pledge_first_name', true );
			if ( empty( $wpl_pledge_first_name ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( __( '%s', 'charity-wpl' ), $wpl_pledge_first_name );
			break;
			/*-----------------------------------------------------------
				Case: Last Name
			-----------------------------------------------------------*/
			case 'wpl_pledge_last_name' :
			$wpl_pledge_last_name = get_post_meta( $post_id, 'wpl_pledge_last_name', true );
			if ( empty( $wpl_pledge_last_name ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( __( '%s', 'charity-wpl' ), $wpl_pledge_last_name );
			break;

			/*-----------------------------------------------------------
				Case: Donation amount
			-----------------------------------------------------------*/
			case 'wpl_pledge_donation_amount' :
			$wpl_pledge_donation_amount = get_post_meta( $post_id, 'wpl_pledge_donation_amount', true );
			if ( empty( $wpl_pledge_donation_amount ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( __( '%s', 'charity-wpl' ), $wpl_pledge_donation_amount );
			break;
			/*-----------------------------------------------------------
				Case: Payment Source
			-----------------------------------------------------------*/
			case 'wpl_pledge_payment_source' :
			$wpl_pledge_payment_source = get_post_meta( $post_id, 'wpl_pledge_payment_source', true );
			if ( empty( $wpl_pledge_payment_source ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( __( '%s', 'charity-wpl' ), $wpl_pledge_payment_source );
			break;
			/*-----------------------------------------------------------
				Case: Payment Status
			-----------------------------------------------------------*/
			case 'wpl_pledge_payment_Status' :
			$wpl_pledge_payment_Status = get_post_meta( $post_id, 'wpl_pledge_payment_Status', true );
			if ( empty( $wpl_pledge_payment_Status ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( __( '%s', 'charity-wpl' ), $wpl_pledge_payment_Status );
			break;

		} // end switch
	}
	add_action('manage_post_pledges_posts_custom_column', 'wplook_pledge_columns', 10, 2);
}

// Make Pledge Columns Sortable

function wplook_pledge_sortable_columns( $columns ) {
	$columns['wpl_pledge_cause'] = 'wpl_pledge_cause';
	$columns['wpl_pledge_first_name'] = 'wpl_pledge_first_name';
	$columns['wpl_pledge_last_name'] = 'wpl_pledge_last_name';
	$columns['wpl_pledge_donation_amount'] = 'wpl_pledge_donation_amount';
	$columns['wpl_pledge_payment_source'] = 'wpl_pledge_payment_source';
	$columns['wpl_pledge_payment_Status'] = 'wpl_pledge_payment_Status';
	return $columns;
}
add_filter( 'manage_edit-post_pledges_sortable_columns', 'wplook_pledge_sortable_columns' );

function wplook_pledge_column_orderby( $vars ) {
	if ( isset( $vars['orderby'] ) && 'wpl_pledge_cause' == $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
			'meta_key' => 'wpl_pledge_cause',
			'orderby' => 'meta_value'
		) );
	}
	if ( isset( $vars['orderby'] ) && 'wpl_pledge_first_name' == $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
			'meta_key' => 'wpl_pledge_first_name',
			'orderby' => 'meta_value'
		) );
	}
	if ( isset( $vars['orderby'] ) && 'wpl_pledge_last_name' == $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
			'meta_key' => 'wpl_pledge_last_name',
			'orderby' => 'meta_value'
		) );
	}
	if ( isset( $vars['orderby'] ) && 'wpl_pledge_donation_amount' == $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
			'meta_key' => 'wpl_pledge_donation_amount',
			'orderby' => 'meta_value_num'
		) );
	}
	if ( isset( $vars['orderby'] ) && 'wpl_pledge_payment_source' == $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
			'meta_key' => 'wpl_pledge_payment_source',
			'orderby' => 'meta_value'
		) );
	}
	if ( isset( $vars['orderby'] ) && 'wpl_pledge_payment_Status' == $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
			'meta_key' => 'wpl_pledge_payment_Status',
			'orderby' => 'meta_value'
		) );
	}
    return $vars;
}
// Load only on edit.php
function wplook_pledge_load() {
	add_filter( 'request', 'wplook_pledge_column_orderby' );
}
add_action( 'load-edit.php', 'wplook_pledge_load' );


/*-----------------------------------------------------------------------------------*/
/*	Manage columns for Causes
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_add_new_causes_columns' ) ) {
	function wplook_add_new_causes_columns($columns) {
		$columns = array(
			'cb' => '<input type="checkbox" />',
			'title' => __( 'Title', 'charity-wpl' ),
			'wpl_goal_amount' => __( 'Goal Amount', 'charity-wpl' ),
			'date' => __( 'Date', 'charity-wpl' )
		);
	return $columns;
	}
	add_filter("manage_edit-post_causes_columns", "wplook_add_new_causes_columns");
}
if ( ! function_exists( 'wplook_causes_columns' ) ) {
	function wplook_causes_columns( $column, $post_id ) {

		switch ($column) {

			/*-----------------------------------------------------------
				causes: Goal Amount
			-----------------------------------------------------------*/
			case 'wpl_goal_amount' :
			$wpl_goal_amount = get_post_meta( $post_id, 'wpl_goal_amount', true );
			if ( empty( $wpl_goal_amount ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( __( '%s', 'charity-wpl' ), $wpl_goal_amount );
			break;

		} // end switch
	}
	add_action('manage_post_causes_posts_custom_column', 'wplook_causes_columns', 10, 2);
}

/*-----------------------------------------------------------------------------------*/
/*	Manage columns for Events
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'wplook_add_new_events_columns' ) ) {
	function wplook_add_new_events_columns($columns) {
		$columns = array(
			'cb' => '<input type="checkbox" />',
			'title' => __( 'Event name', 'charity-wpl' ),
			'wpl_event_date_time' => __( 'Date', 'charity-wpl' ),
			'wpl_event_address' => __( 'Address', 'charity-wpl' ),
		);
	return $columns;
	}
	add_filter("manage_edit-post_events_columns", "wplook_add_new_events_columns");
}
if ( ! function_exists( 'wplook_events_columns' ) ) {
	function wplook_events_columns( $column, $post_id ) {

		switch ($column) {
			/*-----------------------------------------------------------
				Events: Date Time
			-----------------------------------------------------------*/
			case 'wpl_event_date_time' :
			$wpl_event_date_time = get_post_meta( $post_id, 'wpl_event_date_time', true );
			if ( empty( $wpl_event_date_time ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( _x( '%1$s at %2$s', '[date] at [time]', 'charity-wpl' ), date( get_option( 'date_format' ), strtotime( $wpl_event_date_time ) ), date( get_option( 'time_format' ), strtotime( $wpl_event_date_time ) ) );
			break;

			/*-----------------------------------------------------------
				Events: Address
			-----------------------------------------------------------*/
			case 'wpl_event_address' :
			$wpl_event_address = get_post_meta( $post_id, 'wpl_event_address', true );
			if ( empty( $wpl_event_address ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( __( '%s', 'charity-wpl' ), $wpl_event_address );
			break;

		} // end switch
	}
	add_action('manage_post_events_posts_custom_column', 'wplook_events_columns', 10, 2);
}

/*-----------------------------------------------------------------------------------*/
/*	Manage columns for Documents
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'wplook_add_new_publications_columns' ) ) {

	function wplook_add_new_publications_columns($columns) {
		$columns = array(
			'cb' => '<input type="checkbox" />',
			'title' => __( 'Title', 'charity-wpl' ),
			'wpl_document_file_size' => __( 'File size', 'charity-wpl' ),
			'date' => __( 'Date', 'charity-wpl' )
		);
	return $columns;
	}
	add_filter("manage_edit-post_documents_columns", "wplook_add_new_publications_columns");
}
if ( ! function_exists( 'wplook_publications_columns' ) ) {

	function wplook_publications_columns( $column, $post_id ) {

		switch ($column) {

			case 'wpl_document_file_size' :
			$wpl_file_size = get_post_meta( $post_id, 'wpl_document_file_size', true );
			if ( empty( $wpl_file_size ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( __( '%s', 'charity-wpl' ), $wpl_file_size );
			break;

		} // end switch
	}
	add_action('manage_post_documents_posts_custom_column', 'wplook_publications_columns', 10, 2);
}
/*-----------------------------------------------------------------------------------*/
/*	Manage columns for Staff
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'wplook_add_new_staff_columns' ) ) {
	function wplook_add_new_staff_columns($columns) {
		$columns = array(
			'cb' => '<input type="checkbox" />',
			'title' => __( 'Name', 'charity-wpl' ),
			'wpl_candidate_position' => __( 'Position', 'charity-wpl' ),
			'date' => __( 'Date', 'charity-wpl' )
		);
	return $columns;
	}
	add_filter("manage_edit-post_staff_columns", "wplook_add_new_staff_columns");
}

if ( ! function_exists( 'wplook_staff_columns' ) ) {
	function wplook_staff_columns( $column, $post_id ) {

		switch ($column) {

			/*-----------------------------------------------------------
				Staff: Position
			-----------------------------------------------------------*/
			case 'wpl_candidate_position' :
			$wpl_candidate_position = get_post_meta( $post_id, 'wpl_candidate_position', true );
			if ( empty( $wpl_candidate_position ) )
				echo __( 'Unknown', 'charity-wpl' );
			else
				printf( __( '%s', 'charity-wpl' ), $wpl_candidate_position );
			break;

		} // end switch
	}
	add_action('manage_post_staff_posts_custom_column', 'wplook_staff_columns', 10, 2);
}

/*-----------------------------------------------------------------------------------*/
/*  Page Navi - Numeric pagination
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_pagination' ) ) {
	function wplook_pagination() {

	global $wp_query;
	global $page, $numpages, $multipage, $more;

		$big = 999999999; // need an unlikely integer
		$paginate_links = paginate_links(
			array(
				'base'         => str_replace( $big, '%#%', esc_url( get_pagenum_link($big) ) ),
				'format'       => '',
				'current'      => max( 1, get_query_var('paged') ),
				'total'        => $wp_query->max_num_pages,
				'prev_text'    => '<i class="fas fa-chevron-left"></i>',
				'next_text'    => '<i class="fas fa-chevron-right"></i>',
				'type'         => 'list',
				'end_size'     => 3,
				'mid_size'     => 3
			)
		);

		$paginate_links = str_replace( "<ul class='page-numbers'>", "<ul class='pagination'>", $paginate_links );
		$paginate_links = str_replace( '<li><span class="page-numbers dots">', "<li><a href='#'>", $paginate_links );
		$paginate_links = str_replace( "<li><span class='page-numbers current'>", "<li class='current'><a href='#'>", $paginate_links );
		$paginate_links = str_replace( "</span>", "</a>", $paginate_links );
		$paginate_links = str_replace( "<li><a href='#'>&hellip;</a></li>", "<li><span class='dots'>&hellip;</span></li>", $paginate_links );
		$paginate_links = preg_replace( "/\s*page-numbers/", "", $paginate_links );
		// Display the pagination if more than one page is found
		if ( $paginate_links ) {
			echo '<div class="pagination-centered">'.$paginate_links.'</div><!--// end .pagination -->';
		}
	}
}


/*-----------------------------------------------------------------------------------*/
/*	Return post format icon
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_postformat_icon' ) ) {
	function wplook_postformat_icon($postformat) {

		switch ($postformat) {
			case 'aside':
				$postformaticon = 'far fa-file-alt';
				break;
			case 'chat':
				$postformaticon = 'fab fa-weixin';
				break;
			case 'gallery':
			case 'image':
				$postformaticon = 'far fa-image';
				break;
			case 'link':
				$postformaticon = 'fas fa-link';
				break;
			case 'quote':
				$postformaticon = 'fas fa-quote-left';
				break;
			case 'status':
				$postformaticon = 'far fa-file-alt';
				break;
			case 'video':
				$postformaticon = 'fas fa-film';
				break;
			case 'audio':
				$postformaticon = 'far fa-file-audio';
				break;
			default:
				$postformaticon = 'far fa-file-alt';
		}
		return $postformaticon;
	}
}

/*-----------------------------------------------------------
	Custom Tag cloud Widget
-----------------------------------------------------------*/

if ( ! function_exists( 'wplook_tag_cloud_widget' ) ) {

	function wplook_tag_cloud_widget($args) {
		$args['largest'] = 12;
		$args['smallest'] = 12;
		$args['unit'] = 'px';
		return $args;
	}
	add_filter( 'widget_tag_cloud_args', 'wplook_tag_cloud_widget' );

}

/*-----------------------------------------------------------------------------------*/
/*	Doctitle
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'wplook_doctitle' ) ) {
	function wplook_doctitle() {
		if ( is_search() ) {
			$content = __('Search Results for:', 'charity-wpl');
			$content .= ' ' . esc_html(stripslashes(get_search_query()));
		}
		elseif ( is_category() ) {
			$content = __('Category Archives:', 'charity-wpl');
			$content .= ' ' . single_cat_title("", false);
		}
		elseif ( is_day() ) {
			$content = __( 'Daily Archives:', 'charity-wpl');
			$content .= ' ' . esc_html(stripslashes( get_the_date()));
		}

		elseif ( is_month() ) {
			$content = __( 'Monthly Archives:', 'charity-wpl');
			$content .= ' ' . esc_html(stripslashes( get_the_date( 'F Y' )));
		}
		elseif ( is_year()  ) {
			$content = __( 'Yearly Archives:', 'charity-wpl');
			$content .= ' ' . esc_html(stripslashes( get_the_date( 'Y' ) ));
		}

		elseif ( is_tag() ) {
			$content = __('Tag Archives:', 'charity-wpl');
			$content .= ' ' . single_tag_title( '', false );
		}
		elseif ( is_author() ) {
			$content = __("Author's Posts", 'charity-wpl');

		}

		elseif ( is_404() ) {
			$content = __('Not Found', 'charity-wpl');
		}

		else {
			$content = '';
		}

		$elements = array("content" => $content);
		// Filters should return an array
		$elements = apply_filters('wplook_doctitle', $elements);

		// But if they don't, it won't try to implode
			if(is_array($elements)) {
				$doctitle = implode(' ', $elements);
			} else {
				$doctitle = $elements;
			}
			if ( is_search() || is_category() || is_day() || is_month() || is_year() || is_404() || is_tag() || is_author() ) {
				$doctitle =  $doctitle;
			}
		echo esc_html($doctitle);
	}
}

/*-----------------------------------------------------------------------------------*/
/* [Function that return icon name depending on the file extension]
/* @param  [type] $file [file, or file patch]
/* @return [type]       [icon name]
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'wplook_get_icon_name' ) ) {
	function wplook_get_icon_name($file) {
		$ext = pathinfo($file, PATHINFO_EXTENSION);
		switch ($ext) {
		case "pdf":
			$icon_name = "far fa-file-pdf";
			break;
		case "zip":
		case "7z":
		case "rar":
		case "gz":
		case "gzip":
		case "tar":
			$icon_name = "far fa-file-archive";
			break;
		case "ppt":
		case "pptx":
			$icon_name = "far fa-file-powerpoint";
			break;
		case "doc":
		case "docx":
		case "odt":
			$icon_name = "far fa-file-word";
			break;
		case "xls":
		case "xla":
		case "xlt":
		case "xlw":
		case "xlsx":
		case "xlsb":
		case "xltx":
		case "xltm":
		case "xlam":
			$icon_name = "far fa-file-excel";
			break;
		case "gif":
		case "png":
		case "jpg":
		case "jpeg":
		case "jpe":
		case "tif":
		case "tiff":
		case "ico":
		case "bmp":
		case "tif":
			$icon_name = "far fa-image";
			break;
		case "pkg":
		case "prc":
		case "mobi":
		case "lit":
		case "azw3":
		case "azw":
		case "kf8":
		case "ibooks":
		case "fb2":
		case "pdb":
		case "epub":
		case "djvu":
			$icon_name = "fas fa-book";
			break;
		case "3gp":
		case "act":
		case "aiff":
		case "aac":
		case "amr":
		case "au":
		case "awb":
		case "dct":
		case "dss":
		case "dvf":
		case "flac":
		case "gsm":
		case "iklax":
		case "ivs":
		case "m4a":
		case "m4p":
		case "mmf":
		case "mp3":
		case "mpc":
		case "msv":
		case "ogg":
		case "oga":
		case "opus":
		case "ra":
		case "rm":
		case "raw":
		case "sln":
		case "tta":
		case "vox":
		case "wav":
		case "wma":
		case "wv":
		case "webm":
			$icon_name = "far fa-file-audio";
			break;
		default:
			$icon_name = "far fa-file-alt";
		}

		return $icon_name;
	}
}

/*-----------------------------------------------------------
	Breadcrumbs
-----------------------------------------------------------*/
if ( ! function_exists( 'wplook_breadcrumbs' ) ) {
	function wplook_breadcrumbs() {
		$showOnHome 		= '0'; // 1 - show breadcrumbs on the homepage, 0 - don't show
		$delimiter 			= ''; // delimiter between crumbs

		$showCurrent 		= '1'; // 1 - show current post/page title in breadcrumbs, 0 - don't show
		$before 			= '<li class="current">'; // tag before the current crumb
		$after 				= '</li>'; // tag after the current crumb

		$text['home'] 		= __('Home','charity-wpl'); // text for the 'Home' link
		$text['category']	= __('Archive for %s','charity-wpl'); // text for a category page
		$text['search']		= __('Search results for: %s','charity-wpl'); // text for a search results page
		$text['tag'] 		= __('Posts tagged %s','charity-wpl'); // text for a tag page
		$text['author'] 	= __('Posts by %s','charity-wpl'); // text for an author page
		$text['404'] 		= __('Error 404','charity-wpl'); // text for the 404 page

		global $post;
		$homeLink = esc_url( home_url( '/' ) );
		echo '<li><a href="' . $homeLink . '">' . $text['home'] . '</a></li> ' . $delimiter . ' ';
		if ( is_category() ) {
			global $wp_query;
			$cat_obj = $wp_query->get_queried_object();
			$thisCat = $cat_obj->term_id;
			$thisCat = get_category($thisCat);
			$parentCat = get_category($thisCat->parent);
			if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
			echo $before . sprintf($text['category'], single_cat_title('', false)) . $after;
		} elseif ( is_search() ) {
			echo $before . sprintf($text['search'], get_search_query()) . $after;
		} elseif ( is_day() ) {
			echo '<li><a href="' . esc_url(get_year_link(get_the_time('Y'))) . '">' . get_the_time('Y') . '</a></li> ' . $delimiter . ' ';
			echo '<li><a href="' . esc_url(get_month_link(get_the_time('Y'),get_the_time('m'))) . '">' . get_the_time('F') . '</a></li> ' . $delimiter . ' ';
			echo $before . get_the_time('d') . $after;
		} elseif ( is_month() ) {
			echo '<li><a href="' . esc_url(get_year_link(get_the_time('Y'))) . '">' . get_the_time('Y') . '</a></li> ' . $delimiter . ' ';
			echo $before . get_the_time('F') . $after;
		} elseif ( is_year() ) {
			echo $before . get_the_time('Y') . $after;
		} elseif ( (class_exists( 'WooCommerce' )) && is_shop() ) {
		//} elseif (function_exists('is_shop') ) {
			echo "<li class='current'>";
			echo __('Shop','charity-wpl');
			echo "</li>";
		} elseif ( is_singular( 'post_projects' ) ) {
			$page = ot_get_option( 'wpl_project_page' );
			$name = ot_get_option( 'wpl_projects_name_plural' );

			if( !empty( $page ) ) {
				echo '<li><a href="' . esc_url( get_page_link( $page ) ) . '">' . $name . '</a></li> ' . $delimiter . ' ';
			} else {
				echo '<span>' . __( 'Projects', 'charity-wpl' ) . '</span> ' . $delimiter . ' ';
			}

			if ($showCurrent == 1) echo $before . get_the_title() . $after;
		} elseif ( is_singular( 'post_documents' ) ) {
			$page = ot_get_option( 'wpl_documents_page' );
			$name = ot_get_option( 'wpl_documents_name_plural' );

			if( !empty( $page ) ) {
				echo '<li><a href="' . esc_url( get_page_link( $page ) ) . '">' . $name . '</a></li> ' . $delimiter . ' ';
			} else {
				echo '<span>' . __( 'Documents', 'charity-wpl' ) . '</span> ' . $delimiter . ' ';
			}

			if ($showCurrent == 1) echo $before . get_the_title() . $after;
		} elseif ( is_singular( 'post_staff' ) ) {
			$page = ot_get_option( 'wpl_staff_page' );
			$name = ot_get_option( 'wpl_staff_name_plural' );

			if( !empty( $page ) ) {
				echo '<li><a href="' . esc_url( get_page_link( $page ) ) . '">' . $name . '</a></li> ' . $delimiter . ' ';
			} else {
				echo '<span>' . __( 'Staff', 'charity-wpl' ) . '</span> ' . $delimiter . ' ';
			}

			if ($showCurrent == 1) echo $before . get_the_title() . $after;
		} elseif ( is_singular( 'post_gallery' ) ) {
			$page = ot_get_option( 'wpl_gallery_page' );
			$name = ot_get_option( 'wpl_gallery_name_plural' );

			if( !empty( $page ) ) {
				echo '<li><a href="' . esc_url( get_page_link( $page ) ) . '">' . $name . '</a></li> ' . $delimiter . ' ';
			} else {
				echo '<span>' . __( 'Gallery', 'charity-wpl' ) . '</span> ' . $delimiter . ' ';
			}

			if ($showCurrent == 1) echo $before . get_the_title() . $after;
		} elseif ( is_singular( 'post_events' ) ) {
			$page = ot_get_option( 'wpl_event_page' );
			$name = ot_get_option( 'wpl_events_name_singular' );

			if( !empty( $page ) ) {
				echo '<li><a href="' . esc_url( get_page_link( $page ) ) . '">' . $name . '</a></li> ' . $delimiter . ' ';
			} else {
				echo '<span>' . __( 'Events', 'charity-wpl' ) . '</span> ' . $delimiter . ' ';
			}

			if ($showCurrent == 1) echo $before . get_the_title() . $after;
		} elseif ( is_singular( 'post_causes' ) ) {
			$page = ot_get_option( 'wpl_cause_page' );
			$name = ot_get_option( 'wpl_causes_name_plural' );

			if( !empty( $page ) ) {
				echo '<li><a href="' . esc_url( get_page_link( $page ) ) . '">' . $name . '</a></li> ' . $delimiter . ' ';
			} else {
				echo '<span>' . __( 'Causes', 'charity-wpl' ) . '</span> ' . $delimiter . ' ';
			}

			if ($showCurrent == 1) echo $before . get_the_title() . $after;
		} elseif ( is_home() && !is_front_page() ) {
			echo "<li class='current'>";
			echo __('News','charity-wpl');
			echo "</li>";
		} elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) {
			$post_type = get_post_type_object(get_post_type());
			echo $before . $post_type->labels->name . $after;
		} elseif ( is_attachment() ) {
			$parent = get_post($post->post_parent);
			//$cat = get_the_category($parent->ID); $cat = $cat[0];
			//echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
			echo '<a href="' . esc_url(get_permalink($parent)) . '">' . $parent->post_title . '</a>';
			if ($showCurrent == 1) echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
		} elseif ( is_page() && !$post->post_parent ) {
			if ($showCurrent == 1) echo $before . get_the_title() . $after;
		} elseif ( is_page() && $post->post_parent ) {
			$parent_id  = $post->post_parent;
			$breadcrumbs = array();
			while ($parent_id) {
				$page = get_page($parent_id);
				$breadcrumbs[] = '<a href="' . esc_url(get_permalink($page->ID)) . '">' . get_the_title($page->ID) . '</a>';
				$parent_id  = $page->post_parent;
			}
			$breadcrumbs = array_reverse($breadcrumbs);
			for ($i = 0; $i < count($breadcrumbs); $i++) {
				echo $breadcrumbs[$i];
				if ($i != count($breadcrumbs)-1) echo ' ' . $delimiter . ' ';
			}
			if ($showCurrent == 1) echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
		} elseif ( is_tag() ) {
			echo $before . sprintf($text['tag'], single_tag_title('', false)) . $after;
		} elseif ( is_author() ) {
			global $author;
			$userdata = get_userdata($author);
			echo $before . sprintf($text['author'], $userdata->display_name) . $after;
		} elseif ( is_404() ) {
			echo $before . $text['404'] . $after;
		}
		// if ( get_query_var('paged') ) {
		// 	if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
		// 	echo ' ' . $delimiter . ' '; echo __('Page', 'charity-wpl') . ' ' . get_query_var('paged');
		// 	if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
		// }
	} // end breadcrumbs()
}

/*-----------------------------------------------------------
	Modify The Read More Link Text
-----------------------------------------------------------*/
function wplook_modify_read_more_link() {
	return '<div class="post-actions"><a class="button small" href="' . esc_url(get_permalink()) . '">'.__('Read More', 'charity-wpl').'</a></div>';
}
add_filter( 'the_content_more_link', 'wplook_modify_read_more_link' );

/*-----------------------------------------------------------
	 Replaces the excerpt "more" text by a link
-----------------------------------------------------------*/
function wplook_excerpt_more($more) {
    global $post;
    return '<div class="post-actions"><a class="button small" href="' . esc_url(get_permalink($post->ID)) . '">'.__('Read More', 'charity-wpl').'</a></div>';
}
add_filter('excerpt_more', 'wplook_excerpt_more');


/*	----------------------------------------------------------
	Post Like functionality
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = */

$wplook_time_before_revote = 0;

add_action('wp_ajax_nopriv_post-like', 'wplook_post_like');
add_action('wp_ajax_post-like', 'wplook_post_like');


if ( ! function_exists( 'wplook_post_like' ) ) {

	function wplook_post_like() {
		$nonce = $_POST['nonce'];

		if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
			die ( 'Busted!');

		if(isset($_POST['wplook_post_like'])) {
			$ip = $_SERVER['REMOTE_ADDR'];
			$post_id = $_POST['post_id'];

			$meta_IP = get_post_meta($post_id, "wplook_voted_IP");

			// BugFix by Rico Dupuis
			$wplook_voted_IP = array();
			if( is_array($meta_IP) && count($meta_IP))
				$wplook_voted_IP = $meta_IP[0];
			// END: BugFix

			$meta_count = get_post_meta($post_id, "votes_count", true);

			if(!wplook_has_already_voted($post_id)) {
				$wplook_voted_IP[$ip] = time();

				update_post_meta($post_id, "wplook_voted_IP", $wplook_voted_IP);
				update_post_meta($post_id, "votes_count", ++$meta_count);

				echo $meta_count;
			}
			else
				_e( 'already','charity-wpl');
		}
		exit;
	}

}

if ( ! function_exists( 'wplook_has_already_voted' ) ) {

	function wplook_has_already_voted($post_id) {
		global $wplook_time_before_revote;

		$meta_IP = get_post_meta($post_id, "wplook_voted_IP");

		if(isset($_POST['wplook_post_like'])) {
			// BugFix by Rico Dupuis
			$wplook_voted_IP = array();
			if( is_array($meta_IP) && count($meta_IP))
				$wplook_voted_IP = $meta_IP[0];
			// END: BugFix

			$ip = $_SERVER['REMOTE_ADDR'];

			if(in_array($ip, array_keys($wplook_voted_IP))) {
				$time = $wplook_voted_IP[$ip];
				$now = time();

				if(round(($now - $time) / 60) > $wplook_time_before_revote)
					return false;

				return true;
			}
		}
		return false;
	}
}

if ( ! function_exists( 'wplook_get_post_like' ) ) {

	function wplook_get_post_like($post_id) {
		$vote_count = get_post_meta($post_id, "votes_count", true);
		$vote_count = intval($vote_count);

		$output = '<li class="post-like">';
		if(wplook_has_already_voted($post_id))
			$output .= ' <i class="far fa-heart"></i> ';
		else
			$output .= '<a href="#" data-post_id="'.$post_id.'"><i class="far fa-heart"></i></a> ';

		$output .= '<span class="count">';

		if( $vote_count == 1 )
			$output .= $vote_count;
		elseif( $vote_count >= 2 )
			$output .= $vote_count;

		$output .= '</span></li>';

		return $output;
	}
}

/*------------------------------------------------------------
	Get Attachement image info
============================================================*/
if ( ! function_exists( 'wplook_get_attachment_info' ) ) {
	function wplook_get_attachment_info( $attachment_id ) {

		$attachment = get_post( $attachment_id );
		return array(
			'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
			'caption' => $attachment->post_excerpt,
			'description' => $attachment->post_content,
			'href' => get_permalink( $attachment->ID ),
			'src' => $attachment->guid,
			'title' => $attachment->post_title
		);
	}
}


/*-----------------------------------------------------------------------------------*/
/*  Return HTML for an icon picker
/*-----------------------------------------------------------------------------------*/

if( !function_exists( 'wplook_return_icon_picker' ) ) {

	function wplook_return_icon_picker( $field_choices = array(), $field_value, $location ) {

		ob_start();
		?>

			<div class="icon-picker <?php echo ( !empty( $location ) ? $location : 'plugin-location' ); ?>">
				<div class="icon-list">

					<?php foreach( $field_choices as $code => $name ) : ?>
						<div class="item <?php echo ( $code == $field_value ? 'selected' : '' ); ?>" data-code="<?php echo $code; ?>">
							<div class="item-wrapper">
								<div class="item-image">
									<i class="fa <?php echo $code; ?>"></i>
								</div>

								<span class="item-name"><?php echo $name; ?></span>
							</div>
						</div>
					<?php endforeach; ?>

				</div>

				<div class="show-more">
					<div class="background"></div>
					<button type="button" class="button show-more-button"><?php _e( 'Show all icons', 'charity-wpl' ); ?></button>
				</div>
			</div>

		<?php
		return ob_get_clean();

	}

}
