<?php
/**
 * Functions for getting values in templates
 */
if ( ! defined( 'ABSPATH' ) ) {
	return;
}

/**
 * Creating the gallery
 *
 * @param  array  $gallery_images Array of image ID's
 * @param  string $size           Image Size
 *
 * @return string                 HTML
 */
function the_giveasap_gallery( $gallery_images, $size = 'full' ) {
	if ( $gallery_images != '' ) {

		$gallery_images_array = explode( ',', $gallery_images );
		$content              = '<ul class="giveasap_gallery">';
		foreach ( $gallery_images_array as $image_id ) {

			$image = wp_get_attachment_image_src( $image_id, $size );
			$html  = '';
			if ( $image ) {
				$html = '<img src="' . $image[0] . '" />';
			}

			if ( $html == '' ) {
				continue;
			}

			$content .= '<li>';

			$content .= $html;

			$content .= '</li>';
		}

		$content .= '</ul>';
		echo $content;

	}
}

/**
 * Applying only the core WordPress the_content hooks for rendering content
 *
 * @param  boolean $echo If false, the the content will be returned
 *
 * @return mixed         Void if $echo true, string if $echo is false
 */
function giveasap_the_content( $echo = true, $post = null, $raw = false ) {
    $content = $raw && $post ? $post->post_content : get_the_content( '', false, $post );
	$content = apply_filters( 'giveasap_the_content', $content );
	if ( $echo ) {
		echo $content;
	} else {
		return $content;
	}
}

/**
 * Returning the first image of the gallery
 *
 * @param  string $gallery_images String of IDs separated by a comma
 *
 * @return string                 URL of the image
 */
function the_giveasap_first_gallery_image( $gallery_images ) {
	if ( $gallery_images != '' ) {

		$gallery_images_array = explode( ',', $gallery_images );
		$first_image          = $gallery_images_array[0];
		$image                = wp_get_attachment_image_src( $first_image, 'full' );

		return $image[0];
	}
}

/**
 * Getting the URL of the image
 *
 * @param  int    $image_id ID of the image
 * @param  string $size     Size of the image
 *
 * @return string            URL of the image
 */
function giveasap_get_image_url( $image_id, $size = 'full' ) {
	if ( ! is_numeric( $image_id ) ) {
		return false;
	}

	$image = wp_get_attachment_image_src( $image_id, $size );

	return $image[0];
}

/**
 * Displays an alert if a giveaway has ended
 *
 * @return void
 */
function giveasap_show_ended_alert() {
	echo '<div class="giveasap_alert giveasap_ended">';
	_e( 'Ended', 'giveasap' );
	echo '</div>';
}

/**
 * Display Winners for a giveaway
 *
 * @since 2.9.0
 *
 * @param integer $post_id Post ID. If empty, use global.
 * @param boolean $force If forced, it will still display the winners even if disabled in settings.
 */
function giveasap_show_winners( $post_id = 0, $force = false ) {
	if ( ! $post_id ) {
		global $post;
		$post_id = $post->ID;
	}

	$giveaway_status = get_post_status( $post_id );

	if ( 'giveasap_notified' === $giveaway_status || 'giveasap_winners' === $giveaway_status ) {
		$settings = giveasap_get_settings();
		if ( ! $force ) {
			$display_winners = isset( $settings['display_winners'] ) ? $settings['display_winners'] : '0';
			if ( '1' !== $display_winners ) {
				return false;
			}
		}
		$winners = giveasap_get_winners( $post_id );
		$show_points = isset( $settings['display_winners_points'] ) ? $settings['display_winners_points'] : '0';

		if ( $winners ) {
		    $fields        = sg_get_form_fields( $post_id );
		    $winner_fields = array();

		    foreach ( $fields as $field_key => $field ) {
                if ( isset( $field['winner'] ) && '1' === $field['winner'] ) {
                    $winner_fields[] = $field_key;
                }
            }
			echo '<div class="giveasap_alert giveasap_winners">';
			echo '<p>' . _n( 'Winner', 'Winners', count( $winners ), 'giveasap' ) . '</p>';
			echo '<ul>';
			foreach ( $winners as $winner ) {

			    $name = '';
			    if ( $winner_fields ) {
			        $_name = array();
                    foreach ( $winner_fields as $winner_field ) {

	                    if ( 'user_email' === $winner_field ) {
		                    $field_value = $winner['email'];
		                    $field_value = sg_mask_email( $field_value );
	                    } else {
		                    $field_value = giveasap_get_meta( $winner['id'], '_' . $winner_field, true );
                        }

	                    if ( ! $field_value ) {
	                        continue;
                        }

                        $_name[] = $field_value;
                    }

                    if ( $_name ) {
	                    $_name = array_values( $_name );
	                    $name  = implode( ', ', $_name );
                    }
                }

                // If we stil don't have a name.
                if ( ! $name ) {
				    $user_id = giveasap_get_meta( $winner['id'], 'user_id', true );
				    $f_name  = giveasap_get_meta( $winner['id'], '_user_name', true );
				    $name    = $f_name ? $f_name : $winner['email'];

				    if ( ! $f_name ) {
					    // Let's mask the email.
					    $name = sg_mask_email( $name );
				    }

				    if ( $user_id ) {
					    $user = get_userdata( $user_id );
					    $name = $user->display_name ? $user->display_name : $name;
				    }
                }

				if ( '1' === $show_points ) {
				    $subscriber = giveasap_get_user_by_id( $winner['id'] );
				    if ( $subscriber ) {
				        $name .= ' (' . $subscriber->entries . ')';
                    }
                }

				$name = apply_filters( 'sg_show_winner_name', $name, $winner );

				echo '<li>' . $name . '</li>';
			}
			echo '</ul>';
			echo '</div>';
		}
	}
}

