<?php
function wpj_display_private_messages_page_content() { $messages_class = new WPJ_Messages(); ?>

	<div class="wrap">
		<h2 class="wpj-admin-title">Jobster - <?php _e( 'Messages', 'wpjobster' ); ?></h2>

		<div id="usual2" class="usual wpj-admin-table-wrapper">

			<div class="wpj-admin-header">
				<ul>
					<li><a href="#private-messages"><?php _e( 'Private Messages', 'wpjobster' ); ?></a></li>
					<li><a href="#transaction-messages"><?php _e( 'Transaction Messages', 'wpjobster' ); ?></a></li>
					<li><a href="#review-messages"><?php _e( 'Review Messages', 'wpjobster' ); ?></a></li>
				</ul>
			</div>

			<!-- Private Messages -->
			<div id="private-messages">

				<?php
				$messages_class->deletePrivateMessage();
				$messages_class->deletePermanentlyPrivateMessage(); ?>

				<div class="wpj-admin-top-search-form-wrapper"><?php wpj_search_user_private_messages_form(); ?></div>

				<?php $rows = $messages_class->getOrderRow( 'job_pm' );

				if ( $rows['count'] > 0 ) { ?>

					<table class="widefat post" cellspacing="0">
						<thead>
							<tr>
								<th width="25%"><?php _e( 'Sender', 'wpjobster' ); ?></th>
								<th width="25%"><?php _e( 'Receiver', 'wpjobster' ); ?></th>
								<th width="25%"><?php _e( 'Sent on', 'wpjobster' ); ?></th>
								<th width="25%"><?php _e( 'Actions', 'wpjobster' ); ?></th>
							</tr>
						</thead>

						<tbody>

							<?php foreach ( $rows['all'] as $row ) {
								$sender   = get_userdata( $row->initiator );
								$receiver = get_userdata( $row->user ); ?>

								<tr>

									<td class="medium-column">
										<div class="title"><?php echo isset( $sender->user_login ) ? wpj_get_user_display_type( $sender->ID ) : sprintf( __( 'Deleted User (ID: %d)', 'wpjobster' ), $row->initiator ); ?></div>
										<div class="message-content" id="message_<?php echo $row->id; ?>">

											<?php echo $row->content;

											do_action( 'wpj_after_admin_private_message_content', $row ); ?>

										</div>
									</td>

									<td><?php echo isset( $receiver->user_login ) ? wpj_get_user_display_type( $receiver->ID ) : sprintf( __( 'Deleted User (ID: %d)', 'wpjobster' ), $row->user ); ?></td>

									<td class="highlighted">
										<?php echo wpj_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $row->datemade ); ?>
									</td>

									<td>

										<?php if ( $row->show_to_source == 1 && $row->show_to_destination == 1 ) { ?>

											<a href="<?php echo get_admin_url() . 'admin.php?page=jobster-messages&delete_message=' . $row->id; ?>" class="small-button gray"><?php _e( 'Delete', 'wpjobster' ); ?></a>

										<?php } else { ?>

											<a href="<?php echo get_admin_url() . 'admin.php?page=jobster-messages&permanently_delete_message=' . $row->id; ?>" class="small-button gray"><?php _e( 'Permanent Delete', 'wpjobster' ); ?></a>

											<br>

										<?php

											_e( 'Message Deleted', 'wpjobster' );

										} ?>

									</td>

								</tr>

							<?php } ?>

						</tbody>
					</table>

					<?php wpj_show_pagination_bar( $rows, [ 'at' => 'private-messages' ] );

				} else { ?>

					<div style="padding:15px; background: #fff;"><?php _e( 'There are no private messages!', 'wpjobster' ); ?></div>

				<?php } ?>

			</div>

			<!-- Transaction Messages -->
			<div id="transaction-messages">

				<?php $messages_class->deleteTransactionMessage(); ?>

				<div class="wpj-admin-top-search-form-wrapper"><?php wpj_search_user_transaction_messages_form(); ?></div>

				<?php $rows = $messages_class->getOrderRow( 'job_chatbox' );

				if ( $rows['count'] > 0 ) { ?>

					<table class="widefat post" cellspacing="0">
						<thead>
							<tr>
								<th><?php _e( 'Sender', 'wpjobster' ); ?></th>
								<th><?php _e( 'Receiver', 'wpjobster' ); ?></th>
								<th><?php _e( 'Job Owner', 'wpjobster' ); ?></th>
								<th width="20%"><?php _e( 'Job Title', 'wpjobster' ); ?></th>
								<th><?php _e( 'Sent On', 'wpjobster' ); ?></th>
								<th width="25%"><?php _e( 'Options', 'wpjobster' ); ?></th>
							</tr>
						</thead>

						<tbody>

							<?php foreach ( $rows['all'] as $row ) {
								$order       = wpj_get_job_order_by_id( $row->oid );
								$post        = get_post( $order->pid );
								$post_author = $post ? get_userdata( $post->post_author ) : '';
								$sender      = get_userdata( $row->uid );
								$receiver    = ( $post_author ) ? $post_author : get_userdata( $order->uid );
								$receiver    = $receiver == $sender ? get_userdata ( wpj_get_buyer_id( $row->oid ) ) : $receiver;?>

								<tr>
									<td class="medium-column">
										<div class="title"><?php if ( $sender ) echo wpj_get_user_display_type( $sender->ID ); ?></div>
										<div class="message-content" id="message_<?php echo $row->id; ?>"><?php echo $row->content; ?></div>
									</td>
									<td><?php if ( $receiver ) echo wpj_get_user_display_type( $receiver->ID ); ?></td>
									<td><?php if ( $post_author ) echo wpj_get_user_display_type( $post_author->ID ); ?></td>
									<td>
										<?php if ( $post ) echo '<a href="' . get_permalink( $order->pid ) . '">' . $post->post_title . '</a>'; ?>
									</td>
									<td class="highlighted"><?php echo wpj_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $row->datemade ); ?></td>
									<td>
										<a href="<?php echo get_admin_url() . 'admin.php?page=jobster-messages&delete_transaction=' . $row->id; ?>" class="small-button gray"><?php echo __( 'Delete', 'wpjobster' ); ?></a>
									</td>
								</tr>

							<?php } ?>

						</tbody>
					</table>

					<?php wpj_show_pagination_bar( $rows, [ 'at' => 'transaction-messages' ] );

				} else { ?>

					<div style="padding:15px; background: #fff;"><?php echo __( 'There are no transaction messages!', 'wpjobster' ); ?></div>

				<?php } ?>

			</div>

			<!-- Review Messages -->
			<div id="review-messages">

				<?php $messages_class->deleteReviewMessage(); ?>

				<div class="wpj-admin-top-search-form-wrapper"><?php wpj_search_user_review_messages_form(); ?></div>

				<?php $rows = $messages_class->getOrderRow( 'job_ratings' );

				if ( $rows['count'] > 0 ) { ?>

					<table class="widefat post" cellspacing="0">
						<thead>
							<tr>
								<th><?php _e( 'Review', 'wpjobster' ); ?></th>
								<th><?php _e( 'Stars', 'wpjobster' ); ?></th>
								<th><?php _e( 'Order', 'wpjobster' ); ?></th>
								<th><?php _e( 'Job', 'wpjobster' ); ?></th>
								<th><?php _e( 'Awarded On', 'wpjobster' ); ?></th>
								<th><?php _e( 'Options', 'wpjobster' ); ?></th>
							</tr>
						</thead>

						<tbody>

							<?php foreach ( $rows['all'] as $row ) {

								ob_start();
								wpj_display_rating_stars( $row->grade );
								$stars = ob_get_contents();
								ob_end_clean(); ?>

								<tr>
									<td class="medium-column">
										<div class="title"><?php echo wpj_get_user_display_type( wpj_get_buyer_id( $row->orderid ) ); ?></div>
										<div class="message-content" id="review_<?php echo $row->id; ?>"><?php echo wpj_stripslashes( wpj_stripslashes( $row->reason ) ); ?></div>
									</td>
									<td><?php echo $stars; ?></td>
									<td><a href="<?php echo wpj_get_order_link( $row->orderid ); ?>"><?php echo $row->orderid; ?></a></td>
									<td><a href="<?php echo get_permalink( $row->pid ); ?>"><?php echo get_the_title( $row->pid ); ?></a>
									</td>
									<td class="highlighted"><?php echo wpj_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $row->datemade ); ?></td>
									<td>
										<a href="<?php echo get_admin_url() . 'admin.php?page=jobster-messages&delete_review=' . $row->id . '&oid=' . $row->orderid; ?>" class="small-button gray"><?php echo __( 'Delete', 'wpjobster' ); ?></a>
									</td>
								</tr>

								<?php $response_rows = $messages_class->getOrderRow( 'job_ratings_by_seller', $row->orderid );

								if ( $response_rows['count'] > 0 ) {
									foreach ( $response_rows['all'] as $response_row ) {

										ob_start();
										wpj_display_rating_stars( $response_row->grade );
										$stars = ob_get_contents();
										ob_end_clean(); ?>

										<tr>
											<td class="medium-column">
												<div class="title"><?php echo wpj_get_user_display_type( wpj_get_seller_id( $response_row->orderid ) ); ?></div>
												<div class="message-content" id="review_<?php echo $response_row->id; ?>"><?php echo wpj_stripslashes( wpj_stripslashes( $response_row->reason ) ); ?></div>
											</td>
											<td><?php echo $stars; ?></td>
											<td><a href="<?php echo wpj_get_order_link( $response_row->orderid ); ?>"><?php echo $response_row->orderid; ?></a></td>
											<td><a href="<?php echo get_permalink( $response_row->pid ); ?>"><?php echo get_the_title( $response_row->pid ); ?></a>
											</td>
											<td class="highlighted"><?php echo wpj_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $response_row->datemade ); ?></td>
											<td>
												<a href="<?php echo get_admin_url() . 'admin.php?page=jobster-messages&delete_review_response=' . $response_row->id . '&oid=' . $response_row->orderid; ?>" class="small-button gray"><?php echo __( 'Delete response', 'wpjobster' ); ?></a>
											</td>
										</tr>

									<?php }
								}

							} ?>

						</tbody>
					</table>

					<?php wpj_show_pagination_bar( $rows, [ 'at' => 'review-messages' ] );

				} else { ?>

					<div style="padding:15px; background: #fff;"><?php echo __( 'There are no review messages!', 'wpjobster' ); ?></div>

				<?php } ?>

			</div>

		</div>
	</div>

