<?php
/* Get interlocutor from URL */
if ( ! function_exists( 'wpj_get_pm_interlocutor_from_url' ) ) {
	function wpj_get_pm_interlocutor_from_url( $ret_type = 'data' ) {
		global $wp_query;

		$interlocutor_id = $interlocutor_data = '';

		$url_user = isset( $wp_query->query_vars['pg'] ) ? urldecode( $wp_query->query_vars['pg'] ) : '';

		if ( isset( $_GET['username'] ) || isset( $_GET['user_id'] ) || $url_user ) {

			if ( isset( $_GET['username'] ) ) {
				$interlocutor_data = get_user_by( 'login', WPJ_Form::get( 'username' ) );
				$interlocutor_id   = isset( $interlocutor_data->ID ) ? $interlocutor_data->ID : '';

			} elseif ( isset( $_GET['user_id'] ) ) {
				$interlocutor_id   = WPJ_Form::get( 'user_id' );
				$interlocutor_data = get_userdata( $interlocutor_id );

			} elseif ( $url_user ) {
				if ( is_numeric( $url_user ) ) {
					$interlocutor_data = wpj_get_userdata( $url_user );
					$interlocutor_id   = $url_user;

				} elseif ( is_string( $url_user ) ) {
					$interlocutor_data = get_user_by( 'login', $url_user );
					$interlocutor_id   = isset( $interlocutor_data->ID ) ? $interlocutor_data->ID : '';

				}

			}

		}

		if ( $ret_type == 'id' ) {
			return $interlocutor_id;
		}

		return $interlocutor_data;
	}
}

/* Get message job or request post */
if ( ! function_exists( 'wpj_get_message_post_id' ) ) {
	function wpj_get_message_post_id( $message ) {
		$message_with_title = explode( '\n', $message );

		if ( ! empty( $message_with_title[0] ) ) {
			$post = wpj_get_page_by_title( $message_with_title[0], 'request' );

			if ( ! $post ) {
				$post = wpj_get_page_by_title( $message_with_title[0], 'job' );
			}

			$pid = 0;

			if (
				$post
				&& $post->post_status == 'publish'
				&& ( $post->post_type == 'job' || $post->post_type == 'request' )
				&& get_post_meta( $post->ID, 'active', true ) == 1
				&& $post->post_name
			) {
				$pid = $post->ID;
			}

			unset( $message_with_title[0] );

			return [
				'id'      => $pid,
				'message' => implode( ' ', $message_with_title )
			];

		}

		return $message;
	}
}

/* Mark message as read */
if ( ! function_exists( 'wpj_mark_pm_as_read' ) ) {
	function wpj_mark_pm_as_read( $message ) {
		if ( ! is_object( $message ) )
			$message = wpj_get_pm_notify( 'id, rd, user', ['id' => $message], 'row' );

		wpj_update_pm_notify( ['rd' => 1, 'readdate' =>current_time( 'timestamp', 1 )], ['id' => $message->id] );

		if ( $message->rd != 1 ) {
			wpj_refresh_user_notifications( $message->user, 'messages' );
		}

		return false;
	}
}