/**
 * Displaying the Logo with the link
 *
 * @since 2.9.0
 *
 * @param array $settings Display Settings.
 */
function giveasap_show_logo( $settings ) {
	if ( isset( $settings['logo'] ) && $settings['logo'] != '' ) {
		$image_url = giveasap_get_image_url( $settings['logo'] );
		$logo_link = isset( $settings['logo_link'] ) ? $settings['logo_link'] : '';

		echo '<div class="giveasap_logo_container">';

		if ( $logo_link ) {
			if ( false === strpos( $logo_link, 'http' ) ) {
				$logo_link = 'http://' . $logo_link;
			}
			echo '<a target="_blank" href="' . $logo_link . '">';
		}

		echo '<img class="giveasap_logo" src="' . $image_url . '" title="Logo" />';

		if ( $logo_link ) {
			echo '</a>';
		}

		echo '</div>';
	}
}

/**
 * Edit Form for a Subscriber.
 *
 * @param GiveASAP_Front $giveasap_front
 * @param $giveasap_settings
 */
function sg_subscriber_edit_form( $giveasap_front ) {
    $giveaway   = $giveasap_front->get_giveaway();
    $subscriber = $giveasap_front->get_subscriber();
    $settings   = giveasap_get_settings();
	$fields     = sg_get_form_fields( $giveaway->get_id() );
	$hideForm   = true;

	if ( $fields ) {
		foreach( $fields as $field_name => $field ) {
			if ( 'user_email' === $field['name'] ) {
				$field['value'] = $subscriber->get_email();
				$field['disabled'] = 1;
			} else {
				$field['value'] = $subscriber->get_meta( '_' . $field['name'] );
			}
			if (
                isset( $field['required'] )
                && (bool) $field['required']
                && ( null === $field['value'] || '' === $field['value'] )
            ) {
			    $hideForm = false;
				$giveasap_front->add_error( 'field-required', sprintf( __( 'Field %s is required'), $field['label'] ) );
            }
			$fields[ $field_name ] = $field;
		}
	}

	$allow_edit = isset( $settings['allow_subscriber_edit'] ) ? absint( $settings['allow_subscriber_edit'] ) : 0;
	// If we don't allow to edit form and the we have all required fields. We don't show it.
	if ( $hideForm && ! $allow_edit ) {
	    return;
    }

    ?>
    <div class="sg-subscriber-edit-data">
        <p>
            <?php echo sprintf( __( 'Subscribed as: %s', 'giveasap' ), $subscriber->get_email() ); ?>.
            <?php if ( $hideForm ) { ?>
                <button type="button"
                        class="sg-button-link sg-toggle"
                        data-text="<?php esc_attr_e( 'Hide Details', 'giveasap' ); ?>"
                        data-target="#giveasap_subscribe_form"
                        data-class="sg-hidden">
                    <?php esc_html_e( 'Edit Details', 'giveasap' ); ?>
                </button>
            <?php } ?>
        </p>
        <?php
        $giveasap_front->show_successes();
        $giveasap_front->show_errors();
        $giveasap_front->show_notices();
        ?>
	    <form id="giveasap_subscribe_form" class="giveasap_form <?php echo $hideForm ? 'sg-hidden' : ''; ?>" method="post">
        <input type="hidden" name="sg_giveaway_id" value="<?php echo esc_attr( $giveaway->get_id() ); ?>" />
        <input type="hidden" name="sg_giveaway_subscriber" value="<?php echo esc_attr( $subscriber->get_id() ); ?>" />
		<?php

            if ( $fields ) {
                foreach( $fields as $field ) {
                    sg_render_form_field( $field );
                }
            }

            do_action( 'sg_form_edit_before_button', $giveasap_front );
            wp_nonce_field( 'sg_form_edit_' . $subscriber->get_id(), 'sg_form_edit_nonce' );
        ?>
        <button type="submit" class="giveasap_button"
            name="giveasap_edit">
            <?php _e( 'Update', 'giveasap' ); ?>
        </button>

    </form>
    </div>
    <?php
}

/**
 * Displaying the Form
 *
 * @param  GiveASAP_Front $giveasap_front
 * @param  array          $giveasap_settings
 *
 * @return void
 */
