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

class WRE_Submit_Listings {

	/**
	 * Metabox prefix
	 * @var string
	 */
	public $prefix = '_wre_listing_';

	public function __construct() {
		$this->submit_listing_type = 'memberships';
		$this->current_user_id     = get_current_user_id();
		add_filter( 'wp', array( $this, 'has_shortcode' ) );
		add_shortcode( 'wre_submit_listing', array( $this, 'wre_submit_listing_form' ) );

		add_action( 'cmb2_init', array( $this, 'wre_submit_listing_fields' ) );
		add_action( 'wp_ajax_wre_add_listings', array( $this, 'wre_add_listings_callback' ) );
		add_action( 'wp_ajax_nopriv_wre_add_listings', array( $this, 'wre_add_listings_callback' ) );

		add_action( 'wp_ajax_wre_subscription_details', array( $this, 'wre_subscription_details_callback' ) );
		add_action( 'wp_ajax_nopriv_wre_subscription_details', array( $this, 'wre_subscription_details_callback' ) );
	}

	/**
	 * Check if we have the shortcode displayed
	 */
	public function has_shortcode() {
		global $post;
		if ( is_a( $post, 'WP_Post' ) && ( has_shortcode( $post->post_content, 'wre_submit_listing' ) ) ) {
			add_filter( 'is_wre', array( $this, 'is_wre' ) );
		}
	}

	/**
	 * Add this as a wre page
	 *
	 * @param bool $return
	 * @return bool
	 */
	public function is_wre( $return ) {
		return true;
	}

	/**
	 * Get metabox fields
	 *
	 */
	public function wre_submit_listing_fields() {
		$listing_metaboxes = new WRE_Metaboxes();
		$listing_metaboxes->get_instance();
	}

	public function wre_validate_form( $listing_data, $images_data ) {
		$error_messages = array();
		$message        = '';
		if ( empty( $listing_data['_wpnonce'] ) || ! wp_verify_nonce( $listing_data['_wpnonce'], 'wre-submit_listing' ) ) {
			$error_messages[] = __( 'We were unable to process your request, please try again.', 'wp-real-estate' );
		}
		if ( isset( $listing_data['email'] ) && '' === $listing_data['email'] ) {
			$error_messages[] = __( 'User Email is a required field.', 'wp-real-estate' );
		}
		if ( ! isset( $listing_data['title'] ) || '' === $listing_data['title'] ) {
			$error_messages[] = __( 'Listing title is a required field.', 'wp-real-estate' );
		}
		if ( empty( $images_data ) && ! isset( $listing_data['wre_gallery_images'] ) ) {
			$error_messages[] = __( 'Listing image is a required field.', 'wp-real-estate' );
		}
		if ( ! empty( $error_messages ) ) {
			foreach ( $error_messages as $error_message ) {
				$message .= $this->wre_get_error_message( $error_message );
			}
		}
		return $message;
	}

	public function wre_get_error_message( $message ) {
		return '<span>' . $message . '</span>';
	}

	public function wre_upload_gallery_images( $listing_id = '', $files = array() ) {
		$file_obj = array();
		for ( $i = 0; $i < count( $files['name'] ); $i++ ) {
			$file_obj[] = array(
				'name'     => $files['name'][ $i ],
				'type'     => $files['type'][ $i ],
				'tmp_name' => $files['tmp_name'][ $i ],
				'error'    => $files['error'][ $i ],
				'size'     => $files['size'][ $i ],
			);
		}

		require_once( ABSPATH . 'wp-admin/includes/admin.php' );
		require_once( ABSPATH . 'wp-admin/includes/image.php' );

		$image_gallery = array();
		foreach ( $file_obj as $file_data ) {

			if ( wre_check_image_file( $file_data['name'] ) ) {

				$file_return = wp_handle_upload( $file_data, array( 'test_form' => false ) );
				if ( ! isset( $file_return['error'] ) && ! isset( $file_return['upload_error_handler'] ) ) {

					$filename   = $file_return['file'];
					$attachment = array(
						'post_mime_type' => $file_return['type'],
						'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
						'post_content'   => '',
						'post_status'    => 'inherit',
						'guid'           => $file_return['url'],
					);

					$attachment_id   = wp_insert_attachment( $attachment, $file_return['url'], $listing_id );
					$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
					wp_update_attachment_metadata( $attachment_id, $attachment_data );

					if ( 0 < intval( $attachment_id ) ) {
						$image_gallery[ $attachment_id ] = wp_get_attachment_image_src( $attachment_id, 'medium' )[0];
					}
				}
			}
		}
		return $image_gallery;
	}

