<?php
/**
 * @package WordPress
 * @subpackage Campoal
 */

global $campoal_options;
global $post;
global $current_user;
global $paged;

$supporter_per_page_setting = isset($campoal_options['conikal_supporter_per_page_field']) ? $campoal_options['conikal_supporter_per_page_field'] : '';
$supporter_per_page = $supporter_per_page_setting != '' ? $supporter_per_page_setting : 12;

$hidden_amount_contribute = isset($campoal_options['conikal_amount_contribute_field']) ? $campoal_options['conikal_amount_contribute_field'] : 0;

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$petition_id 	= isset($_GET['id']) ? sanitize_text_field($_GET['id']) : '';
$type 			= isset($_GET['type']) ? sanitize_text_field($_GET['type']) : 'supporter';

// get petition of update
$title 				= get_the_title($petition_id);
$link 				= get_permalink($petition_id);
$gallery 			= get_post_meta($petition_id, 'petition_gallery', true);
$images 			= conikal_get_gallery_images($gallery);
$thumb_id 			= get_post_thumbnail_id($petition_id);
$thumbnail 			= wp_get_attachment_image_src($thumb_id, 'thumbnail', true);
$thumbnail_small 	= wp_get_attachment_image_src($thumb_id, 'conikal-petition-small', true);
$thumb_placeholder 	= get_post_meta($petition_id, 'petition_thumb', true);
$thumb 				= get_post_meta($petition_id, 'petition_thumb_small', true);
$supporter_number 	= conikal_get_supporter_donors_number($petition_id);
$goal 				= $supporter_number->goal;
$sign_num 			= $supporter_number->sign;

$author_id 			= get_post_field('post_author', $petition_id);
$author_name 		= conikal_get_author_name($author_id);

// get form id
if (get_post_type($petition_id) == 'petition') {
    $form_id = get_post_meta($petition_id, 'petition_contribute', true);
    $contribute_approve = get_post_status($form_id);
    if ($contribute_approve === 'pending') {
        $form_id = '';
    }
} else {
    $form_id = $petition_id;
}

// get post thumbnail
$thumbnail_small = conikal_get_petition_thumbnail($petition_id, 'conikal-petition-small', 'thumbnail');

// lazy placeholder
$lazy_placeholder_avatar = conikal_lazy_load_placeholder('avatar');
$lazy_placeholder = conikal_lazy_load_placeholder('thumbnail');
?>

<div class="ui hidden divider"></div>