function giveasap_the_form( $giveasap_front, $giveasap_settings ) {
	$giveaway = $giveasap_front->get_giveaway();

	if ( ! $giveaway->showing_subscriber_page() || $giveasap_front->get_step() == 1 ) {

	    if ( $giveaway->has_started() ) {
		    /**
		     * @since  2.5.0
		     */
		    do_action( 'giveasap_form_before', $giveasap_front, $giveasap_settings );

		    if ( $giveaway->is_open_to_subscribe() ) {
			    ?>
                <form id="giveasap_subscribe_form" class="giveasap_form"
                      action="<?php echo $giveasap_front->get_form_link(); ?>" method="post">
                    <input type="hidden" name="sg_giveaway_id" value="<?php echo esc_attr( $giveaway->get_id() ); ?>" />
                    <input type="hidden" name="sg_giveaway_type" value="<?php echo esc_attr( $giveaway->get_type() ); ?>" />

                    <?php
                    if ( $giveasap_front->get_from_page() ) {
                        ?>
                        <input type="hidden" name="sg_from_page" value="<?php echo esc_attr( $giveasap_front->get_from_page() ); ?>" />
                    <?php
                    }
                    ?>
				    <?php if ( $giveasap_front->shareID != 0 ) { ?>
                        <input type="hidden" name="user_share" value="<?php echo $giveasap_front->shareID; ?>"/>
				    <?php }

				    if ( isset( $_GET['method'] ) && '' !== $_GET['method'] ) {
					    ?>
                        <input type="hidden" name="sg_sharing_method" value="<?php echo $_GET['method']; ?>"/>
					    <?php
				    }

				    $giveasap_front->show_errors();
				    $giveasap_front->show_notices();
				    $giveasap_front->show_successes();

				    /**
				     * Checking if a user is already logged in to use their email list
				     *
				     * @since  2.5.0
				     */
				    $current_user = wp_get_current_user();

				    /**
				     * @since  2.8.0
				     */
				    do_action( 'giveasap_form_before_default', $giveasap_front, $giveasap_settings, $current_user );

				    $fields = sg_get_form_fields( $giveaway->get_id() );

                    if ( $fields ) {
                        foreach( $fields as $field ) {
                            if ( $current_user->ID ) {
                                if ( 'user_name' === $field['name'] ) {
	                                $field['value'] = $current_user->get( 'first_name' );
                                } else {
	                                $field['value'] = $current_user->get( $field['name'] );
                                }

                                if ( 'user_email' === $field['name'] ) {
                                    $field['disabled'] = true;
                                }
                            }
                            sg_render_form_field( $field );
                        }
                    }

				    if ( ! $current_user->ID ) {
					     if ( $giveasap_settings['google_site_key'] ) { ?>
                            <div class="g-recaptcha"
                                 data-sitekey="<?php echo $giveasap_settings['google_site_key']; ?>"></div>
                             <?php
					     }
				    }

				    do_action( 'sg_form_before_button', $giveasap_front, $giveasap_settings, $current_user );

				    if ( sg_is_gdpr_active() ) { ?>
                        <label for="giveasap_consent" class="giveasap_consent">
                            <input type="checkbox" required="required" value="1" name="giveasap_consent"
                                   id="giveasap_consent">
						    <?php
						    $consent_text = isset( $giveasap_settings['gdpr_consent'] ) ? $giveasap_settings['gdpr_consent'] : __( 'By signing up, you are agreeing to Terms & Conditions and our Privacy Policy.', 'giveasap' );
						    echo wp_kses( $consent_text, array('a' => array( 'href' => true, 'target' => true )), '' );
						    ?>

                        </label>
				    <?php } ?>
                    <button type="submit" class="giveasap_button"
                            name="giveasap_submit"><?php _e( 'Enter', 'giveasap' ); ?></button>
				    <?php
				    if ( is_singular( 'giveasap' ) ) {
					    ?>
                        <button type="button" class="giveasap_button transparent center"
                                id="giveasap_request_link"><?php _e( 'Forgot your subscribed link?', 'giveasap' ); ?></button>
					    <?php
				    }
				    ?>
                </form>

			    <?php
		    } else {
			    $message = $giveaway->get_not_open_reason();
			    if ( $message ) {
				    echo '<div class="giveasap_form">';
				    echo '<p class="giveasap_error">' . $message . '</p>';
				    echo '</div>';
			    }
		    }

		    if ( is_singular( 'giveasap' ) ) {
			    ?>
                <form id="giveasap_request_link_form" class="giveasap_form hidden" action="" method="post">
                    <div class="sg-form-field">
                        <label for="sg_request_email"><?php esc_html_e( 'Email', 'giveasap' ); ?></label>
                        <input required="required" class="giveasap_input" id="sg_request_email" type="email" name="request_email" value=""
                               placeholder="<?php _e( 'Enter your email', 'giveasap' ); ?>"/>
                    </div>
                    <button type="submit" class="giveasap_button"
                            name="giveasap_request_link"><?php _e( 'Get Link', 'giveasap' ); ?></button>

                </form>
			    <?php
		    }

		    /**
		     * @since  2.5.0
		     */
		    do_action( 'giveasap_form_after', $giveasap_front, $giveasap_settings );
	    } else {
		    echo '<div class="giveasap_form">';
		    echo '<p>' . esc_html__( 'Giveaway has not started yet.', 'giveasap' ) . '</p>';
		    echo '</div>';
        }
    }

	if ( $giveaway->showing_subscriber_page() && $giveasap_front->get_step() == 2 ) {

		sg_subscriber_edit_form( $giveasap_front );

		if ( $giveaway->is_collecting_entries() ) {
			?>
            <p class="giveasap-entries">
				<?php _e( 'Your Current Entries:', 'giveasap' ); ?>
                <strong><?php $giveasap_front->current_entries(); ?></strong>
            </p>
			<?php
		}

		if ( giveasap_is_activation_required() ) {
			if ( $giveasap_front->user->status  === 'pending' ) {
				echo '<div class="giveasap_form">';
				echo '<p class="giveasap_error">' . esc_html__( 'You have to activate your Account to have a chance in winning. The link should be in the email.', 'giveasap' ) . '</p>';
				echo '</div>';
			}

			if ( $giveasap_front->user->status === 'active' && isset( $_GET['activate'] ) && $_GET['activate'] ) {
				echo '<div class="giveasap_form">';
				echo '<p class="giveasap_success">' . esc_html__( 'Account Activated.', 'giveasap' ) . '</p>';
				echo '</div>';
			}
		}


        do_action( 'giveasap_the_form_end', $giveasap_front, $giveasap_settings );
    }
}

