<?php
/**
 * GiveASAP Updates
 *
 * @package giveasap
 */

use Simple_Giveaways\GA_Schedule;

if ( ! defined( 'ABSPATH' ) ) {
	return;
}

/**
 * Updates for Version 2.0.0
 * On this version we will move every giveaway entry into the new table
 * Getting entries from meta giveasap_registered_users and giveasap_registered_entries
 *
 * @return void
 * @since  2.0.0
 */
function giveasap_update_200() {

	// Make sure we are creating the database.
	$installer = new \Simple_Giveaways\GA_Installer();
	$installer->create_db();

	// Get all giveaways.
	$giveaways = get_posts(
		array(
			'posts_per_page' => -1,
			'post_status'    => 'any',
			'post_type'      => 'giveasap',
		)
	);

	foreach ( $giveaways as $giveaway ) {

		$users   = get_post_meta( $giveaway->ID, 'giveasap_registered_users', true );
		$entries = get_post_meta( $giveaway->ID, 'giveasap_registered_entries', true );

		if ( is_array( $users ) ) {
			foreach ( $users as $ref_id => $email ) {
				$user_entry = isset( $entries[ $ref_id ] ) ? $entries[ $ref_id ] : 0;
				giveasap_register_user( $giveaway->ID, $email, $user_entry, $ref_id );
			}
		}
	}
}

/**
 * Updates for Version 2.2.6
 *
 * @return void
 * @since  2.2.6
 */
function giveasap_update_206() {

	$giveaways = get_posts(
		array(
			'posts_per_page' => -1,
			'post_status'    => 'publish',
			'post_type'      => 'giveasap',
		)
	);

	foreach ( $giveaways as $giveaway ) {

		$post_id = $giveaway->ID;

		$schedule       = get_post_meta( $post_id, 'giveasap_schedule', true );
		$class_schedule = new GA_Schedule( $schedule );

		// Get the current Server Time.
		$current_time = time();

		// Get the Current WordPress time.
		$wp_current_time = current_time( 'timestamp' );

		$timezone = get_option( 'timezone_string' );

		$difference = 0;

		if ( ! $timezone ) {
			// Get the difference between. Difference will be minus if that time did not happen yet (such as GMT+0 and GMT+6).
			$difference = $wp_current_time - $current_time;
		}

		// Multiply by -1 to get + so NY != -6 --> == +6.
		$the_end_time = ( -1 ) * $difference + $class_schedule->get_end_timestamp();
		giveasap_update_meta( $post_id, 'end_time', $the_end_time );

	}
}

/**
 * Updating for Version 2.3.3
 * We are updating all unique ref IDs and sending emails
 *
 * @return void
 */
function giveasap_update_233() {
	global $wpdb;

	$giveaways = get_posts(
		array(
			'posts_per_page' => -1,
			'post_status'    => 'publish',
			'post_type'      => 'giveasap',
		)
	);

	$settings = get_option( 'giveasap_settings' );

	foreach ( $giveaways as $giveaway ) {

		$post_id   = $giveaway->ID;
		$entries   = giveasap_get_entries_for( $post_id );
		$permalink = get_permalink( $post_id );
		$title     = $giveaway->post_title;

		$previous_email = '';
		foreach ( $entries as $entry ) {

			if ( $previous_email === $entry->email ) {
				$wpdb->delete( $wpdb->giveasap_entries, array( 'id' => $entry->id ), array( '%d' ) );
				continue;
			}

			$previous_email = $entry->email;

			$ref_id = md5( $entry->id . $entry->email );

			$update = $wpdb->update(
				$wpdb->giveasap_entries,
				array(
					'ref_id' => $ref_id,
				),
				array(
					'id' => $entry->id,
				),
				array(
					'%s',
				),
				array( '%d' )
			);

			if ( false !== $update ) {
				$entry_link = $permalink . '?ref=' . $ref_id;
				$share_link = $permalink . '?share=' . $ref_id;

				$email                    = $entry->email;
				$subscriber_email         = isset( $settings['subscriber_email'] ) ? $settings['subscriber_email'] : '';
				$subscriber_email_subject = isset( $settings['subscriber_email_subject'] ) ? $settings['subscriber_email_subject'] : __( 'Thank you, {{TITLE}} for entering in this giveaway', 'giveasap' );

				$subscriber_email_subject = __( '[SECURITY UPDATE] ', 'giveasap' ) . str_replace( '{{TITLE}}', $title, $subscriber_email_subject );
				$subject_body_update      = '<p><strong>' . __( 'There was an update on your reference & share IDs for security reasons. Please use the ones below.', 'giveasap' ) . '</strong></p>';
				$subscriber_email         = str_replace( '{{TITLE}}', $title, $subscriber_email );
				$subscriber_email         = str_replace( '{{ENTRY_LINK}}', $entry_link, $subscriber_email );
				$subscriber_email         = str_replace( '{{SHARE_LINK}}', $share_link, $subscriber_email );

				$subscriber_email = $subject_body_update . $subscriber_email;

				giveasap_mail( $email, $subscriber_email_subject, $subscriber_email );

			}
		}
	}
}