<div class="ui container">
		<div class="ui vertical basic segment">
			<h1 class="ui aligned header">
	            <div class="content">
	            	<?php if ($type === 'supporter') {
	            		echo sprintf($supporter_number->label, esc_html(conikal_format_number('%!,0i', $sign_num, true)));
	            	} elseif ($type === 'donor') {
						echo sprintf( _n('%s backer', '%s backers', give_get_form_sales_stats( $form_id ), 'campoal'), conikal_format_number('%!,0i', give_get_form_sales_stats( $form_id )) );
	            	} else {
	            		the_title();
	            	} ?>
	            </div>
	        </h1>
	    </div>
		<div class="ui hidden divider"></div>
		<div class="ui four column stackable grid">
		<?php
			$supporters = array();
			if ($type === 'supporter') {
				$supporters = get_post_meta($petition_id, 'petition_users', true);
				// check and remove user not exist
				foreach ($supporters as $user_id => $supporter) { 
					$user = get_userdata($user_id);
					if ($user === false) {
						// destroy a signature
						unset($supporters[$user_id]);
					}
				}
				// update signature then remove not exist user
				// update_post_meta($post_id->ID, 'petition_users', $supporters);

				// reverse array
                $supporters = array_reverse($supporters);
			} elseif (class_exists('Give')) {
				if(function_exists('give_get_payments')) {
	                $args = array(
	                	'status'     => 'publish',
	                    'give_forms' => array($form_id),
	                    'order' => 'DESC'
	                );
	                $donations = give_get_payments( $args );

	                foreach($donations as $donation) {
                        $customer_id = give_get_payment_donor_id( $donation->ID );
                        $customer    = new Give_Customer( $customer_id );
                        array_push($supporters, array('id' => $customer->id, 'user_id' => $customer->user_id, 'name' => $customer->name, 'payment_id' => $donation->ID));
                    }
	            }
			}

			// paination calulate
			$total = count( $supporters ); //total items in array    
			$limit = $supporter_per_page; //per page    
			$pages = ceil( $total / $limit ); //calculate total pages
			$paged = max($paged, 1); //get 1 page when $_GET['page'] <= 0
			$paged = min($paged, $pages); //get last page when $_GET['page'] > $totalPages
			$offset = ($paged - 1) * $limit;
			if( $offset < 0 ) $offset = 0;

			$supporters = array_slice( $supporters, $offset, $limit );

		    $current_user_follows = get_user_meta($current_user->ID, 'follow_user', true);
		    foreach ($supporters as $supporter) {
	        	$user 			= get_user_by('ID', $supporter['user_id']);
	        	$anonymous 		= isset($supporter['anonymous']) ? $supporter['anonymous'] : 0;
				$comment_id 	= isset($supporter['comment_id']) ? $supporter['comment_id'] : false;

	        	if ($type == 'donor') {
	        		$payment    			= new Give_Payment( $supporter['payment_id'] );
					$payment_date 			= strtotime($payment->date, current_time('timestamp'));
					$payment_date_format 	= date_i18n(get_option('date_format'), $payment_date);
					$payment_date_human		= sprintf(esc_html__('%s ago', 'campoal'), human_time_diff($payment_date, current_time('timestamp')));
					$payment_total			= give_format_amount($payment->total, array( 'sanitize' => false ));
					$payment_total_format 	= give_currency_filter(give_format_amount($payment->total, array( 'sanitize' => false )));
					$payment_gateway 		= give_get_gateway_admin_label(give_get_payment_gateway(  $payment->ID ));
	        	}

				$user_id = false;
				if ($user) {
	                $user_id 			= $user->ID;
	                $user_name 			= $user->display_name;
	                $user_link 			= get_author_posts_url($user_id);
	                $user_address 		= get_user_meta($user_id, 'user_address', true);
	                $user_neigborhood 	= get_user_meta($user_id, 'user_neigborhood', true);
	                $user_city 			= get_user_meta($user_id, 'user_city', true);
	                $user_state 		= get_user_meta($user_id, 'user_state', true);
	                $user_country 		= get_user_meta($user_id, 'user_country', true);
	                $user_avatar 		= conikal_get_avatar_url( $user_id, array('size' => 64) );
					$user_avatar_retina	= conikal_get_avatar_url( $user_id, array('size' => 128) );
				} else if ($type == 'donor') {
					$user_id 			= $supporter['id'];
					$user_name 			= $supporter['name'];
					$user_link 			= '';
					$user_address 		= '';
					$user_neigborhood 	= '';
					$user_city 			= '';
					$user_state 		= '';
					$user_country 		= '';
					$user_avatar 		= conikal_get_avatar_url( 0, array('size' => 64) );
					$user_avatar_retina	= conikal_get_avatar_url( 0, array('size' => 128) );
				}

	        	if ($user_id) {
		            if (!empty($anonymous)) {
		            	$user_avatar 		= conikal_get_avatar_url( 0, array('size' => 64) );
						$user_avatar_retina	= conikal_get_avatar_url( 0, array('size' => 128) );
		            	$user_name 			= esc_html__('Anonymous', 'campoal');
		            	$user_link 			= '#';
		            }

		            if (class_exists('Give') && function_exists('conikal_contribution_level_badge')) {
                        $level_badge = conikal_contribution_level_badge($user_id);
                    } else {
                        $level_badge = '';
                    }

					if ($user_country || $user_state || $user_city) { 
						$user_location = esc_attr($user_city ? $user_city . ', ' : '') . esc_attr($user_state ? $user_state . ', ' : '') . esc_attr($user_country ? $user_country : '');
					} else {
						$user_location 	= ($user) ? esc_html__('Somewhere', 'campoal') : esc_html__('Guest', 'campoal');
					}
	        	?>
	        	<div class="column">
			        <div class="ui fluid card supporter-card">
			            <div class="content">
			            	<a href="<?php echo esc_url($user_link) ?>" class="right floated ui mini image <?php echo esc_attr($level_badge) ?> mini">
			            		<img class="ui mini circular image lazy" data-src="<?php echo esc_url($user_avatar); ?>" data-retina="<?php echo esc_url($user_avatar_retina); ?>" src="<?php echo esc_url($lazy_placeholder_avatar); ?>" alt="<?php echo esc_attr($user_name) ?>" />
			            	</a>
			                <div class="header truncate">
				                <a href="<?php echo esc_url($user_link) ?>" class="header" data-bjax><?php echo esc_html($user_name) ?></a>
				            </div>
				            <div class="meta truncate">
								<?php echo esc_html($user_location) ?>
				            </div>
				            <div class="description supporter-comment">
				            	<?php 
				            		if ($type == 'supporter') {
				            			$sign_date 			= strtotime($supporter['date'], current_time('timestamp'));
										$sign_date_format 	= date_i18n(get_option('date_format'), $sign_date);
                						$sign_date_human 	= sprintf(esc_html__('%s ago', 'campoal'), human_time_diff($sign_date, current_time('timestamp')));
										$supporter_comment 	= (!empty($comment_id) ? get_comment($comment_id) : false); ?>

				            			<span class="sub header text grey">
											<?php echo esc_html($sign_date_human) ?> · 
										</span>

										<?php if (!empty($supporter_comment)) {
				           					echo esc_html($supporter_comment ? $supporter_comment->comment_content : '');
				            			} else {
											$subheading_label = sprintf(esc_html__('From %1$s signed this petition at %2$s', 'campoal'), $user_location, $sign_date_format);
											echo esc_html($subheading_label);
										} ?>
				            		<?php } else { 
				            			if ($hidden_amount_contribute == 1) { ?>
					            		<h4 class="ui primary small header">
										  	<?php echo esc_html($payment_total_format); ?>
										  	<div class="sub header text grey">
												<?php echo esc_html( sprintf(__('%1$s via %2$s', 'campoal'), $payment_date_human, $payment_gateway) ); ?>
											</div>
										</h4>
				            		<?php } else { ?>
				            		<h4 class="ui primary small header">
				            			<?php echo esc_html($payment_date_format); ?>
									  	<div class="sub header text grey">
										  <?php echo esc_html( sprintf(__('%1$s via %2$s', 'campoal'), $payment_date_human, $payment_gateway) ); ?>
										</div>
									</h4>
				            		<?php }
				            	} ?>
						    </div>
			            </div>
			            <div class="extra content">
					      	<?php if(is_user_logged_in()) {
			                    if($current_user_follows != '') {
			                        if(in_array($user_id, $current_user_follows) === false) { ?>
			                            <a href="javascript:void(0)" id="follow-page-<?php echo esc_attr($user_id) ?>" class="ui small basic fluid circular button follow-page follow" data-id="<?php echo esc_attr($user_id); ?>"><i class="plus icon"></i><?php esc_html_e('Follow', 'campoal') ?></a>
			                        <?php } else { ?>
			                            <a href="javascript:void(0)" id="follow-page-<?php echo esc_attr($user_id) ?>" class="ui small primary fluid circular button follow-page following" data-id="<?php echo esc_attr($user_id); ?>"><i class="checkmark user icon"></i><?php esc_html_e('Following', 'campoal') ?></a>
			                    <?php } 
			                        } else { ?>
			                        <a href="javascript:void(0)" id="follow-page-<?php echo esc_attr($user_id) ?>" class="ui small basic fluid circular button follow-page follow" data-id="<?php echo esc_attr($user_id); ?>"><i class="plus icon"></i><?php esc_html_e('Follow', 'campoal') ?></a>
			                    <?php }
			                } else { ?>
			                	<a href="javascript:void(0)" id="follow-page-<?php echo esc_attr($user_id) ?>" class="ui small basic fluid circular button signin-btn" data-id="<?php echo esc_attr($user_id); ?>"><i class="plus icon"></i><?php esc_html_e('Follow', 'campoal') ?></a>
			                <?php } ?>
					    </div>
			        </div>
			    </div>
		        <?php }
		    }
		?>
		</div>

		<!-- PAGINATION -->
		<div class="pagination">
			<div class="ui grid ">
				<div class="sixteen wide mobile ten wide tablet twelve wide computer column pagination-column-left">
	                <?php conikal_pagination($pages) ?>
	            </div>
	            <div class="sixteen wide mobile six wide tablet four wide computer right aligned column pagination-column-right">
	                <?php
	                    $per_p_setting = isset($campoal_options['conikal_supporter_per_page_field']) ? $campoal_options['conikal_supporter_per_page_field'] : '';
	                    $per_p = $per_p_setting != '' ? intval($per_p_setting) : 10;
	                    $page_no = (get_query_var('paged')) ? get_query_var('paged') : 1;

	                    $from_p = ($page_no == 1) ? 1 : $per_p * ($page_no - 1) + 1;
	                    $to_p = ($total - ($page_no - 1) * $per_p > $per_p) ? $per_p * $page_no : $total;
	                    echo esc_html($from_p) . ' - ' . esc_html($to_p) . ' ' . esc_html__('of', 'campoal') . ' ' . esc_html(conikal_format_number('%!,0i', $sign_num, true)) . esc_html__(' Supporters', 'campoal');
	                ?>
	            </div>
	        </div>
	    </div>
	</div>