add_action( 'giveasap_the_form_end', 'sg_display_sharing_methods', 10 );

/**
 * Display Sharing Methods
 * @param GiveASAP_Front $giveasap_front
 *
 * @since 2.32.0
 */
function sg_display_sharing_methods( $giveasap_front ) {
    $giveaway = $giveasap_front->get_giveaway();
	if ( $giveaway->is_collecting_entries() ) {
		$giveasap_front->render_sharing_methods();
	}
}

add_action( 'giveasap_form_before', 'giveasap_form_before_conditionals', 20, 2 );

/**
 * Showing conditionals before the form
 *
 * @since  2.5.0
 *
 * @param  GiveASAP_Front $giveasap_front
 * @param  array          $giveasap_settings
 *
 * @return void
 */
function giveasap_form_before_conditionals( $giveasap_front, $giveasap_settings ) {

	$conditions = isset( $giveasap_settings['text_conditions'] ) ? $giveasap_settings['text_conditions'] : false;

	if ( $conditions ) {
		$count = giveasap_get_subscribed_count( $giveasap_front->get_giveaway_id() );

		$after = isset( $conditions[0] ) ? $conditions[0] : false;

		if ( $after && isset( $after['text'] ) && '' !== $after['text'] ) {
			$after_count = intval( $after['number'] );

			if ( $count >= $after_count ) {
				$text = str_replace( '{{count}}', $count, $after['text'] );

				if ( $text ) {
					echo '<p class="giveasap-p">' . $text . '</p>';
				}

				return;
			}
		}

		do_action( 'giveasap_form_before_conditionals', $conditions, $count );

	}
}

/**
 * Display the Simple Giveaway Meta Info
 *
 * @since 2.12.0
 *
 * @param array $options Array of meta info.
 */
function sg_show_meta_info( $options = array() ) {
	if ( ( isset( $options['winners'] ) && $options['winners'] )
	     || ( isset( $options['value'] ) && $options['value'] )
	) {
		?>
        <ul class="giveasap_meta">
			<?php
			if ( isset( $options['winners'] ) && $options['winners'] ) {
				?>
                <li class="person">
                    <span class="fal fa-user-times"></span>
					<?php echo sprintf( _n( '%s <small>winner</small>', '%s <small>winners</small>', $options["winners"], 'giveasap' ), number_format_i18n( $options["winners"] ) ); ?>
                </li>
			<?php } ?>
			<?php
			if ( isset( $options['value'] ) && $options['value'] ) {
				?>
                <li class="value">
                    <span class="fal fa-money-bill"></span>
                    <small><?php _e( 'Value:', 'giveasap' ); ?></small>
					<?php echo $options["value"]; ?>
                </li>
			<?php } ?>
        </ul>
		<?php
	}
	if ( isset( $options['prize'] ) && '' !== $options['prize'] ) {
		?>

        <ul class="giveasap_meta">
            <li class="value">
                <span class="fal fa-gift"></span>
                <small><?php _e( 'Prize:', 'giveasap' ); ?></small>
				<?php echo $options["prize"]; ?>
            </li>
        </ul>
		<?php
	}
}

add_action( 'sg_box_header', 'sg_header', 20, 2 );

/**
 * Displaying the header
 *
 * @param SG_Giveaway    $giveaway
 * @param GiveASAP_Front $front
 */
