<?php
/**
 * Actions and Filters for Registration
 */

use Simple_Giveaways\SG_Action_Referred;
use Simple_Giveaways\SG_Action_Subscribe;
use Simple_Giveaways\SG_Subscriber;

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

add_action( 'giveasap_register_user', 'giveasap_register_subscribe_extra_action', 20, 4 );

/**
 * Add the extra action so we can see that as entries as well.
 *
 * @param integer $subscriber_id Subscriber ID.
 * @param integer $giveaway_id Giveaway ID.
 * @param string  $email Email.
 * @param integer $entry Entries.
 */
function giveasap_register_subscribe_extra_action( $subscriber_id, $giveaway_id, $email, $entry ) {
	$subscribe_action = new SG_Action_Subscribe();
	$subscribe_action->set_instance_id( -1 );
	$subscribe_action->set_giveaway_id( $giveaway_id );
	$subscribe_action->set_entries( $entry );
	$subscribe_action->set_subscriber_id( $subscriber_id );
	$subscribe_action->create_action(
		'completed',
		$giveaway_id,
		array(
			'title' => __( 'Subscribed to the Giveaway', 'giveasap' ),
		)
	);
}

add_action( 'giveasap_register_user', 'giveasap_register_user_form_fields', 20, 2 );

/**
 * Saving all extra form fields
 *
 * @param integer $entry_id Entry ID.
 * @param integer $giveaway_id Giveaway ID.
 */
function giveasap_register_user_form_fields( $entry_id, $giveaway_id ) {
	$form_fields = giveasap_get_form_fields( $giveaway_id );

	$posted_fields = isset( $_POST['sg_form'] ) ? \Simple_Giveaways\Helpers::unslash_and_clean( $_POST['sg_form'] ) : array();

	if ( $posted_fields ) {
        foreach ( $posted_fields as $field_key => $field_value ) {
            // Not a configured field? Maybe someone will save it differently.
            if ( ! isset( $form_fields[ $field_key ] ) ) {
                continue;
            }

            // Email is saved in the table.
            if ( 'user_email' === $field_key ) {
                continue;
            }

            giveasap_update_meta( $entry_id, '_' . $field_key, sanitize_text_field( $field_value ) );
        }
    }

    foreach ( $form_fields as $field_name => $form_field ) {
        if ( 'image' !== $form_field['type'] ) {
            continue;
        }

        $uploaded_image_id = \Simple_Giveaways\Helpers::upload_image( 'sg_form_' . $field_name, array( 'jpg', 'jpeg', 'png' ) );

        if ( ! is_wp_error( $uploaded_image_id ) ) {
            giveasap_update_meta( $entry_id, '_' . $field_name, absint( $uploaded_image_id ) );
        } else {
            var_dump($uploaded_image_id);
            die();
        }
    }
}

add_action( 'giveasap_activated_user', 'giveasap_give_referrer_entries_when_user_activated' );

/**
 * Give the entries to a referrer if the user is activated.
 *
 * @param integer $user_id User ID.
 */
function giveasap_give_referrer_entries_when_user_activated( $user_id ) {
	$entries_to_give = giveasap_get_meta( $user_id, '_entries_to_give', true );
	if ( ! $entries_to_give ) {
		return;
	}

	$referrer = giveasap_get_referrer( $user_id );
	if ( ! $referrer ) {
		return;
	}

	$subscriber = new SG_Subscriber( $referrer );
	$subscriber->add_entries( $entries_to_give );
	giveasap_delete_meta( $user_id, '_entries_to_give' );
	do_action( 'sg_referrer_awarded_points', $referrer, $entries_to_give, $user_id, $subscriber->get_giveaway_id() );
}

add_action( 'giveasap_register_user', 'giveasap_reset_giveaway_leaderboard_transient', 20, 2 );

/**
 * Delete the transient when a new user registers to the giveaway.
 *
 * @param integer $entry_id Subscriber Id.
 * @param integer $giveaway_id Giveaway Id.
 */
