<?php

add_action( 'init', 'aitReservationCustomType' );
add_action( 'add_meta_boxes', 'aitShowReservationDeails', 10, 2 );
add_filter( "manage_ait-tour-reservation_posts_columns", "aitReservationsChangeColumns" );
add_action( "manage_posts_custom_column", "aitReservationsFillColumns", 10, 2);
add_action( 'admin_head', 'aitReservationsCss');
add_action( 'admin_head', 'aitReservationsRemoveAdd');

add_action( 'wp_ajax_ait_reserve_tour', 'aitReserveTour' );
add_action( 'wp_ajax_nopriv_ait_reserve_tour', 'aitReserveTour' );

function aitGetReservations($reservationId) {
	$output = array();
	$reservations = get_post_meta( $reservationId, 'reservations', true );

	$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
	$dateFormat = get_option( 'date_format', 'F j, Y' );

	$i = 1;
	foreach ($reservations as $id => $amount) {
		$offer = get_post( $id );
		$offerTourId = get_post_meta( $offer->ID, 'ait_item_id', true );
		$offerTour = get_post( $offerTourId );

		$offer->options = get_post_meta( $offer->ID, '_ait-dir-item-offer', true );
		$offer->from = date($dateFormat,strtotime($offer->options['from']));
		$offer->to = date($dateFormat,strtotime($offer->options['to']));
		$offer->price = $currency . ' ' . $offer->options['price'];
		$offer->total = $currency . ' ' . (floatval($offer->options['price']) * intval($amount));

		$output[$i] = array();
		$output[$i]['item'] = $offerTour;
		$output[$i]['offer'] = $offer;
		$output[$i]['amount'] = $amount;

		$i++;
	}

	return $output;
}

function aitReservationCustomType() {
	$args = array(
		'public' => true,
		'labels' => array(
			'name'			=> __('Reservations','ait'),
			'singular_name' => __('Reservation','ait'),
			'add_new'		=> __('Add new','ait'),
			'add_new_item'	=> __('Add new reservation','ait'),
			'edit_item'		=> __('Reservation Details','ait'),
			'new_item'		=> __('New reservation','ait'),
			'not_found'		=> __('No reservations found','ait'),
			'not_found_in_trash' => __('No reservations found in Trash','ait'),
			'menu_name'		=> __('Reservations','ait'),
		),
		'menu_position' => 34,
		'supports'		=> array(''),
		'capability_type' => 'ait-tour-reservation',
		'map_meta_cap' => true
	);
	register_post_type( 'ait-tour-reservation', $args );
}

function aitShowReservationDeails($postType, $post) {
	add_meta_box(
		'ait-tour-reservation-contact-info',
		__( 'Contact Information', 'ait' ),
		'aitShowReservationDeailsContact',
		'ait-tour-reservation',
		'normal',
		'high'
	);
	add_meta_box(
		'ait-tour-reservation-reservations',
		__( 'Reservations', 'ait' ),
		'aitShowReservationDeailsReservations',
		'ait-tour-reservation',
		'normal',
		'high'
	);
}

function aitShowReservationDeailsContact($post) {

	$message = $post->post_content;
	$contact = get_post_meta( $post->ID, 'personal_details', true );

	?>
	<table>
		<tbody>
			<tr>
				<td><label><?php _e( 'Title: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['title']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'Name: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['name']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'Surname: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['surname']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'Company name: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['company']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'Address: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['address']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'City: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['city']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'Post/Zip Code: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['zipcode']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'State: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['state']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'Country: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['country']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'Phone: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['phone']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'Email: ', 'ait' ); ?></label></td>
				<td><input type="text" size="98" disabled value="<?php echo $contact['email']; ?>"></input></td>
			</tr>
			<tr>
				<td><label><?php _e( 'Message: ', 'ait' ); ?></label></td>
				<td><textarea disabled cols="100" rows="10"><?php echo $message; ?></textarea></td>
			</tr>
		</tbody>
	</table>
	<?php

}