function sg_header( $giveaway, $front ) {
    $step = $front->get_step();

    $content = giveasap_the_content( false, $giveaway->get_post(), true );
	$content = get_extended( $content );
    $use_hide_button = apply_filters( 'sg_use_content_hide_button', $content['extended'] !== '' );
    ?>
    <header class="giveasap_section <?php if ( ! $use_hide_button ) { echo esc_attr('shown'); } ?>">
        <h1><?php the_title(); ?></h1>
		<?php echo $content['main']; ?>
        <?php
            if ( $use_hide_button && 2 === $step ) {
                echo '<div class="sg-content-extended">';
	            echo $content['extended'];
	            echo '</div>';
	            ?>
                <button
                        type="button"
                        class="sg-button sg-toggle"
                        data-target="header.giveasap_section"
                        data-class="shown"
                        data-text="<?php esc_attr_e( 'Hide the content', 'giveasap' ); ?>">
                    <?php esc_html_e( 'Show the content', 'giveasap' ); ?>
                </button>
                <?php
            } else {
	            echo $content['extended'];
            }
        ?>
    </header>
    <?php
}



add_action( 'sg_box_header', 'sg_header_show_prizes', 20 );

/**
 * Display the prizes
 *
 * @param SG_Giveaway $giveaway
 */
function sg_header_show_prizes( $giveaway ) {
    $prize_settings = $giveaway->get_prize_settings();
    $prizes         = isset( $prize_settings['prizes'] ) ? $prize_settings['prizes'] : array();
	$prizes_layout  = isset( $prize_settings['prizes_layout'] ) ? $prize_settings['prizes_layout'] : 'slider';

    if ( ! $prizes ) {
        return;
    }

    ?>
    <div class="sg-giveaway-prizes sg-giveaway-prizes-<?php echo esc_attr( $prizes_layout ); ?>">
        <?php
        foreach ( $prizes as $prize ) {
            ?>
            <div class="sg-giveaway-prize">
                <h3 class="sg-giveaway-prize-title"><?php echo esc_html( $prize['title'] ); ?></h3>
                <?php if ( isset( $prize['value'] ) && $prize['value'] ) { ?>
                <p class="sg-giveaway-prize-text sg-giveaway-prize-value"><strong><?php echo esc_html( $prize['value'] ); ?></strong></p>
                <?php } ?>
	            <?php if ( isset( $prize['desc'] ) && $prize['desc'] ) { ?>
                <p class="sg-giveaway-prize-text"><?php echo esc_html( $prize['desc'] ); ?></p>
                <?php } ?>
                <?php
                    if ( $prize['image'] ) {
                        echo wp_get_attachment_image( $prize['image'], 'large' );
                    }
                ?>
            </div>
            <?php
        }
        ?>
    </div>
    <?php
}


add_action( 'sg_box_header', 'sg_header_show_message_per_type', 22, 2 );

/**
 * Show a message per type under the header
 *
 * @param $giveaway
 * @param $front
 */
function sg_header_show_message_per_type( $giveaway, $front ) {
    if ( $giveaway->get_header_message( $front ) ) {
        echo '<div class="giveasap_header_message giveasap_notice">' . esc_html( $giveaway->get_header_message( $front ) ) . '</div>';
    }
}

add_filter( 'sg_render_form_field_atts', 'sg_form_field_to_hidden_for_logged_in', 20, 2 );

/**
 * Transforming form fields for hidden that can be filled with user data.
 *
 * @since 2.16.0
 *
 * @param array $atts
 * @param array $field
 */
function sg_form_field_to_hidden_for_logged_in( $atts, $field ) {
    if ( isset( $field['slug'] ) && 'user_email' === $field['slug'] ) {
        $current_user = wp_get_current_user();
        if ( $current_user->ID ) {
	        $atts['type']  = 'hidden';
	        $atts['value'] = $current_user->get( 'user_email' );
        }
    }

	if ( isset( $field['slug'] ) && 'user_name' === $field['slug'] ) {
		$current_user = wp_get_current_user();
		if ( $current_user->ID ) {
			$atts['type']  = 'hidden';
			$atts['value'] = $current_user->get( 'user_firstname' );
		}
	}

    return $atts;
}

/**
 * Return default form fields.
 * @return array
 */
function sg_get_default_form_fields() {
    $fields = array(
	    array(
		    'label'    => __( 'Email', 'giveasap' ),
		    'name'     => 'user_email',
		    'required' => '1',
            'readonly' => true
	    )
    );

    return apply_filters( 'sg_default_form_fields', $fields );
}
/**
 * Return Form Fields.
 *
 * @since 2.16.0
 * @since 2.19.0 - Added Giveaway ID parameter.
 *
 * @param integer $giveaway_id Giveaway ID.
 *
 * @return array
 */
