<?php

namespace Simple_Giveaways;

/**
 * Class SG_Action_Register
 */
class SG_Action_Register extends SG_Extra_Action {

	/**
	 * Is this action using the action button.
	 *
	 * @var bool
	 */
	protected $has_action_button = false;

	/**
	 * SG_Action_Visit constructor.
	 */
	public function __construct() {
		$this->slug        = 'register';
		$this->category    = 'general';
		$this->title       = __( 'Register on the Site', 'giveasap' );
		$this->description = __( 'Rewards the user for registering with an account.', 'giveasap' );
		$this->icon        = 'fal fa-user';
	}

	public function get_fields() {

		$this->fields['register_link'] = array(
			'id'    => 'register_link',
			'label' => __( 'Registration Form Location', 'giveasap' ),
			'type'  => 'url',
			'desc'  => __( 'Where is the registration form located? Use this if you have a custom registration flow.', 'giveasap' ),
		);
		return parent::get_fields();
	}

	/**
	 * This function is used when completing the action.
	 *
	 * @return bool
	 */
	public function needs_validation() {
		return !is_user_logged_in();
	}

	/**
	 * Login the User
	 *
	 * @param $data
	 *
	 * @return \WP_Error|\WP_User
	 */
	protected function login_user( $data ) {

		if ( empty( $data['sg_login_form_username'] ) ) {
			return new \WP_Error( 'no-username', __( 'No Username or email provided', 'giveasap' ) );
		}

		if ( empty( $data['sg_login_form_password'] ) ) {
			return new \WP_Error( 'no-username', __( 'No Password provided', 'giveasap' ) );
		}

		$secure_cookie = '';
		$user_name     = sanitize_user( wp_unslash( $data['sg_login_form_username'] ) );
		$user          = get_user_by( 'login', $user_name );

		if ( ! $user && strpos( $user_name, '@' ) ) {
			$user = get_user_by( 'email', $user_name );
		}

		if ( ! $user ) {
			return new \WP_Error( 'no-user', __( 'No User found', 'giveasap' ) );
		}

		if ( get_user_option( 'use_ssl', $user->ID ) ) {
			$secure_cookie = true;
			force_ssl_admin( true );
		}

		$user = wp_signon(
			array(
				'user_login'    => $user->user_login,
				'user_password' => sanitize_text_field( $data['sg_login_form_password'] ),
			),
			$secure_cookie
		);

		return $user;
	}

	/**
	 * Register User
	 *
	 * @param $data
	 *
	 * @return int|\WP_Error|\WP_User
	 */
	protected function register_user( $data ) {
		if ( empty( $data['sg_register_form_email'] ) ) {
			return new \WP_Error( 'no-username', __( 'No Email provided', 'giveasap' ) );
		}

		if ( empty( $data['sg_register_form_username'] ) ) {
			return new \WP_Error( 'no-username', __( 'No Username provided', 'giveasap' ) );
		}

		if ( empty( $data['sg_register_form_password'] ) ) {
			return new \WP_Error( 'no-password', __( 'No Password provided', 'giveasap' ) );
		}

		$user_login = sanitize_text_field( $data['sg_register_form_username'] );
		$user_email = sanitize_text_field( $data['sg_register_form_email'] );
		$errors     = register_new_user( $user_login, $user_email );

		if ( is_wp_error( $errors ) ) {
			return $errors;
		}

		$user_id = $errors;

		wp_set_password( sanitize_text_field( $data['sg_register_form_password'] ), $user_id );
		update_user_option( $user_id, 'default_password_nag', false, true );

		$secure_cookie = '';

		if ( get_user_option( 'use_ssl', $user_id ) ) {
			$secure_cookie = true;
			force_ssl_admin( true );
		}

		$user = wp_signon(
			array(
				'user_login'    => $user_login,
				'user_password' => sanitize_text_field( $data['sg_register_form_password'] ),
			),
			$secure_cookie
		);

		return $user;
	}

	/**
	 * Validate the instance.
	 *
	 * @param $instance_id
	 * @param $subscriber_id
	 */
	public function validate( $instance_id, $subscriber_id, $data ) {
		$validation = parent::validate( $instance_id, $subscriber_id, $data );

		if ( $validation && ! empty( $data['sg_action_register_redirect'] ) ) {
			parse_str( wp_unslash( $_REQUEST['data'] ), $redirect_data );
			$redirect = esc_url_raw( $redirect_data['sg_action_register_redirect'] );
			return array(
				'redirect' => $redirect,
			);
		}

		return $validation;
	}

	/**
	 * Perform a specific task for the validation action.
	 *
	 * @param array $action An array ot from DB, in most cases, empty on validation.
	 *
	 * @return array|\WP_Error
	 */
	public function validate_action( $action, $data = array() ) {
		if ( ! isset( $data['action_check_value'] ) ) {
			return new \WP_Error( 'no-check-value', __( 'Something went wrong. Contact administrator.', 'giveasap' ) );
		}

		$result = null;

		if ( is_user_logged_in() ) {
			$result = wp_get_current_user();
		}

		if ( ! $result ) {
			switch ( $data['action_check_value'] ) {
				case 'register':
					$result = $this->register_user( $data );
					break;
				default:
					$result = $this->login_user( $data );
					break;
			}

			if ( is_wp_error( $result ) ) {
				return $result;
			}
		}

		return array( 'user_id' => $result->ID );
	}