/**
 * Removing duplicate entries in 2.3.5
 *
 * @return void
 */
function giveasap_update_235() {
	global $wpdb;

	$giveaways = get_posts(
		array(
			'posts_per_page' => -1,
			'post_status'    => 'publish',
			'post_type'      => 'giveasap',
		)
	);

	foreach ( $giveaways as $giveaway ) {

		$post_id = $giveaway->ID;
		$entries = giveasap_get_entries_for( $post_id );

		$entries_array = array();
		foreach ( $entries as $entry ) {

			if ( array_key_exists( $entry->email, $entries_array ) ) {
				$previous_entry = $entries_array[ $entry->email ];
				$points         = $previous_entry['points'];

				// First, let's check if the current one has more points than the previous one.
				// If it does, set those as the entry's points.
				if ( $points < $entry->entries ) {
					$delete_id = $previous_entry['id'];

					$previous_entry['points'] = $entry->entries;
					$previous_entry['id']     = $entry->id;

					$entries_array[ $entry->email ] = $previous_entry;
					$wpdb->delete( $wpdb->giveasap_entries, array( 'id' => $delete_id ), array( '%d' ) );
				} else {
					$wpdb->delete( $wpdb->giveasap_entries, array( 'id' => $entry->id ), array( '%d' ) );
				}
			} else {
				$entries_array[ $entry->email ] = array(
					'points' => $entry->entries,
					'id'     => $entry->id,
				);
			}
		}
	}
}

/**
 * Setting Post Meta for End Time instead of Giveaway Meta
 */
function giveasap_update_250() {
	global $wpdb;

	$posts = $wpdb->get_results( 'SELECT giveasap_id, meta_value FROM ' . $wpdb->giveasapmeta . " WHERE meta_key = 'end_time' " );

	if ( $posts ) {
		foreach ( $posts as $post ) {
			update_post_meta( $post->giveasap_id, 'end_time', $post->meta_value );
			giveasap_delete_meta( $post->giveasap_id, 'end_time' );
		}
	}

	$posts_winnertime = $wpdb->get_results( 'SELECT giveasap_id, meta_value FROM ' . $wpdb->giveasapmeta . " WHERE meta_key = 'winner_time' " );

	if ( $posts_winnertime ) {
		foreach ( $posts_winnertime as $post ) {
			update_post_meta( $post->giveasap_id, 'winner_time', $post->meta_value );
			giveasap_delete_meta( $post->giveasap_id, 'winner_time' );
		}
	}
}

/**
 * This update will use to go over each giveaway and update the winner postmeta in the new format.
 */
function giveasap_update_2100() {
	$giveaway_query = new WP_Query(
		array(
			'post_type'      => 'giveasap',
			'post_status'    => array( 'giveasap_winners', 'giveasap_notified' ),
			'posts_per_page' => -1,
			'fields'         => 'ids',
		)
	);
	$giveaway_ids   = $giveaway_query->posts;
	if ( $giveaway_ids ) {
		foreach ( $giveaway_ids as $id ) {
			$winners = giveasap_get_winners( $id );
			if ( $winners ) {
				$new_array = array();
				foreach ( $winners as $email => $emailed ) {
					if ( is_array( $emailed ) ) {
						// This is already a new way of saving it.
						continue;
					}
					$user = giveasap_get_user_by_email( $email, $id );
					// No user found, might not be sure.
					if ( null === $user ) {
						continue; }

					$new_array[] = array(
						'id'      => $user->id,
						'email'   => $email,
						'emailed' => $emailed,
					);
				}
				$winners = $new_array;
				giveasap_update_winners( $winners, $id );
			}
		}
	}
}

/**
 * This update will set the active column to 1 for all previous entries.
 */
function giveasap_update_2110() {
	global $wpdb;

	include_once GASAP_ROOT . '/includes/class-ga-installer.php';
	// Let's update the database.
	$installer = new \Simple_Giveaways\GA_Installer();
	$installer->install();

	$wpdb->query( 'UPDATE ' . $wpdb->giveasap_entries . ' SET active=1' );
}

/**
 * This update introduces Form Fields.
 * It will check if Name option is used and if it, create a form field.
 */
function giveasap_update_2160() {
	$settings = giveasap_get_settings();
	if ( isset( $settings['use_name_field'] ) && '1' === $settings['use_name_field'] ) {
		$form                    = giveasap_get_default_form_fields();
		$fields                  = array();
		$fields[0]               = array(
			'label'    => __( 'Name', 'giveasap' ),
			'name'     => 'user_name',
			'required' => '1',
		);
		$fields[1]               = $form[0];
		$settings['form_fields'] = $fields;
		update_option( 'giveasap_settings', $settings );
	}
}

/**
 * This update will remove the cached ConvertKit custom fields if available.
 */
function giveasap_update_2170() {
	delete_option( 'giveasap_convertkit_custom_fields' );
}

/**
 * Updating the entries table with new status column.
 */
