<?php
/**
 * Shows the form and handles the processing for sending emails to attendees
 *
 * @param  int $event_id The event ID that we are sending emails for.
 */
function rsvp_pro_admin_mass_email( $event_id ) {
	global $wpdb;
	if ( isset( $_POST['email_subject'] ) && ! empty( $_POST['email_subject'] ) && isset( $_POST['email_body'] ) && ! empty( $_POST['email_body'] ) ) {
		check_admin_referer( 'rsvp-email' );
		rsvp_pro_mass_email_send( $event_id );
	} else {
		rsvp_pro_mass_email_form( $event_id );
	}
}

function rsvp_pro_mass_email_send( $event_id ) {
	global $wpdb;
	set_time_limit( 0 );

	$isSubEvent    = false;
	$parentEventId = $wpdb->get_var( $wpdb->prepare( 'SELECT parentEventID FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d', $event_id ) );
	if ( $parentEventId > 0 ) {
		$isSubEvent = true;
		$subEventID = $event_id;
		$event_id   = $parentEventId;
	}
	$eventUrl = rsvp_pro_get_event_permalink( $event_id );

	$tmp_attendees = array();
	if ( isset( $_POST['attendees'] ) ) {
		$tmp_attendees = $_POST['attendees'];
	}

	if ( $isSubEvent ) {
		$attendees = rsvp_pro_get_attendees( $subEventID, $tmp_attendees, $_POST['rsvp_status'] );
	} else {
		$attendees = rsvp_pro_get_attendees( $event_id, $tmp_attendees, $_POST['rsvp_status'] );
	}
	
	$headers   = array( 'Content-Type: text/html; charset=UTF-8' );
	if ( ! empty( $_POST['email_from'] ) ) {
		$email_from = str_replace( array( '<', '>' ), '', $_POST['email_from'] );
		$headers[]  = 'From: ' . $email_from . "\r\n";
		$headers[]  = 'Reply-To: ' . $email_from . "\r\n";
		$headers[]  = 'Return-Path: ' . $email_from . "\r\n";

		if ( isset( $_POST['email_receipt'] ) && ( strtoupper( $_POST['email_receipt'] ) === 'Y' ) ) {
			$headers[] = 'Return-Receipt-To: ' . $email_from . "\r\n";
			$headers[] = 'Disposition-Notification-To: ' . $email_from . "\r\n";
			$headers[] = 'X-Confirm-Reading-To: ' . $email_from . "\r\n";
		}

		add_filter(
			'wp_mail_from',
			function ( $email ) {
				return str_replace( array( '<', '>' ), '', $_POST['email_from'] );
			}
		);
	}

	if ( ! empty( $_POST['email_from_name'] ) ) {
		add_filter(
			'wp_mail_from_name',
			function ( $name ) {
				return $_POST['email_from_name'];
			}
		);
	}

	if ( isset( $_POST['save_email'] ) && ( 'Y' === $_POST['save_email'] ) ) {
		$wpdb->insert(
			PRO_MESSAGE_LOG,
			array(
				'rsvpEventID'  => ( ( $isSubEvent ) ? $subEventID : $event_id ),
				'from_email'   => ( isset( $_POST['email_from'] ) ? $_POST['email_from'] : '' ),
				'from_name'    => ( isset( $_POST['email_from_name'] ) ? $_POST['email_from_name'] : '' ),
				'rsvp_status'  => $_POST['rsvp_status'],
				'read_receipt' => ( ( isset( $_POST['email_receipt'] ) && ( $_POST['email_receipt'] === 'Y' ) ) ? 'Y' : 'N' ),
				'subject'      => $_POST['email_subject'],
				'message'      => $_POST['email_body'],
				'send_date'    => date( 'Y-m-d H:i:s' ),
			),
			array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
		);

		$log_id = $wpdb->insert_id;
		foreach ( $attendees as $a ) {
			$wpdb->insert(
				PRO_MESSAGE_LOG_ATTENDEES,
				array(
					'message_id' => $log_id,
					'attendeeID' => $a->id,
				),
				array( '%d', '%d' )
			);
		}
	}

	$attachments = array();
	if ( isset( $_FILES['attachment1'] ) ) {
		$tmp_file = wp_handle_upload(
			$_FILES['attachment1'],
			array(
				'action'    => 'rsvp_pro_mail',
				'test_form' => false,
			)
		);
		if ( ! isset( $tmp_file['error'] ) ) {
			$attachments[] = $tmp_file['file'];
		}
	}

	if ( isset( $_FILES['attachment2'] ) ) {
		$tmp_file = wp_handle_upload(
			$_FILES['attachment2'],
			array(
				'action'    => 'rsvp_pro_mail',
				'test_form' => false,
			)
		);
		if ( ! isset( $tmp_file['error'] ) ) {
			$attachments[] = $tmp_file['file'];
		}
	}

	$tmp_array = array();
	$base_email_body = apply_filters( 'rsvp_pro_mass_email_body', $_POST['email_body'] );
	foreach ( $attendees as $a ) {
		$mail_array = $attachments;
		$subject    = rsvp_pro_admin_replaceVariablesForEmail( $a, $eventUrl, $_POST['email_subject'], ( $isSubEvent ) ? $subEventID : $event_id, $tmp_array );
		$email_body = rsvp_pro_admin_replaceVariablesForEmail( $a, $eventUrl, $base_email_body, ( $isSubEvent ) ? $subEventID : $event_id, $mail_array );
		$subject    = stripslashes( $subject );
		$email_body = nl2br( stripslashes( $email_body ) );
		rsvp_pro_send_mail( $a->email, $subject, $email_body, $headers, $mail_array ); 
		?>
			<p><?php echo stripslashes( $a->firstName ) . ' ' . stripslashes( $a->lastName ) . ' ' . rsvp_pro_get_admin_string( 'emailed_label' ); ?></p>
			<?php
	}

	foreach ( $attachments as $a ) {
		wp_delete_file( $a );
	}
	?>
	<br />
	<p><?php echo rsvp_pro_get_admin_string( 'continue_to_rsvp_label' ); ?> <a href="admin.php?page=rsvp-pro-top-level"><?php echo rsvp_pro_get_admin_string( 'list_label' ); ?></a></p>
	<?php
}