function sg_get_form_fields( $giveaway_id = 0 ) {
    $settings    = giveasap_get_settings();
    $form_fields = isset( $settings['form_fields'] ) ? $settings['form_fields'] : sg_get_default_form_fields();

    /**
     * Filtering forms fields so others can extend it.
     *
     * @since 2.19.0 - Passing $giveaway_id to the filter.
     */
    $form_fields = apply_filters( 'sg_form_fields', $form_fields, $giveaway_id );

    $fields_with_key = array();

    // We create an array of fields with keys as their slugs.
    foreach ( $form_fields as $index => $field ) {
        if ( 'winner' === $index ) {
	        $fields_with_key['winner'] = $field;
        } else {
            if ( ! $field['name'] ) {
                $field['name'] = sanitize_title( $field['label'] );
            }
	        $fields_with_key[ $field['name'] ] = $field;
        }
    }

    return $fields_with_key;
}

/**
 * Rendering a single field.
 *
 * @since 2.16.0
 *
 * @param array $field Field Configuration.
 *
 * @return mixed Void if echo is true. Otherwise the field HTML or null.
 */
function sg_render_form_field( $field, $echo = true ) {
    $label   = isset( $field['label'] ) ? $field['label'] : '';
    $name    = isset( $field['name'] ) ? $field['name'] : '';
    $value   = isset( $field['value'] ) ? $field['value'] : '';
    $type    = isset( $field['type'] ) ? $field['type'] : 'text';
	$options = isset( $field['options'] ) ? $field['options'] : array();

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

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

	if ( ( 'select' === $type || 'radio' === $type ) && ! $options ) {
		$type = 'text';
	}

    $required = isset( $field['required'] ) ? (bool) $field['required'] : false;
	$disabled = isset( $field['disabled'] ) ? (bool) $field['disabled'] : false;
	$id       = isset( $field['id'] ) ? $field['id'] : 'sg_field_' . $name;

    $atts = array(
        'class' => 'giveasap_input',
        'placeholder' => sprintf( __( 'Enter %s', 'giveasap' ), $label ),
        'name'  => 'sg_form[' . $name . ']',
        'value' => $value,
        'type'  => $type,
        'id'    => $id,
    );
    if ( $required ) {
        $atts['required'] = 'required';
    }

	if ( $disabled ) {
		$atts['disabled'] = 'disabled';
	}

    $atts = apply_filters( 'sg_render_form_field_atts', $atts, $field );

    if ( 'checkbox' === $atts['type'] && ! $atts['value'] ) {
        $atts['value'] = 1;
    }

    $html_atts = array();
    foreach ( $atts as $key => $att ) {
        $html_atts[] = $key . '="' . esc_attr( $att ) . '"';
    }
	$field_html ='';

    switch ( $atts['type'] ) {
        case 'select':
            $field_html = '<select ' . implode( ' ', $html_atts ) . '>';
            foreach ( $options as $option ) {
                if ( '' === trim( $option ) ) { continue; }
	            $field_html .= '<option value="' . esc_attr( $option ) . '">' . $option . '</option>';
            }
            $field_html .= '</select>';
            break;
	    case 'radio':
		    $field_html = '';
		    foreach ( $options as $index => $option ) {
			    if ( '' === trim( $option ) ) { continue; }
			    $radio_atts = $atts;
			    $radio_atts['id'] = $atts['id'] . '_' . $index;
			    $radio_atts['value'] = $option;
			    $html_atts = array();
			    foreach ( $radio_atts as $key => $att ) {
				    $html_atts[] = $key . '="' . esc_attr( $att ) . '"';
			    }
			    if ( $index === 0 ) {
			        $html_atts[] = 'checked';
                }
			    $field_html .= '<div class="sg-form-field-radio-option"><input ' . implode( ' ', $html_atts ) . '/><label for="' . $radio_atts['id'] . '">' . $option . '</label></div>';
		    }
		    break;
        default:
	        $field_html = '<input ' . implode( ' ', $html_atts ) . '/>';
	        break;
    }

    $outer_html = '<div class="sg-form-field sg-form-field-' . $atts['type'] . '"><label for="' . esc_attr( $id ) . '">' . $label . '</label>%s</div>';

    // If hidden, we will only render the field.
    if ( 'hidden' === $atts['type'] ) {
        $outer_html = '%s';
    }

    if ( 'checkbox' === $atts['type'] ) {
	    $outer_html = '<div class="sg-form-field sg-form-field-' . $atts['type'] . '">%s<label for="' . esc_attr( $id ) . '">' . $label . '</label></div>';
    }

    $html = sprintf( $outer_html, $field_html );
    if ( $echo ) {
        echo $html;
    } else {
        return $html;
    }
}

/**
 * Get the current page URL.
 *
 * @since 2.20.0
 *
 * @return string
 */
function sg_get_current_page_url() {
    global $wp;
	return add_query_arg( $_GET, home_url( $wp->request ) );
}

add_action( 'sg_box_footer', 'sg_box_footer', 20, 3 );

/**
 * Show the Footer
 *
 * @param SG_Giveaway    $giveaway
 * @param GiveASAP_Front $giveasap_front
 */