function aitShowReservationDeailsReservations($post) {
	$reservations = aitGetReservations($post->ID);

	$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
	$total = 0;
	?>
	<table>
		<thead>
			<tr>
				<th><?php _e( 'Item', 'ait' ); ?></th>
				<th><?php _e( 'Offer', 'ait' ); ?></th>
				<th><?php _e( 'Date', 'ait' ); ?></th>
				<th><?php _e( 'Price', 'ait' ); ?></th>
				<th><?php _e( 'Amount', 'ait' ); ?></th>
				<th><?php _e( 'Sum', 'ait' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php foreach ($reservations as $id => $res) {
			$total += (intval($res['amount']) * floatval($res['offer']->options['price']));
			?>
			<tr>
				<td><?php
					echo '<a href="'.get_edit_post_link($res['item']->ID).'" target="_blank">'.$res['item']->post_title.'</a>';
				?></td>
				<td><?php
					echo '<a href="'.get_edit_post_link($res['offer']->ID).'" target="_blank">'.$res['offer']->post_title.'</a>';
				?></td>
				<td><?php echo $res['offer']->from." - ".$res['offer']->to; ?></td>
				<td><?php echo $res['offer']->price; ?></td>
				<td><?php echo $res['amount']; ?></td>
				<td><?php echo $res['offer']->total; ?></td>
			</tr>
			<?php } ?>
			<tr>
				<td class="total-title" colspan="5"><?php _e( 'Total price:', 'ait' ); ?></td>
				<td class="total-value"><?php echo $currency . ' ' . $total; ?></td>
			</tr>
		</tbody>
	</table>
	<?php
}

function aitReservationsChangeColumns($cols) {

	global $aitThemeOptions, $current_user;
	if( isset($aitThemeOptions->members->easyAdminEnable) && isset( $current_user->roles ) && is_array( $current_user->roles ) && ( in_array('directory_1', $current_user->roles) || in_array('directory_2', $current_user->roles) || in_array('directory_3', $current_user->roles) || in_array('directory_4', $current_user->roles) || in_array('directory_5', $current_user->roles) ) ) {
		// easy admin columns
		$cols = array(
			'title'			=> __( 'Name', 'ait'),
			'tour_email'	=> __( 'Email', 'ait'),
			'tour_phone'	=> __( 'Phone', 'ait'),
			'tour_item'		=> __( 'Item', 'ait'),
			'tour_offer'	=> __( 'Reservations', 'ait'),
			'date'			=> __( 'Reservation date', 'ait'),
		);
	} else {
		$cols = array(
			'cb'			=> '<input type="checkbox" />',
			'title'			=> __( 'Name', 'ait'),
			'tour_email'	=> __( 'Email', 'ait'),
			'tour_phone'	=> __( 'Phone', 'ait'),
			'tour_item'		=> __( 'Item', 'ait'),
			'tour_offer'	=> __( 'Reservations', 'ait'),
			'date'			=> __( 'Reservation date', 'ait'),
		);
	}
	return $cols;

}

function aitReservationsFillColumns($column, $postId) {
	switch ($column) {
		case 'tour_item':
			$reservations = aitGetReservations($postId);
			if (isset($reservations[1])) {
				echo '<a href="'.get_edit_post_link($reservations[1]['item']->ID).'" target="_blank">'.$reservations[1]['item']->post_title.'</a>';
			}
			break;
		case 'tour_offer':
			$reservations = aitGetReservations($postId);
			foreach ($reservations as $id => $res) {
				echo $res['amount'].' x '.'<a href="'.get_edit_post_link($res['offer']->ID).'" target="_blank">'.$res['offer']->post_title.'</a> - '.$res['offer']->from.' - '.$res['offer']->to.'<br>';
			}
			break;
		case 'tour_email':
			$contact = get_post_meta( $postId, 'personal_details', true );
			echo $contact['email'];
			break;
		case 'tour_phone':
			$contact = get_post_meta( $postId, 'personal_details', true );
			echo $contact['phone'];
			break;
	}
}

function aitReservationsCss() {
	if((strpos($_SERVER['PHP_SELF'],'edit.php') !== false) && isset($_GET['post_type']) && ($_GET['post_type'] == 'ait-tour-reservation')){
		?>
		<style type="text/css">
			a.add-new-h2 { display: none !important; }
		</style>
		<?php
	}
	?>
	<style type="text/css">
		#ait-tour-reservation-reservations.postbox table 	{
			width: 100%;
		}
		#ait-tour-reservation-reservations.postbox table td {
			background-color: #FFFFFF;
			padding: 7px 10px 5px;
			text-align: center;
		}
		#ait-tour-reservation-reservations.postbox table td.total-title {
			text-align: right;
		}
	</style>
	<?php
}

function aitReservationsRemoveAdd() {
	remove_submenu_page('edit.php?post_type=ait-tour-reservation','post-new.php?post_type=ait-tour-reservation');
}