function giveasap_reset_giveaway_leaderboard_transient( $entry_id, $giveaway_id ) {
	giveasap_delete_leaderboard_transient( $giveaway_id );
}

add_action( 'giveasap_register_user', 'giveasap_save_http_referrer', 99 );
function giveasap_save_http_referrer( $entry_id ) {
    if ( ! isset( $_POST['sg_giveaway_http_referrer'] ) ) {
        return;
    }

    giveasap_update_meta( $entry_id, '_http_referrer', Simple_Giveaways\Helpers::unslash_and_clean( $_POST['sg_giveaway_http_referrer'] ) );

}

add_action( 'giveasap_update_user_entry', 'giveasap_reset_giveaway_leaderboard_transient_on_entry_update' );

/**
 * Reset the leaaderboard transient when we update the user entry.
 *
 * @param integer $entry_id Subscriber Id.
 */
function giveasap_reset_giveaway_leaderboard_transient_on_entry_update( $entry_id ) {
	$user        = giveasap_get_user_by_id( $entry_id );
	$giveaway_id = $user->post_id;
	giveasap_delete_leaderboard_transient( $giveaway_id );
}

add_action( 'giveasap_update_user_entry', 'giveasap_maybe_make_subscriber_a_winner' );

/**
 * Maybe make the current subscriber a winner.
 *
 * @param integer $entry_id Subscriber ID.
 */
function giveasap_maybe_make_subscriber_a_winner( $entry_id ) {
	$user = giveasap_get_user_by_id( $entry_id );
	if ( ! $user ) {
		return;
	}

	$subscriber  = giveasap_get_subscriber( $user );
	$giveaway_id = $subscriber->get_giveaway_id();

	if ( ! $giveaway_id ) {
		return;
	}

	$giveaway = giveasap_get_giveaway( $giveaway_id );

	if ( $giveaway->supports( 'prize_threshold' ) ) {
		$prizes     = $giveaway->get_prize_settings();
		$entries    = $subscriber->get_entries();
		$won_prizes = [];
		$winners    = giveasap_get_winners( $giveaway->get_id() );

		if ( ! $winners ) {
			$winners = array();
		}

		$winner_data     = [];
		$winner_position = null;
		foreach ( $winners as $index => $winner ) {
			if ( $winner['email'] === $subscriber->get_email() ) {
				$winner_data     = $winner;
				$winner_position = $index;
				break;
			}
		}

		if ( ! $winner_data ) {
			$winner_data = [
				'id'      => $subscriber->get_id(),
				'email'   => $subscriber->get_email(),
				'emailed' => 'no',
			];
		}

		foreach ( $prizes['prizes'] as $prize ) {
			if ( empty( $prize['threshold'] ) ) {
				continue;
			}

			if ( absint( $prize['threshold'] ) > $entries ) {
				continue;
			}

			$won_prizes[] = $prize;
		}

		$winner_data['prizes'] = $won_prizes;

		if ( ! is_null( $winner_position ) ) {
			$winners[ $winner_position ] = $winner_data;
		} else {
			$winners[] = $winner_data;
		}

		giveasap_update_winners( $winners, $giveaway_id );
		return;
	}

	if ( $giveaway->supports( 'winner_threshold' ) ) {
		$settings         = $giveaway->get_prize_settings();
		$winner_threshold = isset( $settings['winner_threshold'] ) ? absint( $settings['winner_threshold'] ) : 0;

		if ( $winner_threshold && absint( $subscriber->get_entries() ) === $winner_threshold ) {
			giveasap_subscriber_make_winner( $subscriber, $giveaway );
		}
	}
}

add_filter( 'sg_giveaway_supports', 'giveasap_add_prize_threshold_as_support', 10, 4 );

/**
* @param array  $supports All features currently supported.
* @param string $type Type of giveaway.
* @param string $feature Feature.
* @param \Simple_Giveaways\SG_Giveaway $giveaway Giveaway object.
* @return array
 */
