<?php
/**
 * Shortcode functionality
 */

if ( ! defined( 'ABSPATH' ) ) {
	return;
}

add_action( 'init', 'giveasap_register_all_shortcodes' );

/**
 * Register Shortcodes with appropriate functions.
 *
 * @since 2.17.0
 * @since 2.18.1 Renamed to giveasap_register_all_shortcodes due to SendGrid having the same function.
 */
function giveasap_register_all_shortcodes() {
	add_shortcode( 'giveaway', 'giveasap_shortcode' );
	add_shortcode( 'giveaway_popup', 'giveasap_giveaway_popup_shortcode' );
	add_shortcode( 'giveaway_winners', 'giveasap_show_winners_shortcode' );
	add_shortcode( 'giveaway_leaderboard', 'giveasap_giveaway_leaderboard_shortcode' );
	add_shortcode( 'giveaway_archive', 'giveasap_giveaway_archive_shortcode' );

}

/**
 * Shortcode to show the Giveaway
 *
 * @param array $atts Attributes.
 *
 * @return string
 */
function giveasap_shortcode( $atts ) {
	$attributes = shortcode_atts(
		array(
			'id'                  => '0',
			'description'         => '',
			'title'               => '1',
			'redirect'            => 'self',
			'images'              => '0',
			'use_link'            => '1',
			'prizes'              => '1',
			'show_form'           => '1',
			'only_form'           => '0',
			'show_total_entries'  => '0',
			'show_entries'        => '0',
			'countdown_in_header' => '0',
			'hide_winners_number' => '0',
			'hide_prize_value'    => '0',
			'hide_prize_title'    => '0',
			'content'             => '0',
			'rules'               => '1',
		),
		$atts
	);

	if ( ! absint( $attributes['id'] ) ) {
		return '';
	}

	$post           = get_post( $attributes['id'] );
	$giveaway       = giveasap_get_giveaway( $post );

	if ( ! $giveaway ) {
		return '';
	}

	$prize          = $giveaway->get_prize_settings();
	$display        = false;
	$gasap          = gasap();
	$giveasap_front = new GiveASAP_Front( $post );
	$giveasap_ended = false;

	if ( absint( $attributes['images'] ) === 1 ) {
		$display = $giveaway->get_display_settings();
	}

	if ( $giveaway->has_ended() ) {
		$giveasap_ended = true;
	}

	$timezone          = get_option( 'gmt_offset' );
	$giveasap_settings = giveasap_get_settings();
	$current_page_url  = giveasap_get_current_page_url();

	if ( 'giveaway' !== $attributes['redirect'] ) {
		if ( 'self' === $attributes['redirect'] ) {
			$giveasap_front->set_from_page( $current_page_url );
		} elseif ( strpos( $attributes['redirect'], 'http' ) !== false ) {
			$giveasap_front->set_from_page( $attributes['redirect'] );
		}
	}

	$giveasap_front->set_share_url( $current_page_url );
	ob_start();
	$gasap->load_scripts( $giveasap_front );

	?>
	<div class="giveasap-box sg-shortcode">

		<?php
		if ( '1' !== $attributes['only_form'] ) {
			$meta_header = array();

			if ( '1' === $attributes['show_entries'] ) {
				$entries                = $giveasap_front->get_current_entries();
				$meta_header['entries'] = array(
					'class' => 'giveasap-entries',
					'icon'  => '',
					'text'  => '<strong>' . $entries . '</strong> ' . __( 'Your Entries', 'giveasap' ),
				);
			}

			if ( '1' === $attributes['show_total_entries'] ) {
				$total_entries                = $giveaway->get_total_entries();
				$meta_header['total_entries'] = array(
					'icon' => '',
					'text' => '<strong>' . $total_entries . '</strong> ' . __( 'Total Entries', 'giveasap' ),
				);
			}

			if ( '1' === $attributes['countdown_in_header'] ) {

				$end_time       = giveasap_get_end_time( $giveaway->get_id() );
				$current        = current_time( 'timestamp' );
				$value          = '';
				$countdown_icon = '';

				if ( $giveasap_ended ) {
					$value          = 'Ended';
					$countdown_icon = '<span class="fal fa-gift"></span>';
				} elseif ( absint( $current ) < absint( $end_time ) ) {
					$diff = $end_time - $current;

					if ( $diff >= DAY_IN_SECONDS ) {
						$value = '<strong>' . ceil( $diff / DAY_IN_SECONDS ) . '</strong> ' . _n( 'Day', 'Days', ceil( $diff / DAY_IN_SECONDS ), 'giveasap' );
					} elseif ( $diff >= HOUR_IN_SECONDS ) {
						$value = '<strong>' . ceil( $diff / HOUR_IN_SECONDS ) . '</strong> ' . _n( 'Hour', 'Hours', ceil( $diff / HOUR_IN_SECONDS ), 'giveasap' );
					} elseif ( $diff >= MINUTE_IN_SECONDS ) {
						$value = '<strong>' . ceil( $diff / MINUTE_IN_SECONDS ) . '</strong> ' . _n( 'Minute', 'Minutes', ceil( $diff / MINUTE_IN_SECONDS ), 'giveasap' );
					} else {
						$value = '<strong>' . $diff . '</strong> ' . _n( 'Second', 'Seconds', $diff, 'giveasap' );
					}
				}

				$meta_header['countdown'] = array(
					'icon' => $countdown_icon,
					'text' => $value,
				);
			}

			if ( '0' === $attributes['hide_winners_number'] ) {
				if ( isset( $prize['winners'] ) && $prize['winners'] ) {
					$meta_header['winners'] = array(
						'icon' => '<span class="fal fa-user-times"></span>',
						// translators: %s - number of winners.
						'text' => sprintf( _n( '%s <small>winner</small>', '%s <small>winners</small>', $prize['winners'], 'giveasap' ), number_format_i18n( $prize['winners'] ) ),
					);
				}
			}

			if ( '0' === $attributes['hide_prize_value'] ) {
				if ( isset( $prize['value'] ) && $prize['value'] ) {
					$meta_header['prize_value'] = array(
						'icon' => '<span class="fal fa-money-bill"></span>',
						'text' => '<small>' . esc_html__( 'Value:', 'giveasap' ) . '</small><div class="value">' . esc_html( $prize['value'] ) . '</div>',
					);
				}
			}

			if ( '0' === $attributes['hide_prize_title'] ) {
				if ( isset( $prize['prize'] ) && $prize['prize'] ) {
					$meta_header['prize'] = array(
						'icon' => '<span class="fal fa-gift"></span>',
						'text' => '<small>' . esc_html__( 'Prize:', 'giveasap' ) . '</small><div class="value">' . esc_html( $prize['prize'] ) . '</div>',
					);
				}
			}

			if ( $meta_header ) {
				?>
				<ul class="sg-meta sg-meta-prizes <?php echo esc_attr( 'sg-meta-items-' . count( $meta_header ) ); ?>">
					<?php
					foreach ( $meta_header as $meta ) {
						?>
							<li 
							<?php
							if ( isset( $meta['class'] ) && $meta['class'] ) {
								echo 'class="' . esc_attr( $meta['class'] ) . '"'; }
							?>
							>
							<?php
							if ( isset( $meta['icon'] ) && $meta['icon'] ) {
								echo wp_kses_post( $meta['icon'] );
							}
							?>
							<?php
							if ( isset( $meta['text'] ) && $meta['text'] ) {
								echo wp_kses_post( $meta['text'] );
							}
							?>
							</li>
							<?php
					}
					?>
				</ul>
				<?php
			}

			if ( '1' === $attributes['title'] ) {
				echo '<h2 class="sg-title">';

				if ( '1' === $attributes['use_link'] ) {
					echo '<a href="' . esc_url( $giveasap_front->get_form_link() ) . '">';
				}

				echo esc_html( $post->post_title );

				if ( '1' === $attributes['use_link'] ) {
					echo '</a>';
				}
				echo '</h2>';
			}

			if ( '' !== $attributes['description'] ) {
				echo '<p>' . wp_kses_post( apply_filters( 'giveasap_shortcode_description', $attributes['description'] ) ) . '</p>';
			}

			if ( '0' !== $attributes['content'] ) {
				giveasap_the_content( true, $post );
			}

			if ( '0' !== $attributes['prizes'] ) {
				giveasap_header_show_prizes( $giveaway );
			}

			if ( $display ) {
				the_giveasap_gallery( $display['images'] );
			}
		}

		if ( ! $giveasap_ended ) {

			if ( '1' !== $attributes['only_form'] ) {

				if ( '0' === $attributes['countdown_in_header'] ) {
					?>
					<div data-timezone="<?php echo esc_attr( $timezone ); ?>" data-end="<?php echo esc_attr( giveasap_get_end_time( $giveaway->get_id() ) ); ?>" class="giveasap_countdown">

					</div>
					<?php
				}
				if ( absint( $giveasap_front->get_step() ) === 1 ) {

					if ( $giveasap_settings['google_site_key'] ) {
						?>
						<script src='https://www.google.com/recaptcha/api.js'></script>
						<?php
					}
				} else {
					?>
				<h3 class="sg-participation-message"><?php esc_html_e( 'You are participating in this giveaway', 'giveasap' ); ?></h3>
					<?php
				}
			}

			if ( '0' !== $attributes['show_form'] ) {

				// Used to hide the entries.
				if ( '1' === $attributes['show_entries'] ) {
					add_filter( 'sg_giveaway_displaying_entries', '__return_false' );
				}

				giveasap_the_form( $giveasap_front, $giveasap_settings );

				if ( '1' === $attributes['show_entries'] ) {
					remove_filter( 'sg_giveaway_displaying_entries', '__return_false' );
				}
			}
			?>

		<?php } else { ?>
			<div class="giveasap_alert giveasap_ended">
				<?php esc_html_e( 'Ended', 'giveasap' ); ?>
			</div>
			<?php
			giveasap_show_winners( $giveaway->get_id() );

		}

			do_action( 'giveasap_box_shortcode_footer', $giveaway, $attributes, $giveasap_front, $giveasap_settings );
		?>

	</div>
	<?php

	$output = ob_get_clean();
	return $output;
}

