<?php
if ( ! function_exists( 'wpj_mark_order_as_delivered' ) ) {
	function wpj_mark_order_as_delivered( $oid = '', $forced = false ) {
		if ( ! is_user_logged_in() ) { die(); }

		if ( ! is_demo_user() ) {
			$oid = WPJ_Form::post( 'oid', $oid );

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

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

				if ( $order ) {
					if (
						( ( get_post_field( 'post_author', $order->pid ) == get_current_user_id() || $forced ) )
						&& $order->closed != 1
						&& $order->request_cancellation_from_seller != 1
						&& $order->request_cancellation_from_buyer != 1
					) {
						if ( $order->done_seller != 1 ) {
							do_action( 'wpj_before_order_marked_as_delivered', $order->id );

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

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

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

								if ( wpj_is_custom_offer( $order->pid ) ) {
									wpj_deliver_custom_offer( $order->id, $order->uid );

								} else {
									wpj_notify_user_translated( 'order_delivered', $order->uid, [
										'##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 ) )
									]);

								}
							}

							do_action( 'wpj_after_order_marked_as_delivered', $order->id );
						}
					}
				}
			}
		}

		if ( wpj_is_ajax_call() ) wp_die();

	}
}

// HELPERS

if ( ! function_exists( 'wpj_is_order_delivered' ) ) {
	function wpj_is_order_delivered( $order = '' ) {
		if ( ! $order ) $order = get_query_var( 'oid' );

		if ( ! is_object( $order ) ) $order = wpj_get_job_order_by_id( $order );

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

		$delivered = 0;

		if ( get_current_user_id() != $seller_id ) {
			if ( $order->done_seller == 1 ) $delivered = 1;
		}

		if ( get_current_user_id() == $seller_id ) {
			if ( $order->done_seller == 1 ) $delivered = 1;
			if ( $order->done_seller == -1 ) $delivered = -1;
		}

		return $delivered;
	}
}