/* Archive conversation */
if ( ! function_exists( 'wpj_archive_conversation' ) ) {
	function wpj_archive_conversation( $user1 = '', $user2 = '' ) {
		if ( ! $user1 ) $user1 = get_current_user_id();
		if ( ! $user2 ) $user2 = WPJ_Form::post( 'interlocutor' );

		if ( ! is_demo_user() ) {
			if ( ! wpj_users_have_conversations( $user2, $user1 ) ) {
				wpj_insert_pm_notify(
					[
						'content'             => 'Archived from chat',
						'datemade'            => current_time( 'timestamp', 1 ),
						'initiator'           => $user1,
						'user'                => $user2,
						'show_to_source'      => 0,
						'show_to_destination' => 0,
						'rd'                  => 1,
						'readdate'            => current_time( 'timestamp', 1 )
					],
					['%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d']
				);
			}

			wpj_update_conversation( $user1, $user2, 'archive' );
		}

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

/* Unarchive conversation */
if ( ! function_exists( 'wpj_unarchive_conversation' ) ) {
	function wpj_unarchive_conversation( $user1 = '', $user2 = '' ) {
		if ( ! $user1 ) $user1 = get_current_user_id();
		if ( ! $user2 ) $user2 = WPJ_Form::post( 'interlocutor' );

		if ( ! is_demo_user() ) wpj_update_conversation( $user1, $user2, 'unarchive' );

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

/* Delete conversation */
if ( ! function_exists( 'wpj_delete_conversation' ) ) {
	function wpj_delete_conversation( $user1 = '', $user2 = '' ) {
		if ( ! $user1 ) $user1 = get_current_user_id();
		if ( ! $user2 ) $user2 = WPJ_Form::post( 'interlocutor' );

		if ( ! is_demo_user() ) wpj_update_conversation( $user1, $user2, 'delete' );

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

/* Delete message */
if ( ! function_exists( 'wpj_delete_message' ) ) {
	function wpj_delete_message( $user1 = '', $user2 = '', $message_id = '' ) {
		if ( ! $user1 )      $user1      = get_current_user_id();
		if ( ! $user2 )      $user2      = WPJ_Form::post( 'interlocutor' );
		if ( ! $message_id ) $message_id = WPJ_Form::post( 'message_id' );

		if ( ! is_demo_user() ) {
			$row = wpj_get_pm_notify( 'id, initiator, user', ['id' => $message_id], 'row' );

			if ( isset( $row->id ) ) {
				if ( $user1 == $row->initiator ) {
					wpj_update_pm_notify( ['show_to_source' => 0], ['id' => $row->id] );

				} elseif ( $user1 == $row->user ) {
					wpj_update_pm_notify( ['show_to_destination' => 0], ['id' => $row->id] );

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

				}
			}
		}

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

/* Send new message */
if ( ! function_exists( 'wpj_send_message' ) ) {
	function wpj_send_message() {
		if ( WPJ_Form::post( 'request_id' ) ) $post = get_post( WPJ_Form::post( 'request_id' ) );
		elseif ( WPJ_Form::post( 'job_id' ) ) $post = get_post( WPJ_Form::post( 'job_id' ) );

		$pm_message = ! empty( $post ) ? $post->post_title . '\n' . $_POST['message'] : $_POST['message'];

		if ( ! is_demo_user() ) {
			wpj_save_private_message( [
				'content'      => trim( nl2br( strip_tags( htmlspecialchars( wpj_encode_emoji( $pm_message ) ) ) ) ),
				'datemade'     => current_time( 'timestamp', 1 ),
				'initiator'    => get_current_user_id(),
				'user'         => $_POST['otheruid'],
				'attached'     => WPJ_Form::post( 'upload' ),
				'img_attached' => WPJ_Form::post( 'img_upload' ),
			] );
		}

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

/* Save message to database */
if ( ! function_exists( 'wpj_save_private_message' ) ) {
	function wpj_save_private_message( $args ) {
		$defaults = [
			'content'              => '',
			'datemade'             => current_time( 'timestamp', 1 ),
			'initiator'            => get_current_user_id(),
			'user'                 => 0,
			'attached'             => '',
			'img_attached'         => '',
			'custom_offer'         => 0,
			'associate_request_id' => 0,
			'associate_job_id'     => 0,
		];

		$args = wp_parse_args( $args, $defaults );

		$this_pm = wpj_insert_pm_notify(
			[
				'content'              => $args['content'],
				'datemade'             => $args['datemade'],
				'initiator'            => $args['initiator'],
				'user'                 => $args['user'],
				'attached'             => $args['attached'],
				'custom_offer'         => $args['custom_offer'],
				'associate_request_id' => $args['associate_request_id'],
				'associate_job_id'     => $args['associate_job_id'],
				'more_details'         => $args['img_attached']
			],
			['%s', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s']
		);

		wpj_update_user_notifications( [
			'user1'       => $args['user'],
			'user2'       => $args['initiator'],
			'type'        => 'messages',
			'number'      => +1,
			'notify_id'   => $this_pm,
			'notify_type' => 'new_message',
			'order_id'    => $args['custom_offer']
		] );

		if ( $args['attached'] ) {
			$pm_files_array = explode( ',', $args['attached'] );

			if ( $pm_files_array ) {
				foreach ( $pm_files_array as $attachment ) {
					add_post_meta( $attachment, 'pm_id', $this_pm );

					if ( $args['custom_offer'] == -1 )
						add_post_meta( $attachment, 'is_custom_offer', $this_pm );

					else
						add_post_meta( $attachment, 'is_private_message', $this_pm );
				}
			}
		}

		if ( $args['img_attached'] ) {
			$pm_images_array = explode( ',', $args['img_attached'] );

			if ( $pm_images_array ) {
				foreach ( $pm_images_array as $img_attachment ) {
					add_post_meta( $img_attachment, 'pm_id', $this_pm );

					if ( $args['custom_offer'] == -1 )
						add_post_meta( $img_attachment, 'is_custom_offer', $this_pm );

					else
						add_post_meta( $img_attachment, 'is_private_message', $this_pm );
				}
			}
		}

		if ( $args['custom_offer'] == -1 ) $reason = 'new_request';
		elseif ( $args['custom_offer'] > 0 ) $reason = 'new_offer';
		else $reason = 'new_message';

		$last_login_time = get_user_meta( $args['user'], 'last_user_login', true ) ?: 60000;
		$time_difference = $last_login_time ? ( current_time( 'timestamp', 1 ) - $last_login_time ) / 60 : 1000; // 1000 to show offline deleted users
		$mins            = ( int ) $time_difference;

		if ( $mins > 5 ) {
			wpj_notify_user_translated( $reason, $args['user'], [
				'##sender_username##'         => wpj_get_user_display_type( $args['initiator'] ),
				'##private_message_link##'    => wpj_get_pm_link( $args['initiator'] ),
				'##private_message_excerpt##' => wpj_apply_filter_to_string( wpj_stripslashes( wpj_trim( $args['content'], 55, '...' ) ), true, 'privatemessages' ),
				'##private_message_content##' => wpj_apply_filter_to_string( wpj_stripslashes( $args['content'] ), true, 'privatemessages' )
			] );
		}

		do_action( 'wpj_after_pm_is_sent', $this_pm, 'messages' );

		return $this_pm;
	}
}

/* Save enter key option */
if ( ! function_exists( 'wpj_save_pm_enter_key' ) ) {
	function wpj_save_pm_enter_key() {
		if ( $_POST['value'] == 'true' )
			update_user_meta( get_current_user_id(), 'pm_enter_key_enabled', 1 );

		else
			update_user_meta( get_current_user_id(), 'pm_enter_key_enabled', 0 );

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

/* Filter the message */
if ( ! function_exists( 'wpj_filter_message' ) ) {
	function wpj_filter_message( $message = '' ) {
		$message = WPJ_Form::post( 'message', $message );

		if ( $message ) {
			echo wpj_make_links_clickable( wpj_apply_filter_to_string( wpj_stripslashes( $message ), true, 'privatemessages' ) );
		}

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

/* Add class to PM page by scren type */
if ( ! function_exists( 'wpj_add_pm_class_to_wrapper' ) ) {
	function wpj_add_pm_class_to_wrapper( $classes ) {
		if ( is_page( wpj_get_option( 'wpjobster_my_account_priv_mess_page_id' ) ) ) {
			$classes .= ' is-page-pm is-page-without-chat';

			if ( wpj_get_pm_interlocutor_from_url() ) $classes .= ' is-page-pm-single';
		}

		return $classes;
	}
}

/* Remove 'admin-bar' class from PM page */
if ( ! function_exists( 'wpj_remove_admin_bar_class_from_pm_page' ) ) {
	function wpj_remove_admin_bar_class_from_pm_page( $classes ) {
		if ( is_page( wpj_get_option( 'wpjobster_my_account_priv_mess_page_id' ) ) ) {
			$classes = array_diff( $classes, ['admin-bar'] );
		}

		return $classes;
	}
}