	/**
	 * This is the value that we will show on the Entries table.
	 */
	public function get_value_for_entries_table( $data ) {

		if ( isset( $data['user_id'] ) ) {
			$user = get_user_by( 'id', $data['user_id'] );
			if ( $user ) {
				return '<a target="_blank" href="' . admin_url( 'user-edit.php?user_id=' . $data['user_id'] ) . '">' . $user->display_name . '</a>';
			}
		}
		return '';
	}

	/**
	 * Login Form
	 */
	public function login_form() {
		$admin_data    = $this->get_admin_data();
		$register_link = ! empty( $admin_data['register_link'] ) ? $admin_data['register_link'] : '';
		?>
		<div id="sgRegisterActionLoginForm<?php echo esc_attr( $this->get_instance_id() ); ?>" class="sg-action-form sg-action-login-form">
			<div class="sg-action-form-entry">
				<label for="sg_login_form_username">
					<?php esc_html_e( 'Username or Email', 'giveasap' ); ?>
				</label>
				<input type="text" id="sg_login_form_username" name="sg_login_form_username" />
			</div>

			<div class="sg-action-form-entry">
				<label for="sg_login_form_password">
					<?php esc_html_e( 'Password', 'giveasap' ); ?>
				</label>
				<input type="password" id="sg_login_form_password" name="sg_login_form_password" />
			</div>

			<button type="button" data-check-action="login" class="sg_extra_action_button giveasap_button">
				<?php esc_html_e( 'Login', 'giveasap' ); ?>
			</button>
			<?php
			if ( $register_link ) {
				$register_link = add_query_arg( 'redirect', giveasap_get_current_page_url(), $register_link );
				?>
					<a href="<?php echo esc_url( $register_link ); ?>" class="sg-button-link">
					<?php esc_html_e( 'Don\'t have an account? Click to register', 'giveasap' ); ?>
					</a>
				<?php
			} else {
				?>
                <a href="#" class="sg-toggle sg-button-link" data-target="#sgRegisterActionRegisterForm<?php echo esc_attr( $this->get_instance_id() ); ?>, #sgRegisterActionLoginForm<?php echo esc_attr( $this->get_instance_id() ); ?>" data-class="sg-hidden">
                    <?php esc_html_e( 'Don\'t have an account? Click to register', 'giveasap' ); ?>
                </a>
			<?php } ?>
		</div>
		<?php
	}

	/**
	 * Registration Form
	 */
	public function register_form() {
		$subscriber = giveasap_get_subscriber( $this->get_subscriber_id() );
		$email      = $subscriber->get_email();
		?>
		<div id="sgRegisterActionRegisterForm<?php echo esc_attr( $this->get_instance_id() ); ?>" class="sg-action-form sg-action-register-form sg-hidden">
			<div class="sg-action-form-entry">
				<label for="sg_register_form_email">
					<?php esc_html_e( 'Email', 'giveasap' ); ?>
				</label>
				<input type="email" id="sg_register_form_email" name="sg_register_form_email" value="<?php echo esc_attr( $email ); ?>" />
			</div>

			<div class="sg-action-form-entry">
				<label for="sg_register_form_username">
					<?php esc_html_e( 'Username', 'giveasap' ); ?>
				</label>
				<input type="text" id="sg_register_form_username" name="sg_register_form_username" />
			</div>

			<div class="sg-action-form-entry">
				<label for="sg_register_form_password">
					<?php esc_html_e( 'Password', 'giveasap' ); ?>
				</label>
				<input type="password" id="sg_register_form_password" name="sg_register_form_password" />
			</div>

			<button type="button" data-check-action="register" class="sg_extra_action_button giveasap_button">
				<?php esc_html_e( 'Register', 'giveasap' ); ?>
			</button>

			<a href="#" class="sg-toggle sg-button-link" data-target="#sgRegisterActionLoginForm<?php echo esc_attr( $this->get_instance_id() ); ?>, #sgRegisterActionRegisterForm<?php echo esc_attr( $this->get_instance_id() ); ?>" data-class="sg-hidden">
				<?php esc_html_e( 'Have an account? Click to login', 'giveasap' ); ?>
			</a>
		</div>
		<?php
	}

	/**
	 * Public
	 */
	public function form_public_content() {
		$data                  = $this->get_data();
		$this->submit_disabled = true;

		if ( $this->is_completed() ) {
			return;
		}

		if ( is_user_logged_in() ) {
			$this->submit_disabled = false;
			echo '<p>' . __( 'You are already logged-in. You can complete it.', 'giveasap' ) . '</p>';
			return;
		}

		$admin_data    = $this->get_admin_data();
		$register_link = ! empty( $admin_data['register_link'] ) ? $admin_data['register_link'] : '';

		?>
		<input type="hidden" name="sg_action_register_redirect" value="<?php echo esc_url( giveasap_get_current_page_url() ); ?>" />
		<?php
		$this->login_form();
		if ( ! $register_link ) {
			$this->register_form();
		}
	}

	/**
	 * @param array $action
	 *
	 * @return array|\WP_Error
	 */
	public function complete_action( $action, $data = array() ) {
		if ( ! is_user_logged_in() ) {
			return new \WP_Error( 'not-logged-in', __( 'You are not logged in. Please login with an account', 'giveasap' ) );
		}

		$user = wp_get_current_user();
		return array( 'user_id' => $user->ID );
	}

}