	/**
	 * Add Listing
	 *
	 * @return string
	 */
	public function wre_add_listings_callback() {
		global $current_user;
		$flag         = false;
		$message      = '';
		$redirect_url = get_permalink( wre_option( 'wre_my_listings' ) );
		$listing_id   = '';
		parse_str( $_POST['formData'], $listing_data );

		$content = ! empty( $listing_data['listing_description'] ) ? $listing_data['listing_description'] : '';
		if ( isset( $listing_data['listing_description'] ) && ! empty( $listing_data['listing_description'] ) ) {
			$listing_data['content'] = $content;
			unset( $listing_data['listing_description'] );
		}
		$validate_form = $this->wre_validate_form( $listing_data, $_FILES );
		if ( '' !== $validate_form ) {
			$message .= $validate_form;
		} else {
			$listing_author = $current_user->ID;

			if ( ! $listing_author ) {
				$user_email     = $listing_data['email'];
				$listing_author = wre_create_user( $user_email );
				if ( ! $listing_author['flag'] ) {
					$message       .= $this->wre_get_error_message( $listing_author['message'] );
					$listing_author = '';
				} else {
					$listing_author = $current_user->ID;
				}
			}

			if ( $listing_author ) {

				$prefix      = $this->prefix;
				$meta_fields = array(
					$prefix . 'tagline',
					'content',
					$prefix . 'price',
					$prefix . 'price_suffix',
					$prefix . 'status',
					$prefix . 'purpose',
					$prefix . 'bedrooms',
					$prefix . 'bathrooms',
					$prefix . 'car_spaces',
					$prefix . 'building_size',
					$prefix . 'building_unit',
					$prefix . 'land_size',
					$prefix . 'land_unit',
					$prefix . 'displayed_address',
					$prefix . 'city',
					$prefix . 'state',
					$prefix . 'country',
					$prefix . 'lat',
					$prefix . 'lng',
					$prefix . 'image_gallery',
					$prefix . 'internal_features',
					$prefix . 'external_features',
					$prefix . 'neighborhood',
					$prefix . 'open',
					$prefix . 'hide',
					'consent_label',
				);

				$meta_fields = apply_filters( 'wre_new_listing_fields', $meta_fields );

				// Set Listing Status
				if ( isset( $listing_data['wre-listing-status'] ) && 'draft' === $listing_data['wre-listing-status'] ) {
					$post_status = $listing_data['wre-listing-status'];
				} else {
					$post_status = $this->wre_set_post_status();
				}

				//Update Existing Listing
				if ( 'wre-listings-fields' !== $listing_data['object_id'] ) {

					$listing_id = $listing_data['object_id'];
					if ( 'publish' === $listing_data['wre-listing-status'] && 'publish' === get_post_status( $listing_id ) ) {
						$post_status = 'publish';
					}

					$listing_id = wp_update_post(
						array(
							'ID'          => $listing_id,
							'post_title'  => $listing_data['title'],
							'post_type'   => 'listing',
							'post_status' => $post_status,
							'post_content' => $content,
						)
					);
				} else {
					//Insert New Listing
					$listing_id = wp_insert_post(
						array(
							'post_title'  => $listing_data['title'],
							'post_type'   => 'listing',
							'post_status' => $post_status,
							'post_author' => $listing_author,
							'post_content' => $content,
						)
					);
					WRE_SPL_Gateway::wre_email_notification( 'new_listing', array( 'listing_id' => $listing_id ) );
				}

				if ( is_wp_error( $listing_id ) ) {

					$error_string = $listing_id->get_error_message();
					add_settings_error( 'wre_idx_listing_settings_group', 'insert_post_failed', 'WordPress failed to insert the post. Error ' . $error_string, 'error' );
					$message .= $this->wre_get_error_message( __( 'Something went wrong. Please try again later.', 'wp-real-estate' ) );

				} elseif ( $listing_id ) {

					update_post_meta( $listing_id, '_wre_listing_agent', $listing_author );

					foreach ( $listing_data as $key => $data ) {
						if ( in_array( $key, $meta_fields ) ) {
							if ( '_wre_listing_open' === $key ) {
								$new_data = array();
								foreach ( $data as $d ) {
									if ( ! empty( array_filter( $d ) ) ) {
										array_push( $new_data, $d );
									}
								}
								if ( ! empty( $new_data ) ) {
									$data = $new_data;
								} else {
									$data = '';
								}
							}
							update_post_meta( $listing_id, $key, $data );
						}
					}

					// Add Image Gallery
					$files        = array_filter( $_FILES['files'] );
					$gallery_data = $this->wre_upload_gallery_images( $listing_id, $files );
					if ( isset( $listing_data['wre_gallery_images'] ) ) {
						foreach ( $listing_data['wre_gallery_images'] as $image ) {
							$gallery_data[ $image ] = wp_get_attachment_image_src( $image, 'medium' )[0];
						}
					}
					update_post_meta( $listing_id, '_wre_listing_image_gallery', $gallery_data );

					// Set Listing Type
					if ( $listing_data['_wre_listing_type'] ) {
						wp_set_object_terms( $listing_id, $listing_data['_wre_listing_type'], 'listing-type', true );
					}

					//Set Membership
					if ( isset( $listing_data['membership'] ) && wre_is_subscriber() ) {
						$membership_package_id = $listing_data['membership'];
						$package_amount        = wre_package_meta( 'price', $membership_package_id );

						// Subscribe to package
						if ( 0 === $package_amount ) {
							$membership_details = array(
								'package_id' => $membership_package_id,
								'listing_id' => $listing_id,
							);
							WRE_SPL_Gateway::wre_update_membership_details( $membership_details );
						} elseif ( isset( $listing_data['wre_payment_method'] ) && '' !== $listing_data['wre_payment_method'] && 0 < $package_amount ) {
							if ( 'paypal' === $listing_data['wre_payment_method'] ) {
								$redirect_url = wre_get_paypal_payment_link( $listing_id, $membership_package_id );
							} elseif ( 'stripe' === $listing_data['wre_payment_method'] ) {
								$subscription_data = WRE_SPL_Stripe::wre_subscribe_stripe_package( $listing_data['stripe_token'], $membership_package_id, $listing_id );
								if ( '' !== $subscription_data['message'] ) {
									$message .= $this->wre_get_error_message( $subscription_data['message'] );
								}
							} elseif ( 'bacs' === $listing_data['wre_payment_method'] ) {
								$membership_details = array(
									'package_id'     => $membership_package_id,
									'listing_id'     => $listing_id,
									'payment_type'   => 'bacs',
									'payment_date'   => current_time( 'mysql' ),
									'payment_status' => 'pending',
								);
								WRE_SPL_Gateway::wre_update_membership_details( $membership_details );
							}
						}
						if ( 'paypal' !== $listing_data['wre_payment_method'] ) {
							$redirect_url = wre_get_account_endpoint_page_link( 'subscription' );
						}
					} else {
						$allowed_listings = wre_get_remaining_listings();
						$payment_status   = wre_get_membership_details( $listing_author, 'payment_status' );
						$is_expired       = wre_get_membership_details( $listing_author, 'expiry_date' );
						$subscription_id  = get_user_meta( $listing_author, '_wre_subscription_id', true );
						if ( 'completed' === $payment_status && ( 0 < $allowed_listings || 'unlimited' === $allowed_listings ) && ( '' === $is_expired || time() < $is_expired ) ) {
							WRE_SPL_Gateway::payment_complete( $listing_id, '', $subscription_id );
						} else {
							update_post_meta( $listing_id, '_wre_subscription_id', $subscription_id );
						}
					}
				}
			}
		}
		if ( '' === $message ) {
			$flag = true;
		}
		echo wp_send_json( array(
			'flag'         => $flag,
			'message'      => $message,
			'redirect_url' => $redirect_url,
			'listing_id'   => $listing_id,
		) );
		die();
	}

