<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;


/**
 * Handles the migration of the calendars from the old plugins to the new structure
 *
 */
function wpsbc_action_ajax_migrate_calendars() {

	if( empty( $_POST['token'] ) || ! wp_verify_nonce( $_POST['token'], 'wpsbc_upgrader' ) ) {
		echo json_encode( array( 'success' => 0 ) );
		wp_die();
	}

	$upgrade_from = wpsbc_process_upgrade_from();

	if( false == $upgrade_from ) {
		echo json_encode( array( 'success' => 0 ) );
		wp_die();
	}

	/**
	 * Verify for the existance of calendars
	 *
	 */
	$calendars = wpsbc_get_calendars();

	if( ! empty( $calendars ) ) {
		echo json_encode( array( 'success' => 0 ) );
		wp_die();
	}


	/**
	 * Handle upgrade from old premium version
	 *
	 */
	if( $upgrade_from == 'old_premium' ) {

		global $wpdb;

		$old_calendar_ids = $wpdb->get_results( "SELECT calendarID FROM {$wpdb->prefix}sbc_calendars", ARRAY_N );

		if( ! empty( $old_calendar_ids ) ) {

			// Because we do the upgrade in steps we need to preserve the old legend item
			// keys with the new one's ids
			$legend_items_relationships = array();

			foreach( $old_calendar_ids as $calendar_id ) {

				$calendar_id = $calendar_id[0];
				$calendar 	 = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}sbc_calendars WHERE calendarID = '{$calendar_id}'", ARRAY_A );

				if( is_null( $calendar ) )
					continue;

				/**
				 * Handle Calendar
				 *
				 */
				$calendar_data = array(
					'id'   			=> $calendar['calendarID'],
					'name' 			=> $calendar['calendarTitle'],
					'date_created'	=> date( 'Y-m-d H:i:s', $calendar['createdDate'] ),
					'date_modified'	=> date( 'Y-m-d H:i:s', $calendar['modifiedDate'] ),
					'status'		=> 'active',
					'ical_hash'		=> ( ! empty( $calendar['calendarHash'] ) ? $calendar['calendarHash'] : wpsbc_generate_ical_hash() )
				);

				$calendar_id = wpsbc_insert_calendar( $calendar_data );


				/**
				 * Handle Legend Items
				 *
				 */
				$old_legend_items = json_decode( $calendar['calendarLegend'], true );
				$old_legend_items = ( ! empty( $old_legend_items ) && is_array( $old_legend_items ) ? $old_legend_items : array() );

				// Legend items order
				$legend_items_order = array();

				// Legend items that should be synced as booked
				$legend_items_booked = array();

				foreach( $old_legend_items as $key => $old_legend_item ) {

					// Set color
					$color = array();

					// Add primary color
					if( ! empty( $old_legend_item['color'] ) )
						$color[] = $old_legend_item['color'];

					// Add secondary color
					if( ! empty( $old_legend_item['splitColor'] ) )
						$color[] = $old_legend_item['splitColor'];


					$legend_item_data = array(
						'name'  	  => $old_legend_item['name']['default'],
						'type'  	  => ( empty( $old_legend_item['splitColor'] ) ? 'single' : 'split' ),
						'color' 	  => $color,
						'is_default'  => ( $key == 'default' ? 1 : 0 ),
						'is_visible'  => ( empty( $old_legend_item['hide'] ) ? 1 : 0 ),
						'calendar_id' => $calendar_id
					);

					$legend_item_id = wpsbc_insert_legend_item( $legend_item_data );

					if( $legend_item_id ) {

						// Push to legend items order
						$legend_items_order[] = $legend_item_id;

						// Push to sync as booked
						if( ! empty( $old_legend_item['sync'] ) && $old_legend_item['sync'] == 'yes' )
							$legend_items_booked[] = $legend_item_id;
						
						$legend_items_relationships[$calendar_id][$key] = $legend_item_id;

					}

				}

				// Save the legend items relations ships into a transient
				set_transient( 'wpsbc_upgrader_legend_items_relationships', $legend_items_relationships, HOUR_IN_SECONDS );


				/**
				 * Handle Calendar Metadata
				 *
				 */
				$calendar_options = ( ! empty( $calendar['calendarOptions'] ) ? json_decode( $calendar['calendarOptions'], true ) : array() );
				$calendar_options = ( ! empty( $calendar_options ) && is_array( $calendar_options ) ? $calendar_options : array() );

				// Add legend items order
				wpsbc_update_calendar_meta( $calendar_id, 'legend_items_sort_order', $legend_items_order );

				// Add legend items order
				wpsbc_update_calendar_meta( $calendar_id, 'ical_export_legend_items', $legend_items_booked );

				// Add calendar link options
				if( ! empty( $calendar_options['calendarHyperlinks']['type'] ) )
					wpsbc_update_calendar_meta( $calendar_id, 'calendar_link_type', sanitize_text_field( $calendar_options['calendarHyperlinks']['type'] ) );

				if( ! empty( $calendar_options['calendarHyperlinks']['type'] ) && $calendar_options['calendarHyperlinks']['type'] == 'internal' && ! empty( $calendar_options['calendarHyperlinks']['link'] ) )
					wpsbc_update_calendar_meta( $calendar_id, 'calendar_link_internal', absint( $calendar_options['calendarHyperlinks']['link'] ) );

				if( ! empty( $calendar_options['calendarHyperlinks']['type'] ) && $calendar_options['calendarHyperlinks']['type'] == 'external' && ! empty( $calendar_options['calendarHyperlinks']['link'] ) )
					wpsbc_update_calendar_meta( $calendar_id, 'calendar_link_external', $calendar_options['calendarHyperlinks']['link'] );

				// Add user premissions
				$calendar_users = ( ! empty( $calendar['calendarUsers'] ) && is_array( json_decode( $calendar['calendarUsers'], true ) ) ? json_decode( $calendar['calendarUsers'], true ) : array() );

				foreach( $calendar_users as $user_id ) {

					wpsbc_add_calendar_meta( $calendar_id, 'user_permission', absint( $user_id ) );

				}

			}

		}

	}

	/**
	 * Handle upgrade from free version
	 *
	 */
	if( $upgrade_from == 'free' ) {

		// Get calendars options
		$calendars_options = get_option( 'wp-simple-booking-calendar-options' );

		// Get the first array key of the calendar
		foreach( $calendars_options['calendars'] as $key => $old_calendar_data ) {

			$calendar_id = $key;
			break;

		}

		/**
		 * Handle Calendar
		 *
		 */

		// Set the new calendar data.
		$calendar_data = array(
			'id'   			=> $calendar_id,
			'name' 			=> $calendars_options['calendars'][$calendar_id]['calendarName'],
			'date_created'	=> date( 'Y-m-d H:i:s', $calendars_options['calendars'][$calendar_id]['dateCreated'] ),
			'date_modified'	=> date( 'Y-m-d H:i:s', $calendars_options['calendars'][$calendar_id]['dateModified'] ),
			'status'		=> 'active',
			'ical_hash'		=> wpsbc_generate_ical_hash()
		);

		$calendar_id = wpsbc_insert_calendar( $calendar_data );

		/**
		 * Handle Legend Items
		 *
		 */
		$legend_items_data = wpsbc_get_default_legend_items_data();

		// Add the changeover legend item of the free version
		$legend_items_data[] = array(
			'name'  => __( 'Changeover', 'wp-simple-booking-calendar' ),
			'type'  => 'single',
			'color' => array( '#fee2a0' ),
			'is_visible' => 1
		);

		foreach( $legend_items_data as $legend_item_data ) {

			// Set the calendar id for the legend items data
			$legend_item_data['calendar_id'] = $calendar_id;

			// Insert legend item
			wpsbc_insert_legend_item( $legend_item_data );

		}

	}

	echo json_encode( array( 'success' => 1 ) );
	wp_die();

}
add_action( 'wp_ajax_wpsbc_action_ajax_migrate_calendars', 'wpsbc_action_ajax_migrate_calendars' );


