<?php
if ( ! function_exists( 'wpj_request_modification' ) ) {
	function wpj_request_modification( $oid = '', $message = '' ) {
		if ( ! is_demo_user() && is_user_logged_in() ) {
			$oid     = WPJ_Form::post( 'oid', $oid );
			$message = WPJ_Form::post( 'message_request_modification', $message );

			if ( ! $oid ) $oid = get_query_var( 'oid' );

			if ( $oid ) {
				$order = wpj_get_job_order_by_id( $oid );

				if ( $order ) {
					$seller_id = get_post_field( 'post_author', $order->pid );

					// Update order
					wpj_update_job_order(
						[
							'message_request_modification' => $message,
							'request_modification'         => 1,
							'date_request_modification'    => current_time( 'timestamp', 1 ),
							'done_seller'                  => 0,
							'date_finished'                => 0
						],
						['id' => $order->id]
					);

					// Insert notification
					$this_notification = wpj_insert_order_notification( ['uid' => -15, 'oid' => $order->id, 'content' => $message], ['%d', '%d', '%s'] );

					if ( $this_notification > 0 ) {
						// Update notifications
						wpj_update_user_notifications([
							'user1'       => $seller_id,
							'user2'       => get_current_user_id(),
							'type'        => 'notifications',
							'number'      => +1,
							'notify_id'   => $this_notification,
							'notify_type' => 'mod_buyer',
							'order_id'    => $order->id
						]);

						// Send emails
						if ( wpj_is_custom_offer( $order->pid ) ) {
							wpj_modify_custom_offer( $order->id, $seller_id );

						} else {
							wpj_notify_user_translated( 'mod_buyer', $seller_id, [
								'##sender_username##'       => wpj_get_user_display_type( get_current_user_id() ),
								'##transaction_number##'    => wpj_camouflage_oid( $order->id, $order->date_made ),
								'##transaction_page_link##' => wpj_get_order_link( $order->id ),
								'##job_name##'              => $order->job_title,
								'##job_link##'              => urldecode( get_permalink( $order->pid ) )
							]);

						}
					}
				}
			}
		}

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