<?php }

function wpj_search_user_private_messages_form() { ?>

	<form method="get" action="<?php bloginfo('url'); ?>/wp-admin/admin.php" class="admin-small-search-form">
		<input type="hidden" value="jobster-messages" name="page" />
		<input type="hidden" value="private-messages" name="active_tab" />
		<i class="icon search"></i>
		<input type="text" value="<?php echo WPJ_Form::get( 'search_user', '' ); ?>" name="search_user" size="20" placeholder="<?php _e( 'Search User', 'wpjobster' ); ?>" />
		<input type="submit" class="button-secondary" name="wpjobster_user_private_messages_search" value="<?php _e( 'Search', 'wpjobster' ); ?>"/>
	</form>

<?php }

function wpj_search_user_transaction_messages_form() { ?>

	<form method="get" action="<?php bloginfo('url'); ?>/wp-admin/admin.php" class="admin-small-search-form">
		<input type="hidden" value="jobster-messages" name="page" />
		<input type="hidden" value="transaction-messages" name="active_tab" />
		<i class="icon search"></i>
		<input type="text" value="<?php echo WPJ_Form::get( 'search_user', '' ); ?>" name="search_user" size="20" placeholder="<?php _e( 'Search User', 'wpjobster' ); ?>" />
		<input type="submit" class="button-secondary" name="wpjobster_user_transaction_messages_search" value="<?php _e( 'Search', 'wpjobster' ); ?>"/>
	</form>

<?php }