function giveasap_add_prize_threshold_as_support( $supports, $type, $feature, $giveaway ) {

	if ( isset( $supports[ $feature ] ) ) {
		return $supports;
	}

	if ( 'prize_threshold' !== $feature ) {
		return $supports;
	}

	$prize_settings = $giveaway->get_prize_settings();

	if ( empty( $prize_settings['type'] ) ) {
		return $supports;
	}

	if ( 'threshold' !== $prize_settings['type'] ) {
		return $supports;
	}

	$supports[] = 'prize_threshold';
	return $supports;
}

add_action( 'sg_referrer_awarded_points', 'giveasap_notify_referrer_on_new_entries', 20, 3 );

/**
 * Send Referrer on new entries.
 *
 * @param integer $referrer_id Subscriber ID that referred.
 * @param integer $entries Entries.
 * @param integer $user_id Subscriber ID that got referred.
 */
function giveasap_notify_referrer_on_new_entries( $referrer_id, $entries, $user_id ) {
	$settings = giveasap_get_settings();
	$notify   = isset( $settings['send_referrer_email'] ) ? absint( $settings['send_referrer_email'] ) : false;

	if ( $notify ) {
		giveasap_send_referrer_email( $referrer_id, $entries, $user_id );
	}
}

add_action( 'sg_referrer_awarded_points', 'giveasap_add_referrer_as_extra_action', 20, 3 );

/**
 * Send Referrer on new entries.
 *
 * @param integer $referrer_id Subscriber ID that referred.
 * @param integer $entries Entries.
 * @param integer $user_id Subscriber ID that got referred.
 */
function giveasap_add_referrer_as_extra_action( $referrer_id, $entries, $user_id ) {
	$referrer         = giveasap_get_subscriber( $referrer_id );
	$subscribe_action = new SG_Action_Referred();
	$subscribe_action->set_instance_id( -1 );
	$subscribe_action->set_giveaway_id( $referrer->get_giveaway_id() );
	$subscribe_action->set_entries( $entries );
	$subscribe_action->set_subscriber_id( $referrer_id );
	$subscribe_action->create_action(
		'completed',
		$referrer->get_giveaway_id(),
		array(
			'title' => __( 'Referred a user', 'giveasap' ),
			'user'  => giveasap_get_subscriber( $user_id ),
		)
	);
}

add_filter( 'sg_giveaway_redirect_entry_link', 'giveasap_add_form_fields_to_link', 20, 2 );

/**
 * Add Form Fields as Query string to link
 *
 * @param string         $link Link URL.
 * @param GiveASAP_Front $front Front object.
 */
function giveasap_add_form_fields_to_link( $link, $front ) {

	$giveaway = $front->get_giveaway_id();
	if ( $giveaway ) {
		$subscriber = $front->get_subscriber();
		if ( ! $subscriber ) {
			return $link;
		}

		$form_fields = giveasap_get_form_fields( $giveaway );
		$meta        = giveasap_get_meta( $subscriber->get_id() );
		if ( $meta && $form_fields ) {
			foreach ( $form_fields as $field_slug => $field ) {
				if ( ! isset( $field['query_string'] ) ) {
					continue;
				}

				if ( 1 !== absint( $field['query_string'] ) ) {
					continue;
				}

				if ( 'user_name' === $field_slug ) {
					$value = isset( $meta[ '_' . $field_slug ] ) ? $meta[ '_' . $field_slug ] : '';

					if ( ! $value ) {
						$value = isset( $meta['_name'] ) ? $meta['_name'] : '';
					}
				} else {
					$value = isset( $meta[ '_' . $field_slug ] ) ? $meta[ '_' . $field_slug ] : '';
				}

				if ( ! $value ) {
					continue;
				}

				if ( is_array( $value ) ) {
					$field_value = implode( ',', $value );
				} else {
					$field_value = $value;
				}

				$link = add_query_arg( $field_slug, $field_value, $link );
			}
		}
	}

	return $link;
}