/**
 * Show the winners in a shortcode.
 *
 * @since 2.17.0
 *
 * @param array $atts Shortcode Attributes.
 * @return string
 */
function giveasap_show_winners_shortcode( $atts ) {
	$attributes = shortcode_atts(
		array(
			'id' => 0,
		),
		$atts
	);

	if ( ! absint( $attributes['id'] ) ) {
		return '';
	}

	ob_start();
	giveasap_show_winners( absint( $attributes['id'] ), true );
	return ob_get_clean();
}


/**
 * Display Leaderboard
 *
 * @param array $atts Attributes.
 *
 * @return string
 */
function giveasap_giveaway_leaderboard_shortcode( $atts ) {
	$atts = shortcode_atts(
		array(
			'id'      => '',
			'limit'   => 10,
			'order'   => 'DESC',
			'orderby' => 'entries',
			'columns' => 'entries,email',
			'headers' => 'Entries,Email',
		),
		$atts
	);

	if ( ! $atts['id'] || absint( $atts['id'] ) <= 0 ) {
		return '';
	}

	$results = get_transient( 'giveaway_leaderboard_' . $atts['id'] );

	if ( false === $results ) {
		$results  = giveasap_get_active_entries_for( $atts['id'], $atts['limit'], $atts['order'], $atts['orderby'] );
		$_results = array_map( 'json_encode', $results );
		$results  = array();
		foreach ( $_results as $index => $result ) {
			$results[ $index ] = json_decode( $result, true );
		}
		if ( ! $results ) {
			return '';
		}

		foreach ( $results as $index => $result ) {
			$results[ $index ]['meta'] = get_metadata( 'giveasap', $result['id'] );
		}

		set_transient( 'giveaway_leaderboard_' . $atts['id'], $results, 12 * HOUR_IN_SECONDS );
	}

	$columns = explode( ',', $atts['columns'] );
	$headers = explode( ',', $atts['headers'] );
	if ( count( $headers ) !== count( $columns ) ) {
		$headers = array();
		foreach ( $columns as $column ) {
			$headers[] = $column;
		}
	}

	ob_start();
	?>

	<table class="giveaway-leaderboard">
		<thead>
		<tr>
			<th>#</th>
			<?php
			foreach ( $headers as $header ) {
				echo '<th>' . esc_html( $header ) . '</th>';
			}
			?>
		</tr>
		</thead>
		<tbody>
		<?php
		foreach ( $results as $index => $result ) {
			if ( $index >= $atts['limit'] ) {
				break;
			}
			?>
			<tr>
				<td><?php echo esc_html( $index + 1 ); ?></td>
				<?php
				foreach ( $columns as $column ) {
					echo '<td>';
					if ( isset( $result[ $column ] ) ) {
						if ( 'email' === $column ) {
							echo esc_html( giveasap_mask_email( $result[ $column ] ) );
						} else {
							echo esc_html( $result[ $column ] );
						}
					} elseif ( isset( $result['meta'][ $column ] ) ) {
						echo esc_html( $result['meta'][ $column ][0] );
					} elseif ( isset( $result['meta'][ '_' . $column ] ) ) {
						echo esc_html( $result['meta'][ '_' . $column ][0] );
					} else {
						echo '-';
					}
					echo '</td>';
				}
				?>
			</tr>
			<?php
		}
		?>
		</tbody>
	</table>
	<?php

	return ob_get_clean();
}

