<?php
/**
 * Prizes part
 */

namespace Simple_Giveaways;

/**
 * Class Prizes
 *
 * @package Simple_Giveaways
 */
class Prizes {

	public function __construct() {
		add_action( 'sg_prizes_field_table_tbody_columns', array( $this, 'add_prize_instructions_field' ), 9, 3 );
		add_filter( 'sg_winner_email_text', array( __CLASS__, 'add_prize_instructions_to_email' ), 20, 5 );
		add_filter( 'sg_show_winner_name', array( $this, 'display_prize_next_to_winner_name' ), 20, 2 );
	}

	/**
	 * Show Prize Next to Winner's name
	 *
	 * @param $name
	 * @param $winner
	 */
	public function display_prize_next_to_winner_name( $name, $winner ) {
		if ( empty( $winner['prizes'] ) ) {
			return $name;
		}

		$name .= ' - ';

		$won_prizes = array();
		foreach ( $winner['prizes'] as $winner_prize ) {
			$won_prizes[] = $winner_prize['title'];
		}

		$name .= implode( ', ', $won_prizes );

		return $name;
	}

	/**
	 * Adding Winner Prize instructions to the email.
	 *
	 * @param $email_text
	 * @param $winner
	 * @param $order
	 * @param $post_id
	 * @param $prize_options
	 *
	 * @return mixed
	 */
	public static function add_prize_instructions_to_email( $email_text, $winner, $order, $post_id, $prize_options ) {

		if ( ! isset( $winner['prizes'] ) ) {
			return $email_text;
		}

		if ( false === strpos( $email_text, '{{PRIZE_INSTRUCTIONS}}' ) ) {
			return $email_text;
		}
		
		$instructions = '';
		foreach ( $winner['prizes'] as $prize ) {
			if ( isset( $prize['instructions'] ) && $prize['instructions'] ) {
				$instructions .= '<p><strong>' . $prize['title'] . '</strong></p>';
				$instructions .= '<p>' . $prize['instructions'] . '</p>';
			}
		}

		if ( $instructions ) {
			$instructions = '<p><strong>' . __( 'Prize Instructions', 'giveasap-premium' ) . '</strong></p><hr/>' . $instructions;
			$email_text   = str_replace( '{{PRIZE_INSTRUCTIONS}}', $instructions, $email_text );
		}

		return $email_text;
	}

	/**
	 * Add the Prize Instructions Field
	 *
	 * @param $form_field
	 * @param $index
	 * @param $field
	 */
	public function add_prize_instructions_field( $form_field, $index, $field ) {
		$value = isset( $form_field['instructions'] ) ? $form_field['instructions'] : '';
		?>
		<tr class="sg-prize-field-instructions">
			<th>
				<label for="sg-field-instructions-<?php echo esc_attr( $index ); ?>"><?php esc_html_e( 'Instructions', 'giveasap-premium' ); ?></label>
			</th>
			<td>
				<!-- Maybe initialize with wp.editor: https://wordpress.stackexchange.com/questions/274592/how-to-create-wp-editor-using-javascript -->
				<textarea id="sg-field-instructions-<?php echo esc_attr( $index ); ?>" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][instructions]"><?php echo wp_kses_post( $value ); ?></textarea>
				<p class="description"><?php esc_html_e( 'Enter instructions that are going to be sent to the winner. Included in the winner email.', 'giveasap-premium' ); ?></p>

			</td>
		</tr>
		<?php
	}
}