function wpj_search_user_review_messages_form() { ?>

	<form method="get" action="<?php bloginfo('url'); ?>/wp-admin/admin.php" class="admin-small-search-form">
		<input type="hidden" value="jobster-messages" name="page" />
		<input type="hidden" value="review-messages" name="active_tab" />
		<i class="icon search"></i>
		<input type="text" value="<?php echo WPJ_Form::get( 'search_user', '' ); ?>" name="search_user" size="20" placeholder="<?php _e( 'Search User', 'wpjobster' ); ?>" />
		<input type="submit" class="button-secondary" name="wpjobster_user_review_messages_search" value="<?php _e( 'Search', 'wpjobster' ); ?>"/>
	</form>

<?php }

class WPJ_Messages {

	public function getRowQuery( $rows_per_page = 10, $pageno = 1, $limited = false, $table = '', $oid = '' ) {
		global $wpdb;

		$user = WPJ_Form::get( 'search_user', '' );
		$uid  = ctype_digit( $user ) || is_int( $user ) ? $_GET['search_user'] : '';

		if ( ! $uid ) {
			$uid = wpj_get_user( 'ID', ['user_login' => $user], 'var' );
		}

		if ( ! $uid ) $uid = 0;

		$query = "SELECT * FROM " . $wpdb->prefix . $table;

		if ( $table == 'job_ratings' ) $query .= " WHERE awarded > 0";

		if ( $table == 'job_ratings_by_seller' && $oid ) $query .= " WHERE orderid = {$oid} AND awarded = 1";

		if ( $user && $table == 'job_pm' ) { $query .= " WHERE initiator = {$uid} OR user = {$uid}"; }

		if ( $table == 'job_chatbox' ) {
			if ( $user ) $query .= " WHERE uid = {$uid}";
			else $query .= " WHERE uid >= 1";
		}

		$query .= " ORDER BY id DESC";

		if ( $user && $table == 'job_ratings' )
			$query = "
				SELECT *
				FROM {$wpdb->prefix}job_ratings ratings, {$wpdb->prefix}job_orders orders, {$wpdb->prefix}posts posts
				WHERE orders.pid = posts.ID
					AND posts.post_author = {$uid}
					AND orders.id = ratings.orderid
					AND ratings.awarded > 0
				ORDER BY ratings.id DESC
			";

		if ( $limited ) {
			$query .= " LIMIT " . ( $pageno - 1 ) * $rows_per_page . ',' . $rows_per_page;
		}

		return $query;
	}

