<?php
if (!defined('ABSPATH')) {
	exit;
} // Exit if accessed directly.

/**
 * Run Cron to change expired listings status/premium value
 *
 * @return  int $remaining_listing_count
 */

add_action('init', 'wre_expired_listings_cron');

function wre_expired_listings_cron() {
    if (! wp_next_scheduled ( 'wre_expired_listing_action' )) {
		wp_schedule_event(time(), 'daily', 'wre_expired_listing_action');
    }
}

add_action('wre_expired_listing_action', 'wre_expired_listing_action_callback');

function wre_expired_listing_action_callback() {

	$subscriptions = get_posts(array(
		'post_type'			=> 'wre-subscription',
		'post_status'		=>	'any',
		'posts_per_page'	=>	-1,
		'fields'			=>	'ids',
		'meta_query' => array(
			'relation'	=> 'OR',
			array(
				'relation'	=> 'AND',
				array(
					'key'     => '_wre_subscription_status',
					'value'   => 'expired',
					'compare' => '!=',
				),
				array(
					'key'     => '_wre_subscription_status',
					'value'   => 'cancelled',
					'compare' => '!=',
				)
			),
			array(
				'key'     => '_wre_subscription_status',
				'value'   => 'expired',
				'compare' => 'NOT EXISTS',
			),
		),
	));

	if( !empty($subscriptions) ) {
		$expired_listings = array();
		foreach($subscriptions as $subscription) {
			$subscription_details = get_post_meta( $subscription, '_wre_subscription_details', true );
			$expiry_date = $subscription_details['expiry_date'];

			if( time() > $expiry_date ) {
				$listings = wre_get_subscription_listings($subscription);
				$expired_listings = array_merge( $selected_listings, $listings );
				update_post_meta( $subscription, '_wre_subscription_status', 'expired' );
			}
		}
		if(!empty($expired_listings)) {
			$action = wre_option( 'wre_after_expiration' );
			foreach( $expired_listings as $expired_listing ) {
				if( $action == 'mark-free' ) {
					update_post_meta( $expired_listing, '_wre_listing_premium', '' );
				} else if( $action == 'draft' ) {
					$my_listing = array(
						'ID'			=> $expired_listing,
						'post_status'	=> 'draft'
					);
					wp_update_post( $my_listing );
				}
			}
		}
	}
}

if ( ! function_exists( 'wre_get_subscription_listings' ) ) {
	/**
	 * Get Listings by subscription id
	 * @param	$subscription_id, $allowed_listings
	 *
	 * @return  array $listings
	 */
	function wre_get_subscription_listings($subscription_id, $allowed_listings = -1) {
		$listings = get_posts(array(
			'post_type'			=> 'listing',
			'post_status'		=>	'any',
			'meta_key'			=>	'_wre_subscription_id',
			'meta_value'		=>	$subscription_id,
			'posts_per_page'	=>	$allowed_listings,
			'fields'			=>	'ids'
		));
		return $listings;
	}
}

if ( ! function_exists( 'wre_get_subscription_premium_listings' ) ) {
	/**
	 * Get Premium Listings by subscription id
	 * @param	$subscription_id, $allowed_listings
	 *
	 * @return  array $listings
	 */
	function wre_get_subscription_premium_listings($subscription_id, $allowed_listings = -1) {
		$user_id = get_current_user_id();
		$listings = get_posts(array(
			'post_type'			=> 'listing',
			'post_status'		=>	'any',
			'meta_key'			=>	'_wre_subscription_id',
			'posts_per_page'	=>	$allowed_listings,
			'fields'			=>	'ids',
			'author'      => $user_id,
			'meta_query' => array(
				'relation'	=> 'AND',
				array(
					'key'     => '_wre_subscription_id',
					'value'   => $subscription_id,
					'compare' => '=',
				),
			),
		));
		return $listings;
	}
}