/**
 * Displays the mass email form.
 *
 * @param  int $event_id The event we are trying to send the mass email for
 */
function rsvp_pro_mass_email_form( $event_id ) {
	global $wpdb;

	// Handle the case when we are passing in only specific attendees.
	$attendees = array();
	if ( isset( $_REQUEST['attendee'] ) ) {
		foreach ( $_REQUEST['attendee'] as $attendee ) {
			if ( is_numeric( $attendee ) && ( $attendee > 0 ) ) {
				$attendees[] = $attendee;
			}
		}
	}

	$from_name    = '';
	$from_email   = rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_NOTIFY_EMAIL );
	$rsvp_status  = '';
	$read_receipt = '';
	$subject      = '';
	$message      = '';
	if ( isset( $_GET['message_log_id'] ) && is_numeric( $_GET['message_log_id'] ) && ( $_GET['message_log_id'] > 0 ) ) {
		$sql         = 'SELECT id, from_name, from_email, rsvp_status, read_receipt, subject, message 
                FROM ' . PRO_MESSAGE_LOG . ' 
                WHERE id = %d';
		$message_log = $wpdb->get_row( $wpdb->prepare( $sql, $_GET['message_log_id'] ) );
		if ( $message_log ) {
			$from_name    = stripslashes( $message_log->from_name );
			$from_email   = stripslashes( $message_log->from_email );
			$rsvp_status  = stripslashes( $message_log->rsvp_status );
			$read_receipt = ( $message_log->read_receipt === 'Y' ) ? true : false;
			$subject      = stripslashes( $message_log->subject );
			$message      = stripslashes( $message_log->message );

			$sql          = 'SELECT attendeeID FROM ' . PRO_MESSAGE_LOG_ATTENDEES . ' WHERE message_id = %d';
			$ml_attendees = $wpdb->get_results( $wpdb->prepare( $sql, $message_log->id ) );
			foreach ( $ml_attendees as $mla ) {
				if ( ! isset( $attendees[ $mla->attendeeID ] ) ) {
					$attendees[] = $mla->attendeeID;
				}
			}
		}
	}

	?>
	<h3><?php echo rsvp_pro_get_admin_string( 'send_message_for_label' ); ?> <?php echo rsvp_pro_get_event_name( $event_id ); ?></h3>
	<form name="rsvp_email" method="post" action="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=mass_email&eventID=' . $event_id ); ?>" enctype="multipart/form-data">
	<?php wp_nonce_field( 'rsvp-email' ); ?>
	<input type="hidden" name="eventID" value="<?php echo $event_id; ?>" />
	<table class="form-table">
		<tbody>
			<tr>
				<th scope="row">
					<?php echo rsvp_pro_get_admin_string( 'attendees_being_emailed_label' ); ?>:	
				</th>
				<td>
					<p>
						<span style="margin-left: 30px;"><?php echo rsvp_pro_get_admin_string( 'settings_available_people_to_send_label' ); ?></span>
						<span style="margin-left: 45px;"><?php echo rsvp_pro_get_admin_string( 'settings_people_being_sent_to_label' ); ?></span>
					</p>
					<select name="attendees[]" id="rsvp_pro_mass_email_attendees" multiple="true">
						<?php
						$select_attendees = rsvp_pro_get_attendees( $event_id );
						foreach ( $select_attendees as $sa ) {
							?>
							<option value="<?php echo $sa->id; ?>" <?php echo ( in_array( $sa->id, $attendees ) ) ? 'selected="selected"' : ''; ?>><?php echo esc_html( stripslashes( $sa->firstName . ' ' . $sa->lastName ) ); ?></option>
							<?php
						}
						?>
					</select>
					<p>
						<span style="margin-left: 30px;"><a href="#" id="rsvp_pro_admin_mass_email_select_all"><?php echo rsvp_pro_get_admin_string( 'select_all_link_text' ); ?></a></span>
						<span style="margin-left: 125px;"><a href="#" id="rsvp_pro_admin_mass_email_deselect_all"><?php echo rsvp_pro_get_admin_string( 'deselect_all_link_text' ); ?></a></span>
					</p>
				</td>
			</tr>
			<tr>
				<th scope="row">
					<label for="email_from"><?php echo rsvp_pro_get_admin_string( 'from_email_label' ); ?></label>
				</th>
				<td>
					<input type="text" name="email_from" id="email_from" value="<?php echo esc_attr( $from_email ); ?>" />
				</td>
			</tr>
			<tr>
				<th scope="row">
					<label for="email_from_name"><?php echo rsvp_pro_get_admin_string( 'from_email_name_label' ); ?></label>
				</th>
				<td>
					<input type="text" name="email_from_name" id="email_from_name" value="<?php echo esc_attr( $from_name ); ?>" />
				</td>
			</tr>
			<tr>
				<th scope="row">
					<label for="rsvp_status"><?php echo rsvp_pro_get_admin_string( 'limit_rsvp_status_label' ); ?></label>
				</th>
				<td>
					<select name="rsvp_status" id="rsvp_status" size="1">
						<option value="">--</option>
						<option value="No" <?php echo ( $rsvp_status == 'No' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_frontend_string( 'no_text' ); ?></option>
						<option value="NoResponse" <?php echo ( $rsvp_status == 'NoResponse' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_frontend_string( 'noresponse_text' ); ?></option>
						<?php if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_ENABLE_WAITLIST ) == 'Y' ) : ?>
								<option value="Waitlist" <?php echo ( $rsvp_status == 'Waitlist' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_frontend_string( 'waitlist_text' ); ?></option>
							<?php endif; ?>
						<option value="Yes" <?php echo ( $rsvp_status == 'Yes' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_frontend_string( 'yes_text' ); ?></option>
					</select>
				</td>
			</tr>
			<tr>
				<th scope="row">
					<label for="email_receipt"><?php echo rsvp_pro_get_admin_string( 'read_receipt_label' ); ?></label>
				</th>
				<td>
					<input type="checkbox" value="Y" name="email_receipt" id="email_receipt" <?php echo $read_receipt ? 'checked="checked"' : ''; ?> />
					<br />
					<span class="description"><?php echo rsvp_pro_get_admin_string( 'from_address_required_label' ); ?></span>
				</td>
			</tr>
			<?php
			rsvp_pro_admin_message_variables( $event_id );
			?>
			<tr>
				<th scope="row">
					<label for="email_subject"><?php echo rsvp_pro_get_admin_string( 'message_subject_label' ); ?></label>
				</th>
				<td>
					<input type="text" name="email_subject" id="email_subject" class="large-text" value="<?php echo esc_attr( $subject ); ?>" />
				</td>
			</tr>
			<tr>
				<th scope="row">
					<label for="email_body"><?php echo rsvp_pro_get_admin_string( 'message_email_label' ); ?></label>
				</th>
				<td>
					<?php wp_editor( $message, 'email_body', $settings = array() ); ?>
				</td>
			</tr>
			<tr>
				<th scope="row" valign="top">
					<label for="attachments"><?php echo rsvp_pro_get_admin_string( 'message_attachments_label' ); ?></label>
				</th>
				<td>
					<input type="file" name="attachment1" /><br />
					<input type="file" name="attachment2" />
				</td>
			</tr>
			<tr>
				<th scope="row">
					<label for="save_email"><?php echo rsvp_pro_get_admin_string( 'save_message_label' ); ?></label>
				</th>
				<td>
					<input type="checkbox" name="save_email" id="save_email" value="Y" checked />
				</td>
			</tr>
			</tbody>
		</table>
		<p class="submit"><input type="submit" value="<?php echo rsvp_pro_get_admin_string( 'send_message_label' ); ?>" class="button-primary" name="sendMessage"></p>
	</form>
	<?php
}
