<?php
/**
 * Class For WRE Pro Import Export page
 */
class WRE_Import_Export {

	public static function admin_print_styles() {

		?>
			<style>
				ul.tabs { width: 100%; display: table; border-collapse: separate; }
				ul.tabs li { font-weight: bold; text-align: center; margin: 0; cursor: pointer; display: table-cell; line-height: 14px; border: 1px solid #eee; background-color: #eee; }
				ul.tabs li.active { background-color: #fff; }
				ul.tabs li a { padding: 10px 5px; display: block; text-decoration: none; font-weight: bold; }
				ul.tabs li a:focus{ box-shadow: none; }
				table.export_wre { border-collapse: collapse; border-color: #eee; }
				table.export_wre tr td { border-bottom: 1px solid #eee; padding: 10px; color: #666; font-size: 14px; }
				.wre_ie_inner_container { width: 31.70%; display: inline-block; }
				form .wre_ie_inner_container { margin-right: 2%; }
				form .wre_ie_inner_container:nth-child(3) { margin-right: 0; }
				.tab-content>.tab-pane { display: none; }
				.tab-content>.active { display: block; }
				.wre_numbers a{ text-decoration: none; padding: 2px; margin: 0 4px; }
				.wre_numbers a.selected{ color: #666; }
				.wre_pag_div{ margin: 5px; }
				#export .tablenav-pages-navspan{ height: 14px; }
				#export .tablenav-pages .current-page{ height: 26px; padding-bottom: 2px; }
				.tablenav .tablenav-pages a{ height: 14px; }
				.paging-input{ margin: 0 5px; }
				.demo-container { width: 32%; display: inline-block; margin-right: 1.3%; background: #FAFBFD; border-radius: 3px; margin-bottom: 20px; padding: 0; }
				.demo-container:nth-child(3n+3) { margin-right: 0; }
                body.rtl .demo-container { margin-right: 0px; margin-left: 1.3%; }
                body.rtl .demo-container:nth-child(3n+3) { margin-left: 0; }
				.demo-container a{ text-decoration: none; }
				.demo-thumb img{ width: 100%; }
				#import hr { margin: 30px 0; }
				.demo-thumb label > input{ display:none; }
				.demo-thumb label img{ cursor:pointer; border:2px solid transparent; }
				.demo-thumb label > input:checked + img { border:2px solid #2196f3; }
			</style>
		<?php

	}

	public static function display_messages() {
		$message = false;
		if ( isset( $_REQUEST['message'] ) && ( $msg = (int) $_REQUEST['message'] ) ) {
			if ( 3 === $msg ) {
				$message = esc_html__( 'Data imported successfully', 'wp-real-estate' );
			} else if ( 4 === $msg ) {
				$message = esc_html__( 'Failed to import Data', 'wp-real-estate' );
			} else if ( 5 === $msg ) {
				$message = esc_html__( 'Data exported successfully', 'wp-real-estate' );
			} else if ( 6 === $msg ) {
				$message = esc_html__( 'Settings exported successfully', 'wp-real-estate' );
			} else if ( 7 === $msg ) {
				$message = esc_html__( 'Settings imported successfully', 'wp-real-estate' );
			}
		}
		$class = isset( $_REQUEST['error'] ) ? 'error' : 'updated';

		if ( $message ) :
		?>
			<div id="message" class="<?php echo $class; ?> notice is-dismissible"><p><?php echo $message; ?></p></div>
		<?php
		endif;
	}

	public static function load() {
		if ( isset( $_POST['action'] ) ) {

			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}
			$location = admin_url() . 'edit.php?post_type=listing&page=wre_import_export';
			switch ( $_POST['action'] ) {
				case 'import':
					if( isset( $_POST['submit-settings'] ) ) {
						$status = self::import_wre_settings();
						$location = add_query_arg( 'message', 7, $location );
					} else {
						$status = self::import_wre_demo();
						$location = add_query_arg( 'message', 3, $location );
					}
					if ( ! $status ) {
						$location = add_query_arg( array( 'error' => true, 'message' => 4 ), $location );
					}
					wp_redirect( $location );
				exit;

				case 'export':
					if ( isset( $_POST['export_settings'] ) ) {
						self::export_wre_settings();
						$location = add_query_arg( 'message', 6, $location );
					} else if ( isset( $_POST['export_wre'] ) && (isset( $_POST['wre_listings'] ))  || isset( $_POST['wre_agencies'] ) || isset( $_POST['wre_packages'] ) ) {
						self::export_wre_data();
						$location = add_query_arg( 'message', 5, $location );
					}
					wp_redirect( $location );
				exit;
			} // end switch
		}

		// Needed javascripts to allow drag/drop, expand/collapse and hide/show of boxes
		wp_enqueue_script( 'common' );
		wp_enqueue_script( 'wp-lists' );
		wp_enqueue_script( 'postbox' );
		$screen = get_current_screen();
		add_meta_box( 'import-export-content', esc_html__( 'Import and Export Data', 'wp-real-estate' ), array( __CLASS__, 'import_export_content' ), $screen->id, 'normal', 'core' );
	}

	public static function page() {
		$screen = get_current_screen();
		?>
			<div class="wrap" id="config-page">
				<h2><?php esc_html_e( 'Import/Export', 'wp-real-estate' ); ?></h2>
				<?php self::display_messages(); ?>
				<?php wp_nonce_field( 'wre_ie_page' ); ?>
				<?php wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false ); ?>
				<?php wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false ); ?>
				<input type="hidden" name="page" value="wre_config" />
				<div id="poststuff">
					<div id="post-body" class="metabox-holder">
						<div id="postbox-container-2" class="postbox-container">
							<?php do_meta_boxes( $screen->id, 'normal', '' ); ?>
						</div>
					</div>
				</div>
			</div>
			<script type="text/javascript">
				//<![CDATA[
					jQuery(document).ready( function($) {
						// close postboxes that should be closed
						$('.if-js-closed').removeClass('if-js-closed').addClass('closed');
						// postboxes setup
						postboxes.add_postbox_toggles('<?php echo $screen->id ?>');

						$('#tabs li a').on('click', function(e){
							e.preventDefault();
							var active_div = $(this).parents('ul').find('.active').removeClass('active').find('a').attr('href');
							$('body').find(active_div).removeClass('active');
							$(this).parent().addClass('active');
							$('body').find($(this).attr('href')).addClass('active');
							return false;
						});

						$(".selectall").change(function() {
							$(this).parents('.wre_ie_inner_container').find('input').prop('checked', $(this).prop("checked"));
						});
					});
				//]]>
			</script>
		<?php
	}

	public static function import_export_content() {
		?>
			
			<div>
				<ul id="tabs" class="tabs" data-tabs="tabs">
					<li class="active"><a href="#import" data-toggle="tab"><?php esc_html_e( 'Import', 'wp-real-estate' ); ?></a></li>
					<li><a href="#export" data-toggle="tab"><?php esc_html_e( 'Export', 'wp-real-estate' ); ?></a></li>
				</ul>
				<div class='tab-content'>
					<div class="tab-pane" id="export">
						<?php
							global $wpdb;
							$wre_listings = $wpdb->get_results( "SELECT `ID`,`post_title` FROM $wpdb->posts WHERE post_type='listing'" );
							$wre_agencies = $wpdb->get_results( "SELECT `ID`,`post_title` FROM $wpdb->posts WHERE post_type='agency'" );
							$wre_packages = $wpdb->get_results( "SELECT `ID`,`post_title` FROM $wpdb->posts WHERE post_type='memberships'" );
						?>
						
						<?php if( !empty( $wre_listings ) || !empty( $wre_agencies ) || ! empty( $wre_packages ) ) : ?>
							<form action="<?php echo admin_url( 'edit.php?post_type=listing&page=wre_import_export' ); ?>" method="post">

								<div class="wre_ie_inner_container">
									<?php  if ( ! empty( $wre_listings ) ) : ?>
										<h3><?php esc_html_e( 'Select Listings to Export', 'wp-real-estate' ); ?></h3>
										<table class="export_wre" width="100%" frame="border">
											<tr>
												<td style="width:5%;"><input id="wre-selectall" class="selectall" type="checkbox" /></td>
												<td>
													<label for="wre-selectall">
														<strong><?php esc_html_e( 'Select All', 'wp-real-estate' ); ?></strong>
													</label>
												</td>
											</tr>
											<?php foreach ( $wre_listings as $wre_listing ) : ?>
												<tr>
													<td><input class="wreId" type="checkbox" id="<?php echo $wre_listing->ID; ?>" value="<?php echo $wre_listing->ID; ?>" name="wre_listings[]" /></td>
													<td><label for="<?php echo $wre_listing->ID; ?>"><?php echo $wre_listing->post_title; ?></label></td>
												</tr>
											<?php endforeach; ?>
										</table>
									<?php else : ?>
										<div><?php esc_html_e( 'No Listings to Export', 'wp-real-estate' ); ?></div>
									<?php  endif; ?>
								</div>

								<div class="wre_ie_inner_container">
									<?php  if ( ! empty( $wre_agencies ) ) : ?>
										<h3><?php esc_html_e( 'Select Agencies to Export', 'wp-real-estate' ); ?></h3>
										<table class="export_wre" width="100%" frame="border">
											<tr>
												<td style="width:5%;"><input id="wre-selectall-agencies" class="selectall" type="checkbox" /></td>
												<td>
													<label for="wre-selectall-agencies">
														<strong><?php esc_html_e( 'Select All', 'wp-real-estate' ); ?></strong>
													</label>
												</td>
											</tr>
											<?php foreach ( $wre_agencies as $wre_agency ) : ?>
												<tr>
													<td><input class="wreagencyId" type="checkbox" id="<?php echo $wre_agency->ID; ?>" value="<?php echo $wre_agency->ID; ?>" name="wre_agencies[]" /></td>
													<td>
														<label for="<?php echo $wre_agency->ID; ?>"><?php echo $wre_agency->post_title; ?></label>
													</td>
												</tr>
											<?php endforeach; ?>
										</table>
									<?php else : ?>
										<div><?php esc_html_e( 'No Agencies to Export', 'wp-real-estate' ); ?></div>
									<?php  endif; ?>
								</div>
								
								<div class="wre_ie_inner_container">
									<?php  if ( ! empty( $wre_packages ) ) : ?>
										<h3><?php esc_html_e( 'Select Membership Packages to Export', 'wp-real-estate' ); ?></h3>
										<table class="export_wre" width="100%" frame="border">
											<tr>
												<td style="width:5%;"><input id="wre-selectall-packages" class="selectall" type="checkbox" /></td>
												<td>
													<label for="wre-selectall-packages">
														<strong><?php esc_html_e( 'Select All', 'wp-real-estate' ); ?></strong>
													</label>
												</td>
											</tr>
											<?php foreach ( $wre_packages as $wre_package ) : ?>
												<tr>
													<td><input class="wreId" type="checkbox" id="<?php echo $wre_package->ID; ?>" value="<?php echo $wre_package->ID; ?>" name="wre_packages[]" /></td>
													<td><label for="<?php echo $wre_package->ID; ?>"><?php echo $wre_package->post_title; ?></label></td>
												</tr>
											<?php endforeach; ?>
										</table>
									<?php else : ?>
										<div><?php esc_html_e( 'No Packages to Export', 'wp-real-estate' ); ?></div>
									<?php  endif; ?>
								</div>

								<p>
									<input type="hidden" name="action" value="export" />
									<input type="submit" name="export_wre" id="submit" class="button-primary" value="<?php _e( 'Export Data', 'wp-real-estate' ); ?>">&nbsp;
									<input type="submit" name="export_settings" id="submit" class="button-primary" value="<?php _e( 'Export Settings', 'wp-real-estate' ) ?>">&nbsp;
								</p>
							</form>
						<?php else : ?>
							<div><?php esc_html_e( 'No Data to Export', 'wp-real-estate' ); ?></div>
						<?php  endif; ?>

					</div>
					<div class="tab-pane active" id="import">
						<p><strong><?php esc_html_e( 'Import Demo', 'wp-real-estate' ); ?></strong></p>
						<form action="<?php echo admin_url( 'edit.php?post_type=listing&page=wre_import_export' ); ?>" method="post">
							<div>
								<div class="demo-container">
									<div class="demo-thumb">
										<label>
											<a href="http://demo.mythemeshop.com/wp-real-estate-pro/" target="_blank">
												<img src="<?php echo WRE_PLUGIN_URL. '/assets/images/wp-real-estate.png'; ?>" />
											</a>
										</label>
									</div>
								</div>
							</div>
							<p>
								<input type="hidden" name="demo" value="true" />
								<input type="hidden" name="action" value="import" />
								<input type="submit" name="submit" id="submit" class="button-primary" value="Import Demo">&nbsp;
							</p>
						</form>
						<hr/>
						<p><strong><?php esc_html_e( 'Import Data from file', 'wp-real-estate' ); ?></strong></p>
						<form action="<?php echo admin_url( 'edit.php?post_type=listing&page=wre_import_export' ); ?>" method="post" enctype="multipart/form-data">
							<p><input type="file" name="wre_import_file" /></p>
							<p>
								<input type="hidden" name="action" value="import" />
								<input type="submit" name="submit" id="submit" class="button-primary" value="<?php _e( 'Import Data', 'wp-real-estate' ); ?>">&nbsp;
							</p>
						</form>
						<hr/>
						<p><strong><?php esc_html_e( 'Import Settings from file', 'wp-real-estate' ); ?></strong></p>
						<form action="<?php echo admin_url( 'edit.php?post_type=listing&page=wre_import_export' ); ?>" method="post" enctype="multipart/form-data">
							<p><input type="file" name="wre_import_settings" /></p>
							<p>
								<input type="hidden" name="action" value="import" />
								<input type="submit" name="submit-settings" id="submit" class="button-primary" value="<?php _e( 'Import Settings', 'wp-real-estate' ); ?>">&nbsp;
							</p>
						</form>
					</div>
				</div>
			</div>
		<?php
	}

	public static function export_wre_settings() {
		$options = get_option('wre_options');
		//Send export
		header( 'Pragma: public' );
		header( 'Expires: 0' );
		header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
		header( 'Content-type: application/json' );
		header( 'Content-Disposition: attachment; filename=wre_settings_' . rand( 0, 1000 ) . '.json;' );
		header( 'Content-Transfer-Encoding: binary' );
		echo json_encode( $options );
		die;
	}

	public static function export_wre_data() {

		$export_data = $agency_data = $listing_data = $packages_data = array();

		if( isset( $_POST['wre_listings'] ) && $_POST['wre_listings'] != '' ) {
			$listings = $_POST['wre_listings'];		
			if( !empty( $listings ) ) {
				$listing_meta_fields = array( 'tagline', 'content', 'price', 'price_suffix', 'status', 'purpose', 'bedrooms', 'bathrooms', 'car_spaces', 'building_size', 'building_unit', 'land_size', 'land_unit', 'agent', 'displayed_address', 'zip', 'city', 'state', 'country', 'lat', 'lng', 'image_gallery', 'open', 'internal_features', 'external_features', 'type', 'mls', 'neighborhood' );
				foreach( $listings as $listing ) {
					$listing_fields = array();
					foreach( $listing_meta_fields as $listing_meta_field ) {
						if( $listing_meta_field == 'type' ) {
							$listing_type = wp_get_post_terms($listing, 'listing-type', array("fields" => "slugs"));
							if (!empty($listing_type))
								$listing_fields[$listing_meta_field] = $listing_type[0];
						} else {
							$listing_fields[$listing_meta_field] = wre_meta( $listing_meta_field, $listing );
						}
					}
					$listing_data[] = array( 'title' => get_the_title( $listing ), 'fields' => $listing_fields );
				}
			}
		}
		if( isset( $_POST['wre_agencies'] ) && $_POST['wre_agencies'] != '' ) {
			$agencies = $_POST['wre_agencies'];
			if( !empty( $agencies ) ) {
				$agency_meta_fields = array( 'tagline', 'content', 'agents', 'displayed_address', 'city', 'zip', 'state', 'country', 'lat', 'lng', 'logo', 'logo_id', 'cover', 'cover_id', 'phone', 'fax', 'email', 'website' );
				foreach( $agencies as $agency ) {
					$agency_fields = array();
					foreach( $agency_meta_fields as $agency_meta_field ) {
						$agency_fields[$agency_meta_field] = wre_agency_meta( $agency_meta_field, $agency );
					}
					$agency_data[] = array( 'title' => get_the_title( $agency ), 'fields' => $agency_fields );
				}
			}
		}
		if( isset( $_POST['wre_packages'] ) && $_POST['wre_packages'] != '' ) {
			$packages = $_POST['wre_packages'];
			if( !empty( $packages ) ) {
				$package_meta_fields = array( 'subscription_period', 'subscription_unit', 'allowed_listings', 'price', 'stripe_id' );
				foreach( $packages as $package ) {
					$package_fields = array();
					$package_content = get_post($package);
					$package_content = $package_content->post_content;
					foreach( $package_meta_fields as $package_meta_field ) {
						$package_fields[$package_meta_field] = wre_package_meta( $package_meta_field, $package );
					}
					$packages_data[] = array( 'title' => get_the_title( $package ), 'content' =>  $package_content,'fields' => $package_fields );
				}
			}
		}

		array_push($export_data, array(
			'agency' => $agency_data,
			'listing' => $listing_data,
			'memberships' => $packages_data
		));
		// Send export
		header( 'Pragma: public' );
		header( 'Expires: 0' );
		header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
		header( 'Content-type: application/json' );
		header( 'Content-Disposition: attachment; filename=wre-' . rand( 0, 1000 ) . '.json;' );
		header( 'Content-Transfer-Encoding: binary' );
		echo json_encode( $export_data );
		die;
	}

	private static function insert_posts( $post_type, $title, $content='' ) {
		return $id = wp_insert_post(
				array(
					'post_title'	=>	$title,
					'post_content'	=> $content,
					'post_type'		=>	$post_type,
					'post_status'	=>	'publish'
				)
			);
	}

	private static function insert_meta_fields( $post_id, $meta_fields, $prefix ) {
		foreach( $meta_fields as $key => $value ) {
			if( !empty($value) ) {
				if( $key == 'type' ) {
					wp_set_object_terms( $post_id, $value, 'listing-type' );
				} else {
					if( $key == 'image_gallery' ) {

						$images = $value;
						$value = array();
						foreach( $images as $image ) {

							$attach_id = wre_download_image_file( $image, $post_id );
							$new_path = get_attached_file($attach_id);

							// Generate the metadata for the attachment, and update the database record.
							$attach_data = wp_generate_attachment_metadata( $attach_id, $new_path );
							wp_update_attachment_metadata( $attach_id, $attach_data );
							$value[$attach_id] = wp_get_attachment_image_src( $attach_id, 'medium' )[0];
						}

					} else if( $key == 'logo' || $key == 'cover' ) {
						$attach_id = wre_download_image_file( $value, $post_id );
						$new_path = get_attached_file($attach_id);

						// Generate the metadata for the attachment, and update the database record.
						$attach_data = wp_generate_attachment_metadata( $attach_id, $new_path );
						$value = wp_get_attachment_image_src( $attach_id, 'wre-lge' )[0];
						add_post_meta( $post_id, $prefix.$key.'_id', $attach_id );
					}
					if( $key == 'content' ) {
						$meta_key = $key;
					} else {
						$meta_key = $prefix.$key;
					}
					add_post_meta( $post_id, $meta_key, $value );
				}
			}

		}
	}

	private static function wre_post_exists( $title, $post_type ) {
		global $wpdb;
		$query = $wpdb->prepare(
			'SELECT ID FROM ' . $wpdb->posts . '
			WHERE post_title = %s
			AND post_type = %s',
			$title,
			$post_type
	   );
	   $wpdb->query( $query );
	   return $wpdb->num_rows;
	}
	
	public static function import_wre_settings() {

		// Get JSON File and It's contents
		if ( isset($_FILES['wre_import_settings']) && $_FILES['wre_import_settings']['error'] == '' ) {
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
			$imported_file         		= $_FILES['wre_import_settings'];
			$wq_upload_dir            	= wp_upload_dir();
			$wq_upload_dir['basedir']	= $wq_upload_dir['basedir'];
			$wq_upload_dir['baseurl']	= $wq_upload_dir['baseurl'];

			if ( ! move_uploaded_file( $imported_file['tmp_name'], $wq_upload_dir['basedir'] . '/' . $imported_file['name'] ) ) {
				return false;
			}

			// Get JSON File and It's contents
			$wre_import_data = file_get_contents( $wq_upload_dir['basedir'] . '/' . $imported_file['name'] );
			$wre_import_data = json_decode( $wre_import_data, true );
			unlink( $wq_upload_dir['basedir'] . '/' . $imported_file['name'] );
		}
		if( is_array( $wre_import_data ) && !empty($wre_import_data) ) {
			update_option('wre_options', $wre_import_data);
			return true;
		}
		return false;

	}

	public static function import_wre_demo() {

		// Get JSON File and It's contents
		if ( isset($_FILES['wre_import_file']) && $_FILES['wre_import_file']['error'] == '' ) {
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
			$imported_file         		= $_FILES['wre_import_file'];
			$wq_upload_dir            	= wp_upload_dir();
			$wq_upload_dir['basedir']	= $wq_upload_dir['basedir'];
			$wq_upload_dir['baseurl']	= $wq_upload_dir['baseurl'];

			if ( ! move_uploaded_file( $imported_file['tmp_name'], $wq_upload_dir['basedir'] . '/' . $imported_file['name'] ) ) {
				return false;
			}

			// Get JSON File and It's contents
			$wre_import_data = file_get_contents( $wq_upload_dir['basedir'] . '/' . $imported_file['name'] );
			$wre_import_data = json_decode( $wre_import_data, true );
			unlink( $wq_upload_dir['basedir'] . '/' . $imported_file['name'] );
		} else {
			$wre_import_data = file_get_contents( WRE_PLUGIN_DIR . '/includes/admin/demo/data.json' );
			$wre_import_data = json_decode( $wre_import_data, true );
		}
		if( is_array( $wre_import_data ) && !empty($wre_import_data) ) {
			foreach ( $wre_import_data as $wre_data ) {
				foreach( $wre_data as $post_type => $pt_data ) {
					$meta_prefix = '_wre_listing_';
					if( $post_type == 'agency' ) {
						$meta_prefix = '_wre_agency_';
					} else if ( $post_type == 'memberships' ) {
						$meta_prefix = '_wre_package_';
					}

					foreach( $pt_data as $data ) {
						$post_exists = self::wre_post_exists( $data['title'], $post_type );
						if( ! $post_exists ) {
							$content = '';
							if( isset( $data['content'] ) ) $content = $data['content'];
							$post_id = self::insert_posts( $post_type, $data['title'], $content );
							self::insert_meta_fields( $post_id, $data['fields'], $meta_prefix );
						}
					}
				}
			}
			return true;
		}
		return false;
	}
}