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

if (!class_exists('WRE_Admin_Metaboxes')) :

	/**
	 * CMB2 Theme Options
	 * @version 0.1.0
	 */
	class WRE_Admin_Metaboxes {

		/**
		 * Constructor
		 * @since 0.1.0
		 */
		public function __construct() {
			add_action('cmb2_admin_init', array($this, 'register_metaboxes'));
			add_filter('cmb2-taxonomy_meta_boxes', array($this, 'wre_listing_type_metaboxes'));
			add_action('add_meta_boxes', array($this, 'wre_payment_metaboxes'), 10, 2);
			add_action('wp_ajax_wre_manage_subscription', array($this, 'wre_manage_subscription_callback'));
			add_action( 'parse_query', array( $this, 'filter' ) );
		}

		function wre_manage_subscription_callback() {
			$subscription_id = (int) $_POST['subscription_id'];
			$subscription_details = get_post_meta( $subscription_id, '_wre_subscription_details', true );
			$payment_status = $subscription_details['payment_status'];

			if( $payment_status == 'pending' ) {
				$subscriber_id = get_post_meta( $subscription_id, '_wre_subscriber_id', true );
				$allowed_listings = $subscription_details['allowed_listings'];
				$listings = wre_user_non_premium_listings( $subscriber_id, $allowed_listings, $subscription_id );

				foreach( $listings as $listing ) {
					WRE_SPL_Gateway::payment_complete($listing, '', $subscription_id, $subscriber_id);
				}
				$subscription_details['payment_status'] = 'completed';
			} else {
				$listings = wre_get_subscription_listings($subscription_id);
				$reset_listings = wre_option('wre_after_expiration') ? wre_option('wre_after_expiration') : 'draft';
				foreach($listings as $listing) {
					if($reset_listings == 'draft') {
						wp_update_post( array( 'ID' => $listing, 'post_status' => 'draft' ) );
					} else {
						update_post_meta( $listing, '_wre_listing_premium', '' );
					}
				}
				$subscription_details['payment_status'] = 'cancelled';
			}
			update_post_meta( $subscription_id, '_wre_subscription_details', $subscription_details );
			update_post_meta( $subscription_id, '_wre_subscription_status', 'cancelled' );
			die();
		}

		function filter( $query ){
			global $pagenow;
			$type = get_post_type() ? get_post_type() : 'wre-subscription';
			if (isset($_GET['post_type'])) {
				$type = $_GET['post_type'];
			}
			if ( 'wre-subscription' == $type && is_admin() && $pagenow == 'edit.php') {
				if(isset($_GET['_subscriber'])) {
					$query->query_vars['meta_key'] = '_wre_subscriber_id';
					$query->query_vars['meta_value'] = $_GET['_subscriber'];
				} else if(isset($_GET['s']) && is_email($_GET['s'])) {

					$user_data = get_user_by('email', $_GET['s']);

					if(!empty($user_data)) {
						$user_id = $user_data->ID;
						$query->query_vars['meta_key'] = '_wre_subscriber_id';
						$query->query_vars['meta_value'] = $user_id;
						$query->query_vars['s'] = '';
					}
				}
			}
		}

		public function wre_payment_metaboxes( $post_type ) {
			if( $post_type == 'wre-subscription' ) {
				add_meta_box(
					'wre-subscription-listings-details',
					__( 'Listings', 'wp-real-estate' ),
					array($this, 'wre_render_subscription_listings_details'),
					'wre-subscription',
					'normal',
					'high'
				);
				add_meta_box(
					'wre-subscription-details',
					__( 'Subscription Details', 'wp-real-estate' ),
					array($this, 'wre_render_subscription_details'),
					'wre-subscription',
					'normal',
					'high'
				);
			}
		}

		public function wre_render_subscription_details() {
			global $post;
			$subscription_details = get_post_meta( $post->ID, '_wre_subscription_details', true );
			$subscriber_id = get_post_meta( $post->ID, '_wre_subscriber_id', true );
			$allowed_listings = $subscription_details['allowed_listings'];
			if( $allowed_listings == -1 ) {
				$allowed_listings = __('Unlimited', 'wp-real-estate');
			}
			$payment_status = $subscription_details['payment_status'];
			$subscriber = get_userdata( $subscriber_id );
			$payment_type = $subscription_details['payment_type'];
			if( $payment_type == 'bacs' ) {
				$payment_type = __('Direct bank transfer', 'wp-real-estate');
			}
			?>
			<div id="wre_subscription_details">

				<h2><?php printf( __( 'Subscription #%s details', 'wp-real-estate' ), $post->ID ); ?></h2>
				<p class="subscription_number">
					<?php printf( __( 'Payment via %s. Customer IP: %s', 'wp-real-estate' ), $payment_type, '<span class="wre-subscription-customerIP">'.  $subscription_details['subscriber_ip_address'] .'</span>' ); ?>
				</p>

				<div class="subscription_data_column_container">
					<div class="subscription_data_column">
						<h3><?php _e( 'General Details', 'wp-real-estate' ); ?></h3>
						<p class="wre-form-field">
							<label for="plan_name"><?php _e( 'Plan:', 'wp-real-estate' ); ?></label>
							<span><?php echo esc_html( $subscription_details['plan_name'] ); ?></span>
						</p>
						<p class="wre-form-field">
							<label for="subscription_date"><?php _e( 'Subscription date:', 'wp-real-estate' ); ?></label>
							<span><?php echo esc_html( date( 'd-M-Y', $subscription_details['payment_date'] ) ); ?></span>
						</p>
						<p class="wre-form-field">
							<label for="amount"><?php _e( 'Amount:', 'wp-real-estate' ); ?></label>
							<span><?php echo wre_currency_symbol(); ?><?php echo esc_html( $subscription_details['price'] ); ?></span>
						</p>
						<p class="wre-form-field">
							<label for="allowed_listings"><?php _e( 'Allowed Listings:', 'wp-real-estate' ); ?></label>
							<span><?php echo esc_html( $allowed_listings ); ?></span>
						</p>
						<p class="wre-form-field">
							<label for="expiry_date"><?php _e( 'Expiry Date:', 'wp-real-estate' ); ?></label>
							<span><?php echo esc_html( date( 'd-M-Y', $subscription_details['expiry_date'] ) ); ?></span>
						</p>
						<p class="wre-form-field">
							<label for="payment_status"><?php _e( 'Payment status: ', 'wp-real-estate' ); ?></label>
							<span><?php echo esc_html(ucfirst($payment_status)); ?></span>
						</p>
					</div>

					<div class="subscription_data_column">
						<?php if($subscriber) { ?>
							<h3><?php printf( __( 'Subscriber #%d Details', 'wp-real-estate' ), $subscriber_id ); ?></h3>

							<p class="wre-form-field">
								<label for="subscriber_name"><?php _e( 'Subscriber Name:', 'wp-real-estate' ); ?></label>
								<span><?php echo esc_html($subscriber->display_name); ?></span>
							</p>
							<p class="wre-form-field">
								<label for="subscriber_email"><?php _e( 'Subscriber Email:', 'wp-real-estate' ); ?></label>
								<span><?php echo esc_html($subscriber->user_email); ?></span>
							</p>
							<p class="wre-form-field">
								<label for="customer_user">
									<?php
									$args = array(
										'post_status'	=> 'all',
										'post_type'		=> 'wre-subscription',
										'_subscriber'	=> $subscriber_id,
									);
									printf( '<a href="%s">%s</a>',
										esc_url( add_query_arg( $args, admin_url( 'edit.php' ) ) ),
										__( 'View other subscriptions &rarr;', 'woocommerce' )
									);
									?>
								</label>
							</p>
						<?php } ?>
					</div>
				</div>
				<div id="wre-subscription-action">
					<?php
					if( $payment_status == 'pending' ) {
						$text = __( 'Activate', 'wp-real-estate' );
					} else {
						$text = __( 'Deactivate', 'wp-real-estate' );
					}
					if( $payment_status == 'pending' || $payment_status == 'completed' ) { ?>
						<a href="#" class="button-primary" data-subscription-id="<?php echo esc_attr($post->ID); ?>">
							<?php echo esc_html($text); ?>
						</a>
					<?php } else {
						$subscription_status = get_post_meta( $post->ID, '_wre_subscription_status', true );
					?>
						<span><?php echo esc_html($subscription_status); ?></span>
					<?php } ?>
				</div>
			</div>

			<?php
		}

		public function wre_render_subscription_listings_details() {
			global $post;
			$listings = wre_get_subscription_listings($post->ID);
			?>
			<div class="wre_subscription_items_wrapper wc-subscription-items-editable">
				<?php if( !empty($listings) ) { ?>
					<table cellpadding="0" cellspacing="0" class="wre_subscription_items">
						<thead>
							<tr>
								<th class="item sortable" colspan="2" data-sort="string-ins"><?php _e( 'Listing', 'wp-real-estate' ); ?></th>
								<th class="item_cost sortable" data-sort="float"><?php _e( 'Status', 'wp-real-estate' ); ?></th>
								<th class="quantity sortable" data-sort="int"><?php _e( 'Premium', 'wp-real-estate' ); ?></th>
							</tr>
						</thead>
						<tbody id="subscription_shipping_line_items">
							<?php foreach( $listings as $listing ) {
								$listing_image = wre_get_first_image($listing);
								$is_premium = !empty(wre_meta('premium', $listing)) ? __( 'Yes', 'wp-real-estate' ) : __( 'No', 'wp-real-estate' );
							?>
								<tr>
									<td class="thumb">
										<a href="<?php echo get_edit_post_link($listing); ?>">
											<img src="<?php echo esc_url($listing_image['sml']); ?>" />
										</a>
									</td>
									<td class="name">
										<a href="<?php echo get_edit_post_link($listing); ?>">
											<?php echo get_the_title($listing); ?>
										</a>
									</td>
									<td><?php echo get_post_status($listing); ?></td>
									<td><?php echo esc_html($is_premium); ?></td>
								</tr>
							<?php } ?>
						</tbody>
					</table>
				<?php } ?>
			</div>
			<?php
		}

		/**
		 * Add the options metabox to the array of metaboxes
		 * @since  0.1.0
		 */
		public function register_metaboxes() {

			/**
			 * Load the metaboxes for listing post type
			 */
			$listing_metaboxes = new WRE_Metaboxes();
			$listing_metaboxes->get_instance();
		}

		/**
		 * Define the metabox and field configurations.
		 *
		 * @param  array $meta_boxes
		 * @return array
		 */
		function wre_listing_type_metaboxes(array $meta_boxes) {

			// Start with an underscore to hide fields from custom fields list
			$prefix = '_wre_';

			/**
			 * Sample metabox to demonstrate each field type included
			 */
			$meta_boxes['marker_metabox'] = array(
				'id' => 'marker_image_metabox',
				'title' => __('Marker Image', 'wp-real-estate'),
				'object_types' => array('listing-type'), // Taxonomy
				'context' => 'normal',
				'priority' => 'high',
				'show_names' => true, // Show field names on the left
				// 'cmb_styles' => false, // false to disable the CMB stylesheet
				'fields' => array(
					array(
						'name' => __('Marker Image', 'wp-real-estate'),
						'desc' => __('Upload an image or enter a URL.', 'wp-real-estate'),
						'id' => $prefix . 'marker_image',
						'type' => 'file',
						'text' => array(
							'add_upload_files_text' => __('Add Image', 'wp-real-estate'),
						),
					),
				),
			);

			return $meta_boxes;
		}

	}

	new WRE_Admin_Metaboxes();

endif;