/**
 * Archive Shortcode to show giveaways.
 *
 * @param array $atts Attributes.
 */
function giveasap_giveaway_archive_shortcode( $atts ) {
	$page = isset( $_GET['sg_page'] ) ? absint( $_GET['sg_page'] ) : 1;
	if ( $page < 1 ) {
		$page = 1;
	}

	$status         = 'publish';
	$count_posts    = wp_count_posts( 'giveasap' );
	$total          = absint( $count_posts->publish );
	$posts_per_page = 6;

	if ( isset( $_GET['sg_archive_type'] ) && 'ended' === \Simple_Giveaways\Helpers::unslash_and_clean( $_GET['sg_archive_type'] ) ) {
		$status = [ 'giveasap_ended', 'giveasap_winners', 'giveasap_notified' ];
		$total  = absint( $count_posts->giveasap_ended ) + absint( $count_posts->giveasap_winners ) + absint( $count_posts->giveasap_notified );
	}

	$category = isset( $_GET['sg_category'] ) ? absint( $_GET['sg_category'] ) : 0;
    $hide_categories = false;
	$hide_statuses = false;

	if ( ! empty( $atts['category'] ) ) {
		$category = $atts['category'];
		$hide_categories = true;
	}

	if ( ! empty( $atts['status'] ) ) {
		$status = $atts['status'] === 'active' ? 'publish' : [ 'giveasap_ended', 'giveasap_winners', 'giveasap_notified' ];
		$total  = $atts['status'] === 'active' ? absint( $count_posts->publish ) : ( absint( $count_posts->giveasap_ended ) + absint( $count_posts->giveasap_winners ) + absint( $count_posts->giveasap_notified ) );
		$hide_statuses = true;
	}

	$query_atts = array(
		'paged'          => $page,
		'posts_per_page' => $posts_per_page,
		'post_status'    => $status,
	);

	if ( $category ) {
		$query_atts['tax_query']      = array(
			array(
				'taxonomy' => 'giveaway_category',
				'field'    => 'term_id',
				'terms'    => $category,
			),
		);
		$query_atts['posts_per_page'] = - 1;

		$term  = get_term( 1, 'giveaway_category' );
		$total = $term->count;
	}

	$giveaways = giveasap_get_giveaways( $query_atts );

	$total_pages = $posts_per_page > 0 ? ceil( $total / $posts_per_page ) : 1;

	ob_start();

	giveasap_get_template(
		'archive-giveaways.php',
		array(
			'giveaways'   => $giveaways,
			'total_pages' => $total_pages,
			'rules'       => empty( $atts['rules'] ) ? 1 : absint( $atts['rules'] ),
			'hide_categories' => $hide_categories,
			'hide_statuses' => $hide_statuses,
			'hide_form' => $hide_categories && $hide_statuses
		)
	);

	return ob_get_clean();
}