	public function wre_subscription_details_callback() {

		ob_start();
		$package_id       = $_POST['package_id'];
		$allowed_listings = wre_package_meta( 'allowed_listings', $package_id );
		$package_price    = wre_package_rate( $package_id );
		if ( -1 === $allowed_listings ) {
			$allowed_listings = __( 'Unlimited', 'wp-real-estate' );
		}
		?>
		<table>
			<thead>
				<tr>
					<th><?php _e( 'Package', 'wp-real-estate' ); ?></th>
					<th><?php echo get_the_title( $package_id ); ?></th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td><?php _e( 'Listings', 'wp-real-estate' ); ?></td>
					<td>
						<span><?php echo esc_html( $allowed_listings ); ?></span>
					</td>
				</tr>
				<tr>
					<td>
						<?php _e( 'Price', 'wp-real-estate' ); ?>
					</td>
					<td><span><?php echo esc_html( $package_price ); ?></span></td>
				</tr>
			</tbody>
		</table>
		<?php
		echo ob_get_clean();
		exit;
	}

	/**
	 * Get Post Status
	 *
	 * @return string
	 */
	public function wre_set_post_status() {

		if ( ! wre_is_subscriber() ) {
			return 'publish';
		}

		if ( 'on' === wre_option( 'wre_auto_publish_listings' ) ) {
			$allowed_listings = wre_get_remaining_listings();
			if ( 'unlimited' === $allowed_listings ) {
				$allowed_listings = 1;
			}
			$is_expired     = wre_get_membership_details( $this->current_user_id, 'expiry_date' );
			$payment_status = wre_get_membership_details( $this->current_user_id, 'payment_status' );
			if ( 0 < $allowed_listings && ( '' === $is_expired || time() < $is_expired ) && 'completed' === $payment_status ) {
				return 'publish';
			}
		}

		return 'draft';
	}

	public function wre_submit_listing_form( $atts ) {
		ob_start();
		do_action( 'wre_submit_listing_form' );
		do_action( 'wre_enqueue_stripe_scripts' );
		if ( wre_map_key() ) {
			wp_enqueue_script( 'wre-geocomplete-map' );
		}
		do_action( 'wre_enqueue_plugin_scripts' );

		return ob_get_clean();
	}

}
return new WRE_Submit_Listings();