function aitReserveTour() {
	// Check for nonce security
	$nonce = $_POST['nonce'];
	if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) ) {
		echo "nonce";
		exit();
	}

	$itemId = $_POST['itemid'];
	$item = get_post(intval($itemId));
	$reservations = $_POST['reservations'];
	$contact = $_POST['contact'];

	// check required personal informations
	if ( (empty($contact['name'])) || (empty($contact['surname']))  || (empty($contact['address'])) || (empty($contact['city'])) || (empty($contact['zipcode'])) || (empty($contact['country'])) || (empty($contact['email'])) ) {
		_e( 'Please fill out all required personal details', 'ait' );
		exit;
	}

	$title = (empty($contact['title'])) ? $contact['name'] . ' ' . $contact['surname'] : $contact['title'] . ' ' . $contact['name'] . ' ' . $contact['surname'];

	$attrs = array(
		'post_author' => $item->post_author,
		'post_type' => 'ait-tour-reservation',
		'post_title' => $title,
		'post_content' => $contact['message']
	);

	$postId = wp_insert_post( $attrs, true );

	if (is_wp_error( $postId )) {
		echo $postId->get_error_message();
		exit();
	}

	// save meta
	update_post_meta( $postId, 'personal_details', $contact );
	update_post_meta( $postId, 'reservations', $reservations );

	// send mail if mailing is enabled
	$res = get_post($postId);
	$mailResult = aitReservationSendEmail($res);
	if (!$mailResult) {
		_e( 'Error with sending email', 'ait' );
		exit;
	}


	echo "success";
	exit;

}

// send emails as HTML
add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));

function aitReservationSendEmail($reservation) {
	global $aitThemeOptions;

	$reservations = aitGetReservations($reservation->ID);

	$subject = (isset($aitThemeOptions->reservations->emailSubject)) ? $aitThemeOptions->reservations->emailSubject : 'New reservation';
	$body = (isset($aitThemeOptions->reservations->emailBody)) ? $aitThemeOptions->reservations->emailBody : '';
	$headers = (isset($aitThemeOptions->reservations->emailFrom)) ? $aitThemeOptions->reservations->emailFrom . "\r\n" : 'From: My Name <myname@mydomain.com>' . "\r\n";

	if (isset($reservations[1]['item'])) {
		// contact
		$contactInfo = get_post_meta( $reservation->ID, 'personal_details', true );

		$contact = '<b>'.__( 'Title: ', 'ait' ).'</b>'.$contactInfo['title'].'<br>';
		$contact .= '<b>'.__( 'Name: ', 'ait' ).'</b>'.$contactInfo['name'].'<br>';
		$contact .= '<b>'.__( 'Surname: ', 'ait' ).'</b>'.$contactInfo['surname'].'<br>';
		$contact .= '<b>'.__( 'Company name: ', 'ait' ).'</b>'.$contactInfo['company'].'<br>';
		$contact .= '<b>'.__( 'Address: ', 'ait' ).'</b>'.$contactInfo['address'].'<br>';
		$contact .= '<b>'.__( 'City: ', 'ait' ).'</b>'.$contactInfo['city'].'<br>';
		$contact .= '<b>'.__( 'Post/Zip Code: ', 'ait' ).'</b>'.$contactInfo['zipcode'].'<br>';
		$contact .= '<b>'.__( 'State: ', 'ait' ).'</b>'.$contactInfo['state'].'<br>';
		$contact .= '<b>'.__( 'Country: ', 'ait' ).'</b>'.$contactInfo['country'].'<br>';
		$contact .= '<b>'.__( 'Phone: ', 'ait' ).'</b>'.$contactInfo['phone'].'<br>';
		$contact .= '<b>'.__( 'Email: ', 'ait' ).'</b>'.$contactInfo['email'].'<br>';

		// define recipients
		$to = array();
		if (isset($GLOBALS['aitThemeOptions']->reservations->sendEmail)) {
			array_push($to, get_option( "admin_email" ));
		}
		if (isset($aitThemeOptions->reservations->emailHierarchy)) {
			if ($aitThemeOptions->reservations->emailHierarchy == 'one') {
				$options = get_post_meta( $reservations[1]['item']->ID, '_ait-dir-item', true );
				if (!empty($options['email'])) {
					array_push($to, $options['email']);
				} else {
					$authorId = $reservations[1]['item']->post_author;
					$author = new WP_User($authorId);
					array_push($to, $author->user_email);
				}
			} else if ($aitThemeOptions->reservations->emailHierarchy == 'two') {
				$authorId = $reservations[1]['item']->post_author;
				$author = new WP_User($authorId);
				array_push($to, $author->user_email);
			}
		}
		if (isset($GLOBALS['aitThemeOptions']->reservations->sendEmailToSender)) {
			array_push($to, $contactInfo['email']);
		}

		// create email body
		ob_start();
		aitShowReservationDeailsReservations($reservation);
		$summary = ob_get_contents();
		ob_end_clean();

		// message
		$message = $reservation->post_content;

		$body = str_replace('[sum-table]', $summary, $body);
		$body = str_replace('[contact-info]', $contact, $body);
		$body = str_replace('[message]', $message, $body);

		// send mails
		return wp_mail( $to, $subject, $body, $headers );

	} else {
		return false;
	}

}