/**
 * Giveaway Popup Shortcode
 *
 * @param $atts
 */
function giveasap_giveaway_popup_shortcode( $atts ) {
	$attributes = shortcode_atts(
		array(
			'id'          => '0',
			'title'       => '1',
			'redirect'    => 'self',
			'images'      => '0',
			'prizes'      => '1',
			'content'     => '0',
			'rules'       => '1',
			'class'       => 'button',
			'button_text' => __( 'Show Giveaway', 'giveasap' ),
		),
		$atts
	);

	if ( ! absint( $attributes['id'] ) ) {
		return '';
	}

	$post           = get_post( $attributes['id'] );
	$giveaway       = giveasap_get_giveaway( $post );
	$display        = false;
	$gasap          = gasap();
	$giveasap_front = new GiveASAP_Front( $post );
	$giveasap_ended = false;

	if ( absint( $attributes['images'] ) === 1 ) {
		$display = $giveaway->get_display_settings();
	}

	if ( $giveaway->has_ended() ) {
		$giveasap_ended = true;
	}

	$giveasap_settings = giveasap_get_settings();
	$current_page_url  = giveasap_get_current_page_url();

	if ( 'giveaway' !== $attributes['redirect'] ) {
		if ( 'self' === $attributes['redirect'] ) {
			$giveasap_front->set_from_page( $current_page_url );
		} elseif ( strpos( $attributes['redirect'], 'http' ) !== false ) {
			$giveasap_front->set_from_page( $attributes['redirect'] );
		}
	}

	$giveasap_front->set_share_url( $current_page_url );

	ob_start();
	$gasap->load_scripts( $giveasap_front );

	?>
	<button type="button" data-giveaway-popup="<?php echo esc_attr( $attributes['id'] ); ?>" class="<?php echo esc_attr( $attributes['class'] ); ?>">
		<?php echo esc_html( $attributes['button_text'] ); ?>
	</button>
	<div class="sg-giveaway-popup" id="sg-giveaway-popup-<?php echo esc_attr( $attributes['id'] ); ?>">
		<div class="sg-giveaway-popup-overlay"></div>
		<div class="sg-giveaway-popup-container">

			<div class="giveasap-box sg-shortcode">
				<button type="button" class="sg-giveaway-popup-close" data-giveaway-popup="<?php echo esc_attr( $attributes['id'] ); ?>"><?php esc_html_e( 'Close', 'giveasap' ); ?></button>

				<?php

				$meta_header = array();

				$entries                = $giveasap_front->get_current_entries();
				$meta_header['entries'] = array(
					'class' => 'giveasap-entries',
					'icon'  => '',
					'text'  => '<strong>' . $entries . '</strong> ' . __( 'Your Entries', 'giveasap' ),
				);

				$total_entries                = $giveaway->get_total_entries();
				$meta_header['total_entries'] = array(
					'icon' => '',
					'text' => '<strong>' . $total_entries . '</strong> ' . __( 'Total Entries', 'giveasap' ),
				);

				$end_time = giveasap_get_end_time( $giveaway->get_id() );
				$current  = current_time( 'timestamp' );
				$value    = '';

				if ( $giveasap_ended ) {
					$value = '<strong>Ended</strong>';
				} elseif ( absint( $current ) < absint( $end_time ) ) {
					$diff = $end_time - $current;

					if ( $diff >= DAY_IN_SECONDS ) {
						$value = '<strong>' . ceil( $diff / DAY_IN_SECONDS ) . '</strong> ' . _n( 'Day', 'Days', ceil( $diff / DAY_IN_SECONDS ), 'giveasap' );
					} elseif ( $diff >= HOUR_IN_SECONDS ) {
						$value = '<strong>' . ceil( $diff / HOUR_IN_SECONDS ) . '</strong> ' . _n( 'Hour', 'Hours', ceil( $diff / HOUR_IN_SECONDS ), 'giveasap' );
					} elseif ( $diff >= MINUTE_IN_SECONDS ) {
						$value = '<strong>' . ceil( $diff / MINUTE_IN_SECONDS ) . '</strong> ' . _n( 'Minute', 'Minutes', ceil( $diff / MINUTE_IN_SECONDS ), 'giveasap' );
					} else {
						$value = '<strong>' . $diff . '</strong> ' . _n( 'Second', 'Seconds', $diff, 'giveasap' );
					}
				}

				$meta_header['countdown'] = array(
					'icon' => '',
					'text' => $value,
				);

				if ( $meta_header ) {
					?>
			<ul class="sg-meta sg-meta-prizes">
						<?php
						foreach ( $meta_header as $meta_header_slug => $meta ) {
							?>
					<li 
							<?php
							if ( isset( $meta['class'] ) && $meta['class'] ) {
								echo 'class="' . esc_attr( $meta['class'] ) . '"'; }
							?>
					>
							<?php
							if ( isset( $meta['icon'] ) && $meta['icon'] ) {
								echo wp_kses_post( $meta['icon'] ); }
							?>
							<?php
							if ( isset( $meta['text'] ) && $meta['text'] ) {
								echo wp_kses_post( $meta['text'] ); }
							?>
					</li>
							<?php
						}
						?>
			</ul>
					<?php
				}

				if ( '1' === $attributes['title'] ) {
					echo '<h2 class="sg-title">';

					if ( '1' === $attributes['use_link'] ) {
						echo '<a href="' . esc_url_raw( $giveasap_front->get_form_link() ) . '">';
					}

					echo esc_html( $post->post_title );

					if ( '1' === $attributes['use_link'] ) {
						echo '</a>';
					}
					echo '</h2>';
				}

				if ( '0' !== $attributes['content'] ) {
					giveasap_the_content( true, $post );
				}

				if ( '0' !== $attributes['prizes'] ) {
					giveasap_header_show_prizes( $giveaway );
				}

				if ( $display ) {
					the_giveasap_gallery( $display['images'] );
				}

				if ( ! $giveasap_ended ) {

					if ( absint( $giveasap_front->get_step() ) === 1 ) {

						if ( $giveasap_settings['google_site_key'] ) {
							?>
					<script src='https://www.google.com/recaptcha/api.js'></script>
							<?php
						}
					} else {
						?>
				<h3 class="sg-participation-message"><?php esc_html_e( 'You are participating in this giveaway', 'giveasap' ); ?></h3>
						<?php
					}

					// Used to hide the countdown.
					if ( '1' === $attributes['show_entries'] ) {
						add_filter( 'sg_giveaway_collecting_entries', '__return_false' );
					}
					giveasap_the_form( $giveasap_front, $giveasap_settings );
					if ( '1' === $attributes['show_entries'] ) {
						remove_filter( 'sg_giveaway_collecting_entries', '__return_false' );
					}
					?>

				<?php } else { ?>
			<div class="giveasap_alert giveasap_ended">
					<?php esc_html_e( 'Ended', 'giveasap' ); ?>
			</div>
					<?php
					giveasap_show_winners( $giveaway->get_id() );

				}

				do_action( 'giveasap_box_shortcode_footer', $giveaway, $attributes, $giveasap_front, $giveasap_settings );
				?>

	</div>
		</div>
	</div>
	<?php

	$output = ob_get_clean();
	return $output;
}