/**
 * Handles the migration of the bookings from the old plugins to the new structure
 *
 */
function wpsbc_action_ajax_migrate_bookings() {

	if( empty( $_POST['token'] ) || ! wp_verify_nonce( $_POST['token'], 'wpsbc_upgrader' ) ) {
		echo json_encode( array( 'success' => 0 ) );
		wp_die();
	}

	$upgrade_from = wpsbc_process_upgrade_from();

	if( false == $upgrade_from ) {
		echo json_encode( array( 'success' => 0 ) );
		wp_die();
	}


	/**
	 * Handle upgrade from old premium version
	 *
	 */
	if( $upgrade_from == 'old_premium' ) {

		global $wpdb;

		// Get legend items relationships
		$legend_items_relationships = get_transient( 'wpsbc_upgrader_legend_items_relationships' );

		// Get old calendars
		$old_calendar_ids = $wpdb->get_results( "SELECT calendarID FROM {$wpdb->prefix}sbc_calendars", ARRAY_N );

		if( ! empty( $old_calendar_ids ) ) {

			foreach( $old_calendar_ids as $calendar_id ) {

				$calendar_id = $calendar_id[0];
				$calendar 	 = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}sbc_calendars WHERE calendarID = '{$calendar_id}'", ARRAY_A );

				if( is_null( $calendar ) )
					continue;

				// Check to see if the new calendar was created with the same id
				$new_calendar = wpsbc_get_calendar( $calendar_id );

				if( is_null( $new_calendar ) )
					continue;

				// Set calendar data
				$calendar_data = json_decode( $calendar['calendarData'], true );

				foreach( $calendar_data as $year => $months ) {

					foreach( $months as $month => $date_values ) {

						/**
						 * Handle the adding of the Events based on the legend item. It also adds the
						 * description for that particular date.
						 *
						 */
						foreach( $date_values as $key => $old_legend_item_id ) {

							if( false !== strpos( $key, 'description' ) )
								continue;

							$event_data = array(
								'calendar_id' 	 => $calendar_id,
								'date_year'   	 => $year,
								'date_month'  	 => $month,
								'date_day'	  	 => $key,
								'description' 	 => ( isset( $date_values['description-' . $key] ) ? _wpsbc_replace_custom( $date_values['description-' . $key] ) : '' ),
								'tooltip' 	  	 => ( isset( $date_values['description-' . $key] ) ? _wpsbc_replace_custom( $date_values['description-' . $key] ) : '' ),
								'legend_item_id' => ( ! empty( $legend_items_relationships[$calendar_id][$old_legend_item_id] ) ? $legend_items_relationships[$calendar_id][$old_legend_item_id] : 0 )
							);

							// Insert the event
							$event_id = wpsbc_insert_event( $event_data );

							// Unset the legend item value from the old data
							unset( $date_values[$key] );

							if( isset( $date_values['description-' . $key] ) )
								unset( $date_values['description-' . $key] );

						}


						/**
						 * Adds the events that only have the description available
						 * At this moment only events with description should remain in the array
						 *
						 */
						if( ! empty( $date_values ) ) {

							foreach( $date_values as $key => $old_legend_item_id ) {

								if( false === strpos( $key, 'description' ) )
									continue;

								$event_data = array(
									'calendar_id' 	 => $calendar_id,
									'date_year'   	 => $year,
									'date_month'  	 => $month,
									'date_day'	  	 => absint( str_replace( 'description-', '', $key ) ),
									'description' 	 => _wpsbc_replace_custom( $date_values[$key] ),
									'tooltip' 	  	 => _wpsbc_replace_custom( $date_values[$key] ),
									'legend_item_id' => 0
								);

								// Insert the event
								$event_id = wpsbc_insert_event( $event_data );

							}

						}

					}

				}

			}

		}

	}


	/**
	 * Handle upgrade from free version
	 *
	 */
	if( $upgrade_from == 'free' ) {

		/**
		 * Get calendar data
		 *
		 */
		$calendars_options = get_option( 'wp-simple-booking-calendar-options' );

		// Get the first array key of the calendar
		foreach( $calendars_options['calendars'] as $key => $old_calendar_data ) {

			$calendar_id = $key;
			break;

		}

		if( ! empty( $calendars_options['calendars'][$calendar_id]['calendarJson'] ) ) {

			$calendar_bookings = json_decode( $calendars_options['calendars'][$calendar_id]['calendarJson'], true );

			/**
			 * Clean up bookings array keys and arrange every year and month array
			 * by keys, so that it's in chronological order
			 *
			 */
			foreach( $calendar_bookings as $year => $year_data ) {

				unset( $calendar_bookings[$year] );

				$year = absint( str_replace( 'year', '', $year ) );

				$calendar_bookings[$year] = $year_data;

				foreach( $year_data as $month => $month_data ) {

					unset( $calendar_bookings[$year][$month] );

					$month = absint( str_replace( 'month', '', $month ) );

					$calendar_bookings[$year][$month] = $month_data;
					
					ksort( $calendar_bookings[$year] );

					foreach( $month_data as $day => $booking ) {

						unset( $calendar_bookings[$year][$month][$day] );

						$day = absint( str_replace( 'day', '', $day ) );

						$calendar_bookings[$year][$month][$day] = $booking;

						ksort( $calendar_bookings[$year][$month] );

					}
					
				}

			}

			/**
			 * Add events based on bookings
			 *
			 */
			foreach( $calendar_bookings as $year => $year_data ) {

				foreach( $year_data as $month => $month_data ) {

					foreach( $month_data as $day => $booking ) {

						$event_data = array(
							'calendar_id' 	 => $calendar_id,
							'date_year'	  	 => $year,
							'date_month'  	 => $month,
							'date_day'	  	 => $day,
							'legend_item_id' => ( $booking == 'booked' ? 2 : ( $booking == 'changeover' ? 5 : 0 ) )
						);

						$event_id = wpsbc_insert_event( $event_data );

					}
					
				}

			}

		}

	}

	echo json_encode( array( 'success' => 1 ) );
	wp_die();

}
add_action( 'wp_ajax_wpsbc_action_ajax_migrate_bookings', 'wpsbc_action_ajax_migrate_bookings' );


