<?php

add_action( 'wp_enqueue_scripts', 'bw_ty_download_assets' );
function bw_ty_download_assets () {
	wp_register_style( 'bw-tyd-style', get_stylesheet_directory_uri() . '/assets/css/bw-tyd.css', array(), '0.0.2' );
}

add_shortcode( 'bw_ty_download', 'bw_ty_download' );
function bw_ty_download( $atts ) {
	$atts = shortcode_atts( array(
		'field' => 'all',
	), $atts, 'bw_ty_download' );

	$lp_id = intval( $_GET['lp'] );

	if ( ! get_post_status( $lp_id ) ) {
		return '';
	}

	wp_enqueue_style( 'bw-tyd-style' );

	$url = get_field( 'download_url', $lp_id );

	ob_start();

	// download link image
	if ( $atts['field'] === 'all' || $atts['field'] === 'thumbnail' ) {

		$field_value = get_field( 'thumbnail', $lp_id );

		if ( ! empty( $field_value ) ) {
			if ( $url ) printf( '<a class="bw-tyd-image" href="%s" target="_blank">', $url );
			echo wp_get_attachment_image( $field_value, 'small' );
			if ($url) echo '</a>';
		}
	}

	if ( $atts['field'] === 'all' || $atts['field'] === 'heading' ) {

		$field_value = get_field( 'heading', $lp_id );
		echo "<h2 class=\"bw-tyd-heading\">{$field_value}</h2>";
	}

	if ( $atts['field'] === 'all' || $atts['field'] === 'subheading' ) {

		$field_value = get_field( 'subheading', $lp_id );
		echo "<h3 class=\"bw-tyd-subheading\">{$field_value}</h3>";
	}

	if ( $atts['field'] === 'all' || $atts['field'] === 'description' ) {
		echo '<div class="bw-twd-description">';
		the_field( 'description', $lp_id );
		echo '</div>';
	}

	// download link button
	if ( $atts['field'] === 'all' || $atts['field'] === 'button' ) {
		$field_value = get_field( 'button', $lp_id );

		if ( empty( $field_value ) ) {
			$field_value = 'Download Now!';
		}

		if ( ! empty( $url ) ) {
			printf( '<p><a class="bw-tyd-button" href="%s" target="_blank">%s</a></p>', $url, esc_html( $field_value ) );
		}
	}

	if ( $atts['field'] === 'all' || $atts['field'] === 'footer' ) {
		$field_value = get_field( 'footer', $lp_id );

		if ( ! empty( $field_value ) ) {
			printf( '<p class="bw-tyd-footer">%s</p>', esc_html( $field_value ) );
		}
	}

	if ( $atts['field'] === 'download_url' ) {
		echo $url;
	}

	return ob_get_clean();
}