if ( ! function_exists( 'wre_get_paypal_payment_link' ) ) {
	/**
	 * Get PayPal Payment Link
	 * @param	$listing_id, $package_id
	 *
	 * @return  url $payment_link
	 */
	function wre_get_paypal_payment_link( $listing_id, $package_id='' ) {
		global $post;
		$current_user_id = get_current_user_id();
		$package_amount = wre_package_meta( 'price', $package_id );
		$subscription_period = wre_package_meta( 'subscription_period', $package_id );
		$subscription_unit = wre_package_meta( 'subscription_unit', $package_id );
		$allowed_listings = wre_package_meta( 'allowed_listings', $package_id );
		$package_name = get_the_title( $package_id );
		$packages_page = wre_option( 'wre_user_packages' );
		if( $post->ID == $packages_page ) {
			$redirect_page = $packages_page;
		} else {
			$redirect_page = wre_option( 'wre_my_listings' ) ? wre_option( 'wre_my_listings' ) : '';
		}
		$success_page_url = wre_get_account_endpoint_page_link('subscription');

		$redirect_url = get_permalink( $redirect_page );
		if( $subscription_period && $subscription_unit ) {
			$paypal_args = apply_filters( 'wre_paypal_args', array(
				'cmd'			=> '_xclick-subscriptions',
				'business'		=> wre_option( 'wre_paypal_merchant_id' ),
				'currency_code'	=> wre_option( 'wre_currency_code' ),
				'charset'		=> 'UTF-8',
				'p3'			=> $subscription_period,
				't3'			=> strtoupper(substr($subscription_unit, 0, 1)),
				'return'		=> add_query_arg( array(
					'success'	=> 'true',
					'user_id'	=> $current_user_id,
					'listing_id'=> $listing_id
				), $success_page_url ),

				'cancel_return'	=> add_query_arg( array(
					'cancel'	=> 'true',
					'user_id'	=> $current_user_id,
					'listing_id'=> $listing_id
				), $redirect_url ),

				'notify_url'	=> add_query_arg( array(
					'listing-manager-api'	=> 'WRE_Listings',
					'gateway'				=> 'paypal',
				), $success_page_url ),
				'custom'		=> $current_user_id,
				'item_name'		=> $package_name,
				'item_number'	=> $package_id,
				'a3'			=> $package_amount,
			) );
		} else {

			$paypal_args = apply_filters( 'wre_paypal_args', array(
				'cmd'			=> '_cart',
				'business'		=> wre_option( 'wre_paypal_merchant_id' ),
				'currency_code'	=> wre_option( 'wre_currency_code' ),
				'charset'		=> 'UTF-8',
				'rm'			=> 2,
				'upload'		=> 1,
				'no_note'		=> 1,
				'return'		=> add_query_arg( array(
					'success'		=> 'true',
					'user_id'	=> $current_user_id,
					'listing_id' => $listing_id
				), $success_page_url ),
				'cancel_return'	=> add_query_arg( array(
					'cancel'		=> 'true',
					'user_id'	=> $current_user_id,
					'listing_id' => $listing_id
				), $redirect_url ),
				'custom'		=> $current_user_id,
				'notify_url'	=> add_query_arg( array(
					'listing-manager-api'	=> 'WRE_Listings',
					'gateway' => 'paypal',
				), $success_page_url ),
				'no_shipping'	=> 1,
				'item_name_1'	=> $package_id,
				'quantity_1'	=> 1,
				'amount_1'		=> $package_amount,
			) );

		}

		$paypal_args = http_build_query( $paypal_args, '', '&' );
		$paypal_link = 'https://www.paypal.com/cgi-bin/webscr?';
		if (  wre_option( 'wre_paypal_enable_sandbox' ) == 'on' ) {
			$paypal_link = 'https://www.sandbox.paypal.com/cgi-bin/webscr?test_ipn=1&';
		}
		return $paypal_link . $paypal_args;
	}
}

if ( ! function_exists( 'wre_get_remaining_listings' ) ) {
	/**
	 * Get Remaining listings count of subscriber
	 *
	 * @return  int $author_listings
	 */
	function wre_get_remaining_listings( $user_id = '' ) {
		$author_listings = '';
		if( $user_id == '' ) $user_id = get_current_user_id();
		$maximum_listings_allowed = wre_get_membership_details( $user_id, 'allowed_listings' );

		if( $maximum_listings_allowed ) {
			if( $maximum_listings_allowed == -1 ) {
				$author_listings = 'unlimited';
			} else {
				$subscription_id = get_user_meta( $user_id, '_wre_subscription_id', true );
				if( $subscription_id ) {
					$author_listings = count(wre_get_subscription_premium_listings($subscription_id));
				}
				$author_listings = $maximum_listings_allowed - $author_listings;
			}
		}

		return $author_listings;
	}
}

if ( ! function_exists( 'wre_invalid_membership' ) ) {
	/**
	 * Check if memberhsip is valid
	 *
	 * @return  bool true/false
	 */
	function wre_invalid_membership() {
		if(! is_user_logged_in()) return true;
		if( wre_is_subscriber() ) {
			$user_id = get_current_user_id();
			$membership_details = get_user_meta( $user_id, '_wre_subscription_id', true );
			$remaining_listings = wre_get_remaining_listings();
			if( $remaining_listings === 'unlimited' ) $remaining_listings = 1;
			$is_expired = wre_get_membership_details( $user_id, 'expiry_date' );
			if( $is_expired !== '' && time() > $is_expired ) {
				$is_expired = false;
			}
			if( empty($membership_details) || $remaining_listings <= 0 || !$is_expired ) {
				return true;
			}
		}
		return false;
	}
}