function sg_box_footer( $giveaway, $giveasap_front, $giveasap_settings ) {
    $ga_schedule       = $giveaway->get_schedule();
	$rules_button_text = isset( $giveasap_settings['rules_button'] ) ? $giveasap_settings['rules_button'] : __( 'Show Rules', 'giveasap' );
	$schedule          = $giveaway->get_schedule_settings();
	$show_timezone     = ! isset( $schedule['sg_hide_timezone'] ) || 1 !== absint( $schedule['sg_hide_timezone'] );

    ?>
    <footer class="giveasap_section">

        <ul class="giveasap_meta items-2 row">
            <li class="time icon-aside">
                <span class="fal fa-2x fa-fw fa-calendar-alt"></span>
                <div class="meta-content">
                    <small><?php _e( 'Ends:', 'giveasap' ); ?></small>
					<?php giveasap_the_formatted_datetime( $ga_schedule->get_original_time( 'end' ), $show_timezone ); ?>
                </div>
            </li>
            <li class="time icon-aside">
                <span class="fal fa-2x fa-fw fa-calendar-alt"></span>
                <div class="meta-content">
                    <small><?php _e( 'Winner Announcement:', 'giveasap' ); ?></small>
					<?php giveasap_the_formatted_datetime( $ga_schedule->get_original_time( 'winner' ), $show_timezone ); ?>
                </div>
            </li>
        </ul>

        <div class="giveasap_rules">
            <h2 class="giveasap_heading"><span class="fal fa-exclamation-circle"></span> <?php _e( 'Rules', 'giveasap' ); ?></h2>
			<?php

            $rules_text = sg_get_rules_text( $giveaway );
			$rules_text = get_extended( $rules_text );
			echo $rules_text['main'];

			if( $rules_text['extended'] != '' ) {
				echo '<button id="giveasap_show_rules" class="giveasap_button secondary">' . $rules_button_text . '</button>';
				?>
                <div class="giveasap_rules_extended">
					<?php echo $rules_text['extended']; ?>
                </div>
			<?php } ?>

        </div>
		<?php

		if ( ! defined( 'GIVEASAP_PRO' ) ) {
			?>
            <a target="_blank" href="https://wordpress.org/plugins/giveasap/" class="giveasap_button-secondary">
				<?php _e( 'Powered by Simple Giveaways', 'giveasap' ); ?>
            </a>
			<?php
		}
		?>
    </footer>
    <?php
}

add_action( 'sg_box_shortcode_footer', 'sg_box_shortcode_footer', 20, 4 );

/**
 * Show the Shortcode Footer
 *
 * @param SG_Giveaway    $giveaway
 * @param GiveASAP_Front $giveasap_front
 */
function sg_box_shortcode_footer( $giveaway, $shortcode_atts, $giveasap_front, $giveasap_settings ) {

	if ( ! defined( 'GIVEASAP_PRO' ) && ! absint( $shortcode_atts['rules'] ) ) {
	    return;
    }
	?>
    <footer class="giveasap_section">
        <?php if ( absint( $shortcode_atts['rules'] ) ) { ?>
        <div class="giveasap_rules">
            <h2 data-class="active" data-target="#sg_rules_extended_<?php echo esc_attr( $giveaway->get_id() ); ?>" class="giveasap_heading sg-toggle"><span class="fal fa-exclamation-circle"></span> <?php _e( 'Rules', 'giveasap' ); ?></h2>
        </div>
		<?php
        }

        ?>
        <a aria-label="<?php esc_attr_e( 'Powered by Simple Giveaways', 'giveasap' ); ?>" target="_blank" href="https://wordpress.org/plugins/giveasap/" class="sg-powered-by giveasap_button-secondary">
            <?php include trailingslashit( GASAP_ROOT ) . 'assets/images/logo-color.svg'; ?>
        </a>
		<?php if ( absint( $shortcode_atts['rules'] ) ) { ?>
        <div class="giveasap_rules sg-rules-text">

            <div id="sg_rules_extended_<?php echo esc_attr( $giveaway->get_id() ); ?>" class="giveasap_rules_extended">
                <?php
                $rules_text = sg_get_rules_text( $giveaway );
                echo $rules_text;
                ?>
            </div>

        </div>
		<?php
        }?>

    </footer>
	<?php
}

/**
 * Get templates in public folder
 *
 * @param string $template_name Template name.
 * @param array  $args          Arguments. (default: array).
 * @param string $template_path Template path. (default: '').
 * @param string $default_path  Default path. (default: '').
 *
 * Copied from WooCommerce
 */
