<?php
if ( ! function_exists( 'wpj_mark_notification_as_read_by_uid' ) ) {
	function wpj_mark_notification_as_read_by_uid( $uid = '', $oid = '', $user_type = '' ) {
		if ( ! $uid ) $uid = get_current_user_id();

		if ( $user_type == 'buyer' ) {
			$buyer_uid = implode( ", ", wpj_get_chatbox_uid_by_user_type( 'buyer' ) );

			wpj_update_order_notifications_by_order_id( $oid, $uid, $buyer_uid );

			wpj_refresh_user_notifications( $uid, 'notifications' );
		}

		if ( $user_type == 'seller' ) {
			$seller_uid = implode( ", ", wpj_get_chatbox_uid_by_user_type( 'seller' ) );

			wpj_update_order_notifications_by_order_id( $oid, $uid, $seller_uid );

			wpj_refresh_user_notifications( $uid, 'notifications' );
		}
	}
}

// Mark single notification as read
if ( ! function_exists( 'wpj_mark_notification_as_read' ) ) {
	function wpj_mark_notification_as_read() {
		$uid = get_current_user_id();

		if ( isset( $_POST['notification_id'] ) ) {
			// get only unread notifications belonging to this user
			$notifications = wpj_get_notifications([
				'limit'  => 10000,
				'uid'    => $uid,
				'status' => 'unread',
			]);

			// build a list of IDs rather than querying in loop, for performance
			$allowed_to_read = [];

			foreach ( $notifications as $notification ) {
				$allowed_to_read[] = $notification->id;
			}

			$notification_id = '';

			if ( in_array( $_POST['notification_id'], $allowed_to_read ) ) {
				$notification_id = $_POST['notification_id'];
			}

			// update read status
			if ( $notification_id ) {
				wpj_update_order_notification( ['rd_receiver' => 1], ['id' => $notification_id] );
			}

			wpj_refresh_user_notifications( $uid, 'notifications' );
		}

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

// Mark all notifications as read
if ( ! function_exists( 'wpj_mark_all_notifications_as_read' ) ) {
	function wpj_mark_all_notifications_as_read() {
		$uid = get_current_user_id();

		if ( ! empty ( $_POST['all_notifications_read'] ) ) {
			// get only unread notifications belonging to this user
			$notifications = wpj_get_notifications( [
				'limit'  => 10000, // reasonable limit
				'uid'    => $uid,
				'status' => 'unread',
			] );

			// build a list of IDs rather than querying in loop, for performance
			$i = 0; $sql_in = '';

			if ( $notifications ) {
				foreach ( $notifications as $notification ) {
					if ( ++$i > 1 ) {
						$sql_in = $sql_in . ', ';
					}

					$sql_in = $sql_in . $notification->id;
				}
			}

			// update read status
			if ( ! empty( $sql_in ) ) {
				wpj_update_order_notifications( $sql_in );
			}

			wpj_refresh_user_notifications( $uid, 'notifications' );
		}
	}
}

/**
 *   0 - marked as paid
 *  -1 - marked as delivered
 *  -2 - marked as completed
 *  -8 - the seller requested cancellation
 *  -9 - the buyer requested cancellation
 * -10 - the buyer accepted mutual cancellation
 * -11 - the buyer declined mutual cancellation
 * -12 - the seller accepted mutual cancellation
 * -13 - the seller declined mutual cancellation
 * -14 - transaction was cancelled by admin
 * -15 - buyer request modification
 * -16 - mutual cancellation was aborted by seller
 * -17 - mutual cancellation was aborted by buyer
 * -18 - buyer rating
 * -19 - seller rating
 * -21 - pending order cancelled by seller
 * -22 - pending order cancelled by buyer
 * -31 - new custom extra added
 * -32 - custom extra cancelled
 * -33 - custom extra declined
 * -34 - custom extra accepted
 * -35 - order cancellation by buyer( delivery time expired );
 * -36 - new tips added
 * -37 - tips payment succes
 * -38 - tips payment failed
 * -39 - the seller requested arbitration
 * -40 - the buyer requested arbitration
 * -41 - arbitration in favor of seller - message for seller
 * -42 - arbitration in favor of seller - message for buyer
 * -43 - arbitration in favor of buyer - message for seller
 * -44 - arbitration in favor of buyer - mesage for buyer
 * -45 - arbitration was aborted by seller
 * -46 - arbitration was aborted by buyer
 * -47 - order accepted by seller
 * -48 - order rejected by seller
 * -49 - the seller requested extended delivery time
 * -50 - the seller cancelled extended delivery time
 * -51 - the buyer accepted requested extended delivery time
 * -52 - the buyer declined requested extended delivery time
 * -53 - milestone delivered
 * -54 - milestone completed
 **/
if ( ! function_exists( 'wpj_get_notification_message_by_id' ) ) {
	function wpj_get_notification_message_by_id( $notification_id = '', $page = '' ) {
		$row = wpj_get_order_notification_by_notification_id( $notification_id );

		$current_uid = get_current_user_id();

		$transaction_number = wpj_camouflage_oid( $row->oid, $row->otm );
		$notification_date  = wpj_date( wpj_get_option( 'date_format' ) . ' - ' . wpj_get_option( 'time_format' ), $row->tm );

		$buyer  = get_userdata( $row->bid );
		$seller = get_userdata( $row->sid );

		$buyer_username  = is_object( $buyer ) ? wpj_get_user_display_type( $buyer->ID ) : __( 'a deleted user', 'wpjobster' );
		$seller_username = is_object( $seller ) ? wpj_get_user_display_type( $seller->ID ) : __( 'a deleted user', 'wpjobster' );

		if ( $current_uid == $row->sid ) {
			$displayname = $page == 'api' ? $seller_username : $buyer_username;

		} elseif ( $current_uid == $row->bid ) {
			$displayname = $page == 'api' ? $buyer_username : $seller_username;

		} else {
			$displayname = __( 'a deleted user', 'wpjobster' );

		}

		$code = $row->code;

		if ( $code > 0 ) {
			$user = get_userdata( $code );

			if ( $user && is_object( $user ) ) {
				if ( is_super_admin( $code ) ) {
					$displayname = wpj_get_user_display_type( $user->ID );
				}

				$content = __( 'You have a new message from %2$s related to transaction %1$s', 'wpjobster' );

			} else {
				$content = __( 'Order %1$s was updated by %2$s', 'wpjobster' );

			}

			$icon_class = 'sent green';

		} else {
			if ( $code == 0 ) {
				$content    = __( 'You have a new order from %2$s. Order ID: %1$s.', 'wpjobster' );
				$icon_class = 'sent green';

			} elseif ( $code == -1 ) {
				$content    = __( '%2$s has delivered the order %1$s', 'wpjobster' );
				$icon_class = 'delivered green';

			} elseif ( $code == -2 ) {
				$content    = __( 'Order %1$s was marked complete by %2$s', 'wpjobster' );
				$icon_class = 'accepted green';

			} elseif ( $code == -8 || $code == -9 ) {
				$content    = __( '%2$s has requested to cancel order %1$s', 'wpjobster' );
				$icon_class = 'declined red';

			} elseif ( $code == -10 || $code == -12 ) {
				$content    = __( '%2$s has accepted cancellation request for order %1$s', 'wpjobster' );
				$icon_class = 'accepted green';

			} elseif ( $code == -11 || $code == -13 ) {
				$content    = __( '%2$s has declined cancellation request for order %1$s', 'wpjobster' );
				$icon_class = 'declined2 red';

			} elseif ( $code == -14 ) {
				$content    = __( 'Order %1$s was cancelled by admin', 'wpjobster' );
				$icon_class = 'admin-action red';

			} elseif ( $code == -15 ) {
				$content    = __( '%2$s has requested modification for order %1$s', 'wpjobster' );
				$icon_class = 'modification orange';

			} elseif ( $code == -16 || $code == -17 ) {
				$content    = __( '%2$s has aborted cancellation for order %1$s', 'wpjobster' );
				$icon_class = 'declined2 red';

			} elseif ( $code == -18 ) {
				$content    = __( '%2$s has rated your order %1$s', 'wpjobster' );
				$icon_class = 'star orange';

			} elseif ( $code == -19 ) {
				$content    = __( '%2$s has replied to your feedback for order %1$s', 'wpjobster' );
				$icon_class = 'star orange';

			} elseif ( $code == -21 || $code == -22 ) {
				if ( $current_uid == $row->bid ) {
					$content = __( 'You have Cancelled the pending order ID: %1$s', 'wpjobster' );

				} else {
					$content = __( '%2$s has Cancelled the pending order ID: %1$s', 'wpjobster' );

				}

				$icon_class = 'declined2 red';

			} elseif ( $code == -31 ) {
				$content    = apply_filters( 'wpj_added_new_custom_extra_string_filter', __( '%2$s added new custom extra for order %1$s', 'wpjobster' ), $row );
				$icon_class = 'sent green';

			} elseif ( $code == -32 ) {
				$content    = apply_filters( 'wpj_cancelled_custom_extra_string_filter', __( '%2$s cancelled custom extra for order %1$s', 'wpjobster' ), $row );
				$icon_class = 'declined red';

			} elseif ( $code == -33 ) {
				$content    = apply_filters( 'wpj_declined_custom_extra_string_filter', __( '%2$s declined custom extra for order %1$s', 'wpjobster' ), $row );
				$icon_class = 'declined red';

			} elseif ( $code == -34 ) {
				$content    = apply_filters( 'wpj_accepted_custom_extra_string_filter', __( '%2$s accepted custom extra for order %1$s', 'wpjobster' ), $row );
				$icon_class = 'accepted green';

			} elseif ( $code == -35 ) {
				$content    = __( '%2$s cancelled the order %1$s', 'wpjobster' );
				$icon_class = 'declined red';

			} elseif ( $code == -37 ) {
				$content    = __( '%2$s added new tips for order %1$s', 'wpjobster' );
				$icon_class = 'accepted green';

			} elseif ( $code == -39 || $code == -40 ) {
				$content    = __( '%2$s has requested arbitration the order %1$s', 'wpjobster' );

				$icon_class = 'arbitration green';
			} elseif ( $code == -41 || $code == -42 ) {
				if ( $current_uid == $row->sid ) {
					$content    = __( 'Arbitration was decided in your favor', 'wpjobster' );
					$icon_class = 'admin-action green';

				} else {
					$content    = __( 'Arbitration was decided in favor of %2$s', 'wpjobster' );
					$icon_class = 'admin-action green';

				}

			} elseif ( $code == -43 || $code == -44 ) {
				if ( $current_uid == $row->bid ) {
					$content    = __( 'Arbitration was decided in your favor', 'wpjobster' );
					$icon_class = 'admin-action green';

				} else {
					$content    = __( 'Arbitration was decided in favor of %2$s', 'wpjobster' );
					$icon_class = 'admin-action green';

				}

			} elseif ( $code == -45 || $code == -46 ) {
				$content    = __( '%2$s has aborted arbitration for order %1$s', 'wpjobster' );
				$icon_class = 'declined2 red';

			} elseif ( $code == -47 ) {
				$content    = __( '%2$s accepted the order %1$s', 'wpjobster' );
				$icon_class = 'accepted green';

			} elseif ( $code == -48 ) {
				$content    = __( '%2$s rejected the order %1$s', 'wpjobster' );
				$icon_class = 'declined2 red';

			} elseif ( $code == -49 ) {
				$content    = __( '%2$s has requested an extension of the delivery time for order %1$s', 'wpjobster' );
				$icon_class = 'modification orange';

			} elseif ( $code == -50 ) {
				$content    = __( '%2$s has aborted extension of the delivery time for order %1$s', 'wpjobster' );
				$icon_class = 'declined2 red';

			} elseif ( $code == -51 ) {
				$content    = __( '%2$s has accepted extension of the delivery time for order %1$s', 'wpjobster' );
				$icon_class = 'accepted green';

			} elseif ( $code == -52 ) {
				$content    = __( '%2$s has declined extension of the delivery time for order %1$s', 'wpjobster' );
				$icon_class = 'declined2 red';

			} else {
				$content    = __( 'Order %1$s was updated', 'wpjobster' );
				$icon_class = 'sent';

			}
		}

		$notification_filter = apply_filters( 'wpj_notification_content_filter', ['content' => $content, 'icon_class' => $icon_class], $code );

		$content = sprintf( $notification_filter['content'], $transaction_number, $displayname );

		return [
			'content'    => $content,
			'icon_class' => $notification_filter['icon_class'],
			'date'       => $notification_date
		];
	}
}

if ( ! function_exists( 'wpj_update_user_notifications' ) ) {
	function wpj_update_user_notifications( $args = [] ) {
		$defaults = [
			'user1'       => get_current_user_id(),
			'user2'       => '',
			'type'        => 'notifications',
			'number'      => +1,
			'notify_id'   => '',
			'notify_type' => '',
			'order_id'    => '',
		];

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

		/**
		 * @var number $user1
		 * @var number $user2
		 * @var string $type
		 * @var number $number
		 * @var number $notify_id
		 * @var string $notify_type
		 * @var number $order_id
		 */
		extract( $args );

		if ( $user1 ) {
			if ( $type == 'messages' || $type == 'notifications' ) {
				$type_number = get_user_meta( $user1, $type . '_number', true );

				if ( is_numeric( $type_number ) && is_numeric( $number ) ) {
					$type_number = $type_number + $number;

					update_user_meta( $user1, $type . '_number', $type_number );

				} else {
					$type_number = wpj_refresh_user_notifications( $user1, $type );

				}

				update_user_meta( $user1, 'notification_info', $args );

				do_action( 'wpj_after_notification_is_sent', $notify_id, $notify_type, $user1 );

				return $type_number;

			} else {
				wpj_refresh_user_notifications( $user1, $type );

				return true;

			}
		}

		return false;
	}
}

if ( ! function_exists( 'wpj_refresh_user_notifications' ) ) {
	function wpj_refresh_user_notifications( $uid = 0, $type = '' ) {
		if ( ! $uid ) $uid = get_current_user_id();

		if ( $uid ) {
			if ( ! $type || $type == 'messages' ) {
				$messages_number = wpj_get_pm_notify( 'COUNT( * )', ['user' => $uid, 'show_to_destination' => 1, 'rd' => 0], 'var' );

				update_user_meta( $uid, 'messages_number', $messages_number );
			}

			if ( ! $type || $type == 'notifications' ) {
				$args = [
					'limit'  => 10000,
					'uid'    => $uid,
					'status' => 'unread',
				];

				$notifications_number = count( wpj_get_notifications( $args ) );

				update_user_meta( $uid, 'notifications_number', $notifications_number );
			}

			update_user_meta( $uid, 'notification_info', [
				'user1'       => $uid,
				'user2'       => '',
				'type'        => '',
				'number'      => isset( $notifications_number ) ? $notifications_number : 0,
				'notify_id'   => '',
				'notify_type' => '',
				'order_id'    => '',
			] );

			if ( ! empty( $messages_number ) )
				return $messages_number;

			elseif ( ! empty( $notifications_number ) )
				return $notifications_number;

			return true;
		}

		return false;
	}
}

if ( ! function_exists( 'wpj_save_user_subscribed_notifications' ) ) {
	function wpj_save_user_subscribed_notifications() {
		$notifications_array = wpj_get_notifications_array();

		unset( $notifications_array['admin'] );
		unset( $notifications_array['registration'] );
		unset( $notifications_array['account_segregation'] );

		if ( $notifications_array ) {
			$user_id = get_current_user_id();

			// EMAIL NOTIFICATIONS
			if ( isset( $_POST['email_notifications'] ) ) {
				$email_notifications = $_POST['email_notifications'];

				$all_email_notifications = [];

				// ARRAY ALL EMAIL NOTIFICATIONS
				foreach ( $notifications_array as $email_category ) {
					foreach ( $email_category["items"] as $reason => $key ) {
						$all_email_notifications[] = 'uz_email_' . $reason . '_enable';
					}
				}

				// ARRAY ALL CHECKED NOTIFICATIONS
				$all_email_notifications_checked = [];

				foreach ( $all_email_notifications as $reason => $val ) {
					if ( isset( $email_notifications[$reason] ) ) {
						$all_email_notifications_checked[] = $email_notifications[$reason];
					}
				}

				// ARRAY ALL UNCHECKED NOTIFICATIONS
				$all_email_notifications_no_checked = array_diff( $all_email_notifications, $all_email_notifications_checked );

				// UPDATE CHECK NOTIFICATIONS
				foreach ( $all_email_notifications_checked as $chk ) {
					update_user_meta( $user_id, $chk, 'yes' );
				}

				// UPDATE UNCHECKED NOTIFICATION
				foreach ( $all_email_notifications_no_checked as $no_chk ) {
					update_user_meta( $user_id, $no_chk, 'no' );
				}

			} else {
				// UPDATE ALL EMAIL NOTIFICATIONS TO NO
				foreach ( $notifications_array as $email_category ) {
					foreach ( $email_category["items"] as $reason => $key ) {
						update_user_meta( $user_id, 'uz_email_' . $reason . '_enable', 'no' );
					}
				}

			}

			// SMS NOTIFICATIONS
			if ( wpj_get_option( 'wpjobster_sms_gateways_enable' ) && wpj_get_option( 'wpjobster_sms_gateways_enable' ) != '-' ) {
				if ( isset( $_POST['sms_notifications'] ) ) {
					$sms_notifications = $_POST['sms_notifications'];

					$all_sms_notifications = [];

					// ARRAY ALL SMS NOTIFICATIONS
					foreach ( $notifications_array as $email_category ) {
						foreach ( $email_category["items"] as $reason => $key ) {
							$all_sms_notifications[] = 'uz_sms_' . $reason . '_enable';
						}
					}

					// ARRAY ALL CHECKED NOTIFICATIONS
					$all_sms_notifications_checked = [];
					foreach ( $all_sms_notifications as $reason => $val ) {
						if ( isset( $sms_notifications[$reason] ) ) {
							$all_sms_notifications_checked[] = $sms_notifications[$reason];
						}
					}

					// ARRAY ALL UNCHECKED NOTIFICATIONS
					$all_sms_notifications_no_checked = array_diff( $all_sms_notifications, $all_sms_notifications_checked );

					// UPDATE CHECK NOTIFICATIONS
					foreach ( $all_sms_notifications_checked as $chk ) {
						update_user_meta( $user_id, $chk, 'yes' );
					}

					// UPDATE UNCHECKED NOTIFICATION
					foreach ( $all_sms_notifications_no_checked as $no_chk ) {
						update_user_meta( $user_id, $no_chk, 'no' );
					}

				} else {
					// UPDATE ALL SMS NOTIFICATIONS TO NO
					foreach ( $notifications_array as $email_category ) {
						foreach ( $email_category["items"] as $reason => $key ) {
							update_user_meta( $user_id, 'uz_sms_' . $reason . '_enable', 'no' );
						}
					}

				}
			}
		}

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

if ( ! function_exists( 'wpj_get_notifications_by_user_type' ) ) {
	function wpj_get_notifications_by_user_type( $notifications_array, $uid = '' ) {
		if ( ! $uid ) {
			$uid = get_current_user_id();
		}

		unset( $notifications_array['admin'] );
		unset( $notifications_array['registration'] );
		unset( $notifications_array['account_segregation'] );

		if ( wpj_get_user_account_type( $uid ) != 'seller' ) {
			unset( $notifications_array['jobs'] );
			unset( $notifications_array['subscriptions'] );

			unset( $notifications_array['job_orders']['items']['purchased_seller'] );
			unset( $notifications_array['job_orders']['items']['cancel_buyer'] );
			unset( $notifications_array['job_orders']['items']['cancel_acc_buyer'] );
			unset( $notifications_array['job_orders']['items']['cancel_decl_buyer'] );
			unset( $notifications_array['job_orders']['items']['cancel_abort_buyer'] );
			unset( $notifications_array['job_orders']['items']['cancel_ord_expired_seller'] );
			unset( $notifications_array['job_orders']['items']['ord_expires_soon'] );
			unset( $notifications_array['job_orders']['items']['mod_buyer'] );
			unset( $notifications_array['job_orders']['items']['extend_delivery_accept'] );
			unset( $notifications_array['job_orders']['items']['extend_delivery_decline'] );
			unset( $notifications_array['job_orders']['items']['order_complete'] );
			unset( $notifications_array['job_orders']['items']['new_feedback'] );

			unset( $notifications_array['arbitration']['items']['arb_request_closed_seller'] );

			unset( $notifications_array['custom_offers']['items']['new_request'] );
			unset( $notifications_array['custom_offers']['items']['offer_acc_seller'] );
			unset( $notifications_array['custom_offers']['items']['offer_decl'] );

			unset( $notifications_array['custom_offer_orders']['items']['cancel_offer_buyer'] );
			unset( $notifications_array['custom_offer_orders']['items']['cancel_offer_acc_buyer'] );
			unset( $notifications_array['custom_offer_orders']['items']['cancel_offer_decl_buyer'] );
			unset( $notifications_array['custom_offer_orders']['items']['cancel_offer_abort_buyer'] );
			unset( $notifications_array['custom_offer_orders']['items']['mod_offer_buyer'] );
			unset( $notifications_array['custom_offer_orders']['items']['order_offer_complete'] );
			unset( $notifications_array['custom_offer_orders']['items']['new_offer_feedback'] );

			unset( $notifications_array['custom_extras']['items']['decline_custom_extra'] );
			unset( $notifications_array['custom_extras']['items']['custom_extra_paid_new_seller'] );
			unset( $notifications_array['custom_extras']['items']['custom_extra_cancelled_by_admin_seller'] );

			unset( $notifications_array['tips']['items']['tips_paid_new'] );

			unset( $notifications_array['milestones']['items']['milestone_paid_new_seller'] );
			unset( $notifications_array['milestones']['items']['decline_milestone'] );
			unset( $notifications_array['milestones']['items']['complete_milestone'] );

			unset( $notifications_array['appointments']['items']['new_appointment_seller'] );
			unset( $notifications_array['appointments']['items']['upcoming_appointment_seller'] );
		}

		return $notifications_array;
	}
}