/**
 * Handles the migration of the general settings from the old plugins to the new structure
 *
 */
function wpsbc_action_ajax_migrate_general_settings() {

	if( empty( $_POST['token'] ) || ! wp_verify_nonce( $_POST['token'], 'wpsbc_upgrader' ) ) {
		echo json_encode( array( 'success' => 0 ) );
		wp_die();
	}

	$upgrade_from = wpsbc_process_upgrade_from();

	if( false == $upgrade_from ) {
		echo json_encode( array( 'success' => 0 ) );
		wp_die();
	}

	/**
	 * Handle upgrade from old premium version
	 *
	 */
	if( $upgrade_from == 'old_premium' ) {

		/**
		 * Get old settings
		 *
		 */
		$old_settings = get_option( 'wpsbc-options', array() );

		if( ! empty( $old_settings ) )
			$old_settings = stripslashes_deep( json_decode( $old_settings, true ) );

		/**
		 * Get old language settings
		 *
		 */
		$old_languages = get_option( 'wpsbc-languages', array() );

		if( ! empty( $old_languages ) )
			$old_languages = stripslashes_deep( json_decode( $old_languages, true ) );

		/**
		 * Set new settings
		 *
		 */
		$new_settings = array();

		// History color
		if( ! empty( $old_settings['historyColor'] ) )
			$new_settings['booking_history_color'] = $old_settings['historyColor'];

		// Start day
		if( ! empty( $old_settings['backendStartDay'] ) )
			$new_settings['backend_start_day'] = $old_settings['backendStartDay'];

		// User roles
		if( ! empty( $old_settings['role_slug'] ) ) {

			$editable_roles = array_reverse( array_keys( get_editable_roles() ) );

			if( in_array( $old_settings['role_slug'], $editable_roles ) ) {

				foreach( $editable_roles as $key => $role ) {

					if( $role == $old_settings['role_slug'] )
						break;

					unset( $editable_roles[$key] );

				}

			}

			$new_settings['user_role_permissions'] = array_reverse( $editable_roles );

		}

		// Languages
		if( ! empty( $old_languages ) )
			$new_settings['active_languages'] = array_keys( $old_languages );


		// Add the settings
		update_option( 'wpsbc_settings', $new_settings );

	}

	echo json_encode( array( 'success' => 1 ) );
	wp_die();

}
add_action( 'wp_ajax_wpsbc_action_ajax_migrate_general_settings', 'wpsbc_action_ajax_migrate_general_settings' );


/**
 * Handles the migration of the general settings from the old plugins to the new structure
 *
 */
function wpsbc_action_ajax_migrate_finishing_up() {

	if( empty( $_POST['token'] ) || ! wp_verify_nonce( $_POST['token'], 'wpsbc_upgrader' ) ) {
		echo json_encode( array( 'success' => 0 ) );
		wp_die();
	}

	// Add the option that the upgrader has migrated the data
	update_option( 'wpsbc_upgrade_8_0_0', 1 );

	echo json_encode( array( 'success' => 1 ) );
	wp_die();

}
add_action( 'wp_ajax_wpsbc_action_ajax_migrate_finishing_up', 'wpsbc_action_ajax_migrate_finishing_up' );