function sg_get_template( $template_name, $args = array(), $template_path = '', $default_path = '' ) {
	$cache_key = sanitize_key( implode( '-', array( 'template', $template_name, $template_path, $default_path, gasap()->version() ) ) );
	$template  = (string) wp_cache_get( $cache_key, 'simple-giveaways' );

	if ( ! $template ) {
		$template = sg_locate_template( $template_name, $template_path, $default_path );

		// Don't cache the absolute path so that it can be shared between web servers with different paths.
		$cache_path = sg_tokenize_path( $template, sg_get_path_define_tokens() );

		sg_set_template_cache( $cache_key, $cache_path );
	} else {
		// Make sure that the absolute path to the template is resolved.
		$template = sg_untokenize_path( $template, sg_get_path_define_tokens() );
	}

	// Allow 3rd party plugin filter template file from their plugin.
	$filter_template = apply_filters( 'sg_get_template', $template, $template_name, $args, $template_path, $default_path );

	if ( $filter_template !== $template ) {
		if ( ! file_exists( $filter_template ) ) {
			/* translators: %s template */
			_doing_it_wrong( __FUNCTION__, sprintf( __( '%s does not exist.', 'giveasap' ), '<code>' . $template . '</code>' ), '2.33.0' );
			return;
		}
		$template = $filter_template;
	}

	$action_args = array(
		'template_name' => $template_name,
		'template_path' => $template_path,
		'located'       => $template,
		'args'          => $args,
	);

	if ( ! empty( $args ) && is_array( $args ) ) {
		extract( $args ); // @codingStandardsIgnoreLine
	}

	do_action( 'sg_before_template_part', $action_args['template_name'], $action_args['template_path'], $action_args['located'], $action_args['args'] );

	include $action_args['located'];

	do_action( 'sg_after_template_part', $action_args['template_name'], $action_args['template_path'], $action_args['located'], $action_args['args'] );
}

/**
 * Locate a template and return the path for inclusion.
 *
 * This is the load order:
 *
 * yourtheme/$template_path/$template_name
 * yourtheme/$template_name
 * $default_path/$template_name
 *
 * Copied from WooCommerce
 *
 * @param string $template_name Template name.
 * @param string $template_path Template path. (default: '').
 * @param string $default_path  Default path. (default: '').
 * @return string
 */
function sg_locate_template( $template_name, $template_path = '', $default_path = '' ) {
	if ( ! $template_path ) {
		$template_path = apply_filters( 'sg_template_path', 'giveaways/' );
	}

	if ( ! $default_path ) {
		$default_path = untrailingslashit( GASAP_ROOT ) . '/public/';
	}

	// Look within passed path within the theme - this is priority.
	$template = locate_template(
		array(
			trailingslashit( $template_path ) . $template_name,
			$template_name,
		)
	);

	// Get default template/.
	if ( ! $template || SG_TEMPLATE_DEBUG_MODE ) {
		$template = $default_path . $template_name;
	}

	// Return what we found.
	return apply_filters( 'sg_locate_template', $template, $template_name, $template_path );
}

/**
 * Given a path, this will convert any of the subpaths into their corresponding tokens.
 * Copied from WooCommerce
 *
 * @param string $path The absolute path to tokenize.
 * @param array  $path_tokens An array keyed with the token, containing paths that should be replaced.
 * @return string The tokenized path.
 */
function sg_tokenize_path( $path, $path_tokens ) {
	// Order most to least specific so that the token can encompass as much of the path as possible.
	uasort(
		$path_tokens,
		function ( $a, $b ) {
			$a = strlen( $a );
			$b = strlen( $b );

			if ( $a > $b ) {
				return -1;
			}

			if ( $b > $a ) {
				return 1;
			}

			return 0;
		}
	);

	foreach ( $path_tokens as $token => $token_path ) {
		if ( 0 !== strpos( $path, $token_path ) ) {
			continue;
		}

		$path = str_replace( $token_path, '{{' . $token . '}}', $path );
	}

	return $path;
}

/**
 * Fetches an array containing all of the configurable path constants to be used in tokenization.
 * Copied from WooCommerce
 *
 * @return array The key is the define and the path is the constant.
 */
function sg_get_path_define_tokens() {
	$defines = array(
		'ABSPATH',
		'WP_CONTENT_DIR',
		'WP_PLUGIN_DIR',
		'WPMU_PLUGIN_DIR',
		'PLUGINDIR',
		'WP_THEME_DIR',
	);

	$path_tokens = array();
	foreach ( $defines as $define ) {
		if ( defined( $define ) ) {
			$path_tokens[ $define ] = constant( $define );
		}
	}

	return apply_filters( 'sg_get_path_define_tokens', $path_tokens );
}

/**
 * Add a template to the template cache.
 * Copied from WooCommerce
 *
 * @param string $cache_key Object cache key.
 * @param string $template Located template.
 */
function sg_set_template_cache( $cache_key, $template ) {
	wp_cache_set( $cache_key, $template, 'simple-giveaways' );

	$cached_templates = wp_cache_get( 'cached_templates', 'simple-giveaways' );
	if ( is_array( $cached_templates ) ) {
		$cached_templates[] = $cache_key;
	} else {
		$cached_templates = array( $cache_key );
	}

	wp_cache_set( 'cached_templates', $cached_templates, 'simple-giveaways' );
}

/**
 * Given a tokenized path, this will expand the tokens to their full path.
 *
 * Copied from WooCommerce
 *
 * @param string $path The absolute path to expand.
 * @param array  $path_tokens An array keyed with the token, containing paths that should be expanded.
 * @return string The absolute path.
 */
function sg_untokenize_path( $path, $path_tokens ) {
	foreach ( $path_tokens as $token => $token_path ) {
		$path = str_replace( '{{' . $token . '}}', $token_path, $path );
	}

	return $path;
}