<?php

/**
 * Handles when a successful payment has been made for an attendee.
 *
 * @return string The output for the payment success page.
 */
function rsvp_pro_payment_success_page() {
	global $wpdb;

	$output = '<div id="rsvp_pro_payment_success_container">';
	if ( isset( $_GET['paymentId'] ) && ! empty( $_GET['paymentId'] ) ) {
		$sql       = 'SELECT id FROM ' . PRO_ATTENDEES_TABLE . ' WHERE transaction_id = %s';
		$attendees = $wpdb->get_results( $wpdb->prepare( $sql, $_GET['paymentId'] ) );

		$sql        = 'SELECT id FROM ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' WHERE transaction_id = %s';
		$sub_events = $wpdb->get_results( $wpdb->prepare( $sql, $_GET['paymentId'] ) );

		if ( ( count( $attendees ) <= 0 ) && ( count( $sub_events ) <= 0 ) ) {
			$output .= '<p>' . rsvp_pro_get_frontend_string( 'payment_success_invalid_payment_id' ) . '</p>';
		} else {
			foreach( $attendees as $a ) {
				$attendee = new Rsvp_Pro_Attendee( $a->id );
				$attendee->set_payment_status( RSVP_PRO_PAID_STATUS );
				$attendee->save();
			}

			foreach( $sub_events as $se ) {
				$sub_event = new Rsvp_Pro_Attendee_Subevent( $se->id );
				$sub_event->set_payment_status( RSVP_PRO_PAID_STATUS );
				$sub_event->save();
			}
			// Display the message that confirms that they have paid
			$output .= '<p>' . rsvp_pro_get_frontend_string( 'payment_success_received' ) . '</p>';
		}
	} else {
		$output .= '<p>' . rsvp_pro_get_frontend_string( 'payment_page_invalid_message' ) . '</p>';
	}
	$output .= '</div>';

	return $output;
}

/**
 * Handles the output of a payment that fails.
 *
 * @return string The output for when a payment fails.
 */
function rsvp_pro_payment_failure_page() {
	$output = '<div id="rsvp_pro_payment_failure_container">';

	if ( isset( $_GET['token'] ) && ! empty( $_GET['token'] ) ) {
		$output .= '<p>' . rsvp_pro_get_frontend_string( 'payment_page_cancelled_message' ) . '</p>';
	} else {
		$output .= '<p>' . rsvp_pro_get_frontend_string( 'payment_page_invalid_message' ) . '</p>';
	}

	$output .= '</div>';
	return $output;
}
