<?php

namespace GemBoards\Frontend;

use GemBoards\Classes\Exception\GemboardsException;
use GemBoards\Entities\Role;
use GemBoards\Utils\Helper;

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

class Invitation {

	public static function init() {
		$self = new self();
		add_filter( 'init', array( $self, 'render_invitation_form' ) );
		add_action( 'admin_post_gemboards_invite_registration', array( $self, 'new_user_registration' ) );
		add_action( 'admin_post_nopriv_gemboards_invite_registration', array( $self, 'new_user_registration' ) );
	}

	public function render_invitation_form() {
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- We're just rendering a form.
		$is_invitation = isset( $_GET['gemboards_invitation'] ) && Helper::string_to_bool( sanitize_text_field( wp_unslash( $_GET['gemboards_invitation'] ) ) );
		if ( ! $is_invitation ) {
			return;
		}

		$hash = isset( $_GET['hash'] ) ? sanitize_text_field( wp_unslash($_GET['hash']) ) : '';
		// phpcs:enable
		if ( empty( $hash ) ) {
			return;
		}

		$invitation_id = Helper::get_invitation_id_from_hash( $hash );
		if ( ! $invitation_id ) {
			wp_die( esc_html__( 'Invalid invitation link.', 'gemboards' ) );
		}

		wp_enqueue_style( 'gemboards-app-style', GEMBOARDS_ASSETS_URI . 'css/new-user-registration.css', array(), filemtime( GEMBOARDS_ASSETS_DIR_PATH . 'css/new-user-registration.css' ) );

		$invitation = Helper::get_user_invitation( $invitation_id );

		Helper::get_template(
			'new-user-registration.php',
			array(
				'invitation' => $invitation,
			)
		);
		exit;
	}

	public function new_user_registration() {
		$hash             = sanitize_text_field( wp_unslash( $_POST['hash'] ?? '' ) );
		$nonce            = sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ?? '' ) );
		$firstname        = sanitize_text_field( wp_unslash( $_POST['firstname'] ?? '' ) );
		$lastname         = sanitize_text_field( wp_unslash( $_POST['lastname'] ?? '' ) );
		$password         = sanitize_text_field( wp_unslash( $_POST['password'] ?? '' ) );
		$confirm_password = sanitize_text_field( wp_unslash( $_POST['confirm_password'] ?? '' ) );

		if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'gemboards_invite_registration_nonce' ) ) {
			wp_die(
				esc_html__( 'Invalid nonce.', 'gemboards' ),
				esc_html__( 'Form nonce error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}

		if ( empty( $hash ) ) {
			wp_die(
				esc_html__( 'Invalid invitation link.', 'gemboards' ),
				esc_html__( 'Field error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}
		if ( empty( $firstname ) ) {
			wp_die(
				esc_html__( 'First name is required.', 'gemboards' ),
				esc_html__( 'Field error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}
		if ( empty( $lastname ) ) {
			wp_die(
				esc_html__( 'Last name is required.', 'gemboards' ),
				esc_html__( 'Field error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}
		if ( empty( $password ) ) {
			wp_die(
				esc_html__( 'Password is required.', 'gemboards' ),
				esc_html__( 'Field error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}
		if ( empty( $confirm_password ) ) {
			wp_die(
				esc_html__( 'Confirm password is required.', 'gemboards' ),
				esc_html__( 'Field error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}
		if ( $password !== $confirm_password ) {
			wp_die(
				esc_html__( 'Password & Confirmation password did not match.', 'gemboards' ),
				esc_html__( 'Field error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}

		$invitation_id = Helper::get_invitation_id_from_hash( $hash );
		if ( ! $invitation_id ) {
			wp_die(
				esc_html__( 'Invalid invitation link.', 'gemboards' ),
				esc_html__( 'Session error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}

		$invitation = Helper::get_user_invitation( $invitation_id );
		if ( ! $invitation ) {
			wp_die(
				esc_html__( 'Invalid invitation link.', 'gemboards' ),
				esc_html__( 'Session error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}

		$email         = $invitation->get_email();
		$base_username = strstr( $email, '@', true );
		$username      = $base_username;
		$counter       = 1;
		while ( username_exists( $username ) ) {
			$username = $base_username . $counter;
			$counter ++;
		}

		$user_id = wp_insert_user(
			array(
				'user_login'   => $username,
				'user_email'   => $email,
				'user_pass'    => $password,
				'role'         => 'subscriber',
				'display_name' => $firstname . ' ' . $lastname,
				'first_name'   => $firstname,
				'last_name'    => $lastname,
			)
		);
		if ( is_wp_error( $user_id ) ) {
			wp_die(
				esc_html(
					sprintf(
					// translators: %s: error message
						__( 'Registration failed: %s', 'gemboards' ),
						$user_id->get_error_message()
					)
				),
				esc_html__( 'Registration error', 'gemboards' ),
				array(
					'back_link' => true,
				)
			);
		}

		$role = new Role();
		$role->set_user_id( $user_id );
		$role->set_object_id( $invitation->get_object_id() );
		$role->set_role( 'member' );
		$role->save();

		try {
			$invitation->delete();
		} catch ( GemboardsException $e ) {
			Helper::error_log( $e->getMessage() );
		}

		wp_set_current_user( $user_id );
		wp_set_auth_cookie( $user_id, true );
		wp_safe_redirect( home_url( Helper::get_settings( 'path', '' ) ) );
	}
}