if ( ! function_exists( 'wre_get_membership_details' ) ) {
	/**
	 * Get membership details
	 * @param	$user_id, $key
	 * @return  string/array	$membership_details/$membership_detailsp[$key]
	 */
	function wre_get_membership_details( $user_id = '', $key = '' ) {

		if( $user_id == '' ) $user_id = get_current_user_id();
		$user_subscription_id = get_user_meta( $user_id, '_wre_subscription_id', true );

		$membership_details = get_post_meta( $user_subscription_id, '_wre_subscription_details', true );
		if( $key == '' ) {
			return $membership_details;
		} else if( !empty( $membership_details ) && isset( $membership_details[$key] ) ) {
			return $membership_details[$key];
		}

		return false;
	}
}

if ( ! function_exists( 'wre_user_non_premium_listings' ) ) {
	/**
	 * Get non-premium listings
	 * @param	$user_id, $allowed_listings, $subscription_id
	 * @return  array	$listings
	 */
	function wre_user_non_premium_listings( $user_id = '', $allowed_listings = '', $subscription_id = '' ) {
		if( ! $user_id ) $user_id = get_current_user_id();
		if( ! $allowed_listings ) $allowed_listings = wre_get_membership_details( $user_id, 'allowed_listings' );
		$args = array(
			'post_type' => 'listing',
			'posts_per_page' => $allowed_listings,
			'post_status' => 'any',
			'fields' => 'ids',
			'author' => $user_id,
			'meta_query' => array(
				'relation'	=> 'AND',
				array(
					'relation'	=> 'OR',
					array(
						'key'     => '_wre_listing_premium',
						'value'   => '',
						'compare' => '=',
					),
					array(
						'key'     => '_wre_listing_premium',
						'value'   => '',
						'compare' => 'NOT EXISTS',
					)
				)
			),
		);
		if($subscription_id) {
			$subscirption_query = array(
					'key'     => '_wre_subscription_id',
					'value'   => $subscription_id,
					'compare' => '=',
				);
			$args['meta_query'][] = $subscirption_query;
		}
		$user_listings = get_posts( $args );
		return $user_listings;
	}
}

if ( ! function_exists( 'wre_get_premium_listings' ) ) {
	/**
	 * Get premium listings
	 * @param	$user_id, $allowed_listings
	 * @return  array	$user_listings
	 */
	function wre_get_premium_listings( $user_id = '', $allowed_listings = '' ) {
		if( ! $user_id ) $user_id = get_current_user_id();
		if( ! $allowed_listings ) $allowed_listings = wre_get_membership_details( $user_id, 'allowed_listings' );

		$user_listings = get_posts( array(
			'post_type' => 'listing',
			'posts_per_page' => $allowed_listings,
			'post_status' => 'any',
			'fields' => 'ids',
			'author' => $user_id,
			'meta_query' => array(
				array(
					'key'     => '_wre_listing_premium',
					'value'   => '',
					'compare' => '!=',
				)
			),
		) );
		return $user_listings;
	}
}
if ( ! function_exists( 'wre_package_rate' ) ) {
	/**
	 * Get membership formatted price
	 * @param	$package_id
	 * @return  string	$price
	 */
	function wre_package_rate($package_id) {
		$package_amount = wre_package_meta( 'price', $package_id );
		$subscription_period = wre_package_meta( 'subscription_period', $package_id );
		$subscription_unit = __( ucfirst( wre_package_meta( 'subscription_unit', $package_id ) ), 'wp-real-estate'  );
		if( $subscription_period == 0 ) {
			$subscription_period = ' '.__( 'Lifetime', 'wp-real-estate' );
		} else if( $subscription_period ) {
			if( $subscription_period == 1 ) {
				$subscription_period = '/'. substr( $subscription_unit, 0, -1 );
			} else {
				$subscription_period = '/'. $subscription_period.' '. $subscription_unit;
			}
		} else {
			$subscription_period = '-';
		}

		if( $package_amount <= 0 ) {
			$package_amount_text = __( 'No fees', 'wp-real-estate' );
			$subscription_period = '';
		} else {
			$package_amount_text = wre_currency_symbol() .$package_amount;
		}
		$package_price = esc_html( $package_amount_text ) . '<span>' . esc_html( $subscription_period ) . '</span>';
		return $package_price;
	}
}

if ( ! function_exists( 'wre_is_subscriber' ) ) {
	/**
	 * Check if logged in user is subscriber or agent
	 *
	 * @return	bool	true/false
	 */
	function wre_is_subscriber() {
		if( current_user_can( 'subscriber' ) || current_user_can( 'wre_agent' ) ) return true;
		return false;
	}
}