function giveasap_update_2190() {
	global $wpdb;

	include_once GASAP_ROOT . '/includes/class-ga-installer.php';
	// Let's update the database.
	$installer = new \Simple_Giveaways\GA_Installer();
	$installer->install();

	if ( giveasap_is_activation_required() ) {
		$wpdb->query( $wpdb->prepare( 'UPDATE ' . $wpdb->giveasap_entries . ' SET status=%s WHERE active=0', 'pending' ) );
		$wpdb->query( $wpdb->prepare( 'UPDATE ' . $wpdb->giveasap_entries . ' SET status=%s WHERE active=1', 'active' ) );
	} else {
		$wpdb->query( $wpdb->prepare( 'UPDATE ' . $wpdb->giveasap_entries . ' SET status=%s', 'active' ) );
	}
}

/**
 * Updating the giveaway scripts and styles settings.
 */
function giveasap_update_2200() {
	global $wpdb;

	$settings = giveasap_get_settings();
	if ( ! $settings ) {
		$settings = array();
	}

	if ( ! isset( $settings['head_scripts'] ) ) {
		$settings['head_scripts'] = '';
	}

	if ( ! isset( $settings['footer_scripts'] ) ) {
		$settings['footer_scripts'] = '';
	}

	if ( $settings['head_scripts'] ) {
		$settings['head_scripts'] = wp_slash( '<script>' ) . $settings['head_scripts'] . wp_slash( '</script>' );
	}

	if ( $settings['footer_scripts'] ) {
		$settings['footer_scripts'] = wp_slash( '<script>' ) . $settings['footer_scripts'] . wp_slash( '</script>' );
	}

	update_option( 'giveasap_settings', $settings );

	include_once GASAP_ROOT . '/includes/class-ga-installer.php';
	// Let's update the database.
	$installer = new \Simple_Giveaways\GA_Installer();
	$installer->install();

	$extra_entries = $wpdb->get_results( $wpdb->prepare( 'SELECT post_id, meta_value FROM ' . $wpdb->postmeta . ' WHERE meta_key=%s', 'giveasap_extra_entries' ), ARRAY_A );
	if ( $extra_entries ) {
		foreach ( $extra_entries as $entry ) {
			$data    = maybe_unserialize( $entry['meta_value'] );
			$post_id = absint( $entry['post_id'] );

			if ( ! isset( $data['extra_actions'] ) ) {
				continue;
			}

			if ( ! $data['extra_actions'] ) {
				continue;
			}

			$actions = array();
			foreach ( $data['extra_actions'] as $index => $action_data ) {
				$action_info = array(
					'instance_id' => $index,
					'title'       => $action_data['text'],
					'button_text' => $action_data['text'],
					'entries'     => isset( $action_data['entries'] ) ? $action_data['entries'] : '',
					'url'         => isset( $action_data['url'] ) ? $action_data['url'] : '',
					'action'      => 'visit',
				);

				if ( 'link' !== $action_data['type'] ) {
					switch ( $action_data['social'] ) {
						case 'facebook':
							$action_info['action'] = 'facebook_visit';
							break;
						case 'twitter':
							$action_info['action']   = 'twitter_visit';
							$action_info['username'] = $action_data['username'];
							break;
						case 'instagram':
							$action_info['action']   = 'instagram_visit';
							$action_info['username'] = $action_data['username'];
							break;
						case 'youtube':
							$action_info['action'] = 'youtube_visit';
							break;
						default:
							break;
					}
				}

				$actions[] = $action_info;
			}

			$updated_data = array(
				'extra_actions'   => $data['extra_actions'],
				'entries_actions' => $actions,
			);

			update_post_meta( $post_id, 'giveasap_extra_entries', $updated_data );
		}
	}
}

/**
 * Update Facebook App ID to use fb_app_id instead of app_id.
 */
function giveasap_update_2231() {

	$facebook_settings = get_option( 'sg_facebook', null );

	// There are no fb settings saved, so we're good.
	if ( null === $facebook_settings ) {
		return;
	}

	$facebook_settings['fb_app_id']     = isset( $facebook_settings['app_id'] ) ? $facebook_settings['app_id'] : '';
	$facebook_settings['fb_app_secret'] = isset( $facebook_settings['app_secret'] ) ? $facebook_settings['app_secret'] : '';
	unset( $facebook_settings['app_id'] );
	unset( $facebook_settings['app_secret'] );
	update_option( 'sg_facebook', $facebook_settings );

}

/**
 * Move Background Image from Featured Image to Display settings.
 */
function giveasap_update_2310() {
	global $wpdb;

	$posts = $wpdb->get_results( 'SELECT post_id, meta_value FROM ' . $wpdb->postmeta . " WHERE meta_key = '_thumbnail_id' " );

	if ( $posts ) {
		foreach ( $posts as $post ) {
			$display_settings = get_post_meta( $post->post_id, 'giveasap_display', true );
			if ( ! $display_settings ) {
				continue;
			}
			$display_settings['background_image'] = $post->meta_value;
			update_post_meta( $post->post_id, 'giveasap_display', $display_settings );
		}
	}
}