	public function getOrderRow( $table = '', $oid = '' ) {
		$r = [ 'all' => '', 'limited' => '', 'lastpage' => '', 'pageno' => '' ];

		global $wpdb;

		$rows_per_page = 10;

		if ( isset( $_GET['pj'] ) ) $pageno = $_GET['pj'];
		else $pageno = 1;

		$s1 = $this->getRowQuery( $rows_per_page, $pageno, false, $table, $oid );
		$s  = $this->getRowQuery( $rows_per_page, $pageno, true, $table, $oid );

		$nr       = count( $wpdb->get_results( $s1 ) );
		$lastpage = ceil( $nr / $rows_per_page );

		$r = [
			'all'      => $wpdb->get_results( $s ),
			'limited'  => $wpdb->get_results( $s1 ),
			'lastpage' => $lastpage,
			'pageno'   => $pageno,
			'count'    => $nr
		];

		return $r;
	}

	public function deletePrivateMessage() {
		if ( isset( $_GET['delete_message'] ) ) {
			$message_id = $_GET['delete_message'];
			$message    = wpj_get_pm_notify( 'user', ['id' => $message_id], 'row' );

			if ( $message ) {
				wpj_update_pm_notify( ['show_to_source' => '0', 'show_to_destination' => '0'], ['id' => $message_id] );

				wpj_refresh_user_notifications( $message->user, 'messages' );

				echo '<div class="updated fade">' . __( 'Message was deleted', 'wpjobster' ) . '</div>';
			}
		}
	}

	public function deletePermanentlyPrivateMessage() {
		if ( isset( $_GET['permanently_delete_message'] ) ) {
			$message_id = $_GET['permanently_delete_message'];
			$message    = wpj_get_pm_notify( 'user', ['id' => $message_id], 'row' );

			if ( $message ) {
				wpj_delete_pm_notify( ['id' => $message_id] );

				wpj_refresh_user_notifications( $message->user, 'messages' );

				echo '<div class="updated fade">' . __( 'Message was deleted', 'wpjobster' ) . '</div>';

			} else {
				echo '<div class="error fade">' . __( 'Message already deleted', 'wpjobster' ) . '</div>';

			}
		}
	}

	public function deleteTransactionMessage() {
		if ( isset( $_GET['delete_transaction'] ) ) {
			$transaction_id = $_GET['delete_transaction'];

			$chatbox_message = wpj_get_order_notification_message( 'oid', ['id' => $transaction_id], 'row' );

			if ( $chatbox_message ) {
				$related_order = wpj_get_job_order_by_id( $chatbox_message->oid );

				wpj_delete_order_notification( ['id' => $transaction_id] );

				wpj_refresh_user_notifications( wpj_get_seller_id( $related_order ), 'notifications' );
				wpj_refresh_user_notifications( wpj_get_buyer_id( $related_order ), 'notifications' );

				echo '<div class="updated fade">' . __( 'Message was deleted', 'wpjobster' ) . '</div>';

			} else {
				echo '<div class="error fade">' . __( 'Message already deleted', 'wpjobster' ) . '</div>';

			}
		}
	}

	public function deleteReviewMessage() {
		if ( isset( $_GET['delete_review'] ) || isset( $_GET['delete_review_response'] ) ) {
			if ( isset( $_GET['delete_review'] ) && isset( $_GET['oid'] ) ) {

				$review_id = $_GET['delete_review'];
				$oid       = $_GET['oid'];

				wpj_delete_job_seller_rating( ['orderid' => $oid] );
				wpj_delete_job_rating( ['id' => $review_id] );

				echo '<div class="updated fade">' . __( 'Review was deleted', 'wpjobster' ) . '</div>';

			} elseif ( isset( $_GET['delete_review_response'] ) && isset( $_GET['oid'] ) ) {
				wpj_delete_job_seller_rating( ['id' => $_GET['delete_review_response']] );

				echo '<div class="updated fade">' . __( 'Review response was deleted', 'wpjobster' ) . '</div>';

			}
		}
	}
}