<?php
/**
 * URMembership Frontend.
 *
 * @class    Frontend
 * @package  URMembership/Frontend
 * @category Frontend
 * @author   WPEverest
 */

namespace WPEverest\URMembership\Frontend;

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

/**
 * Frontend Class
 */
class Frontend {

	/**
	 * Hook in tabs.
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Initialize hooks.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	private function init_hooks() {
		add_action( 'wp_enqueue_membership_scripts', array( $this, 'load_scripts' ), 10, 2 );
		add_action( 'wp_loaded', array( $this, 'ur_add_membership_tab_endpoint' ) );
		add_filter( 'user_registration_account_menu_items', array( $this, 'ur_membership_tab' ), 10, 1 );

		add_action(
			'user_registration_account_ur-membership_endpoint',
			array(
				$this,
				'user_registration_membership_tab_endpoint_content',
			)
		);
	}

	/**
	 * Add the item to $items array.
	 *
	 * @param array $items Items.
	 */
	public function ur_membership_tab( $items ) {
		$current_user_id = get_current_user_id();
		$user_source     = get_user_meta( $current_user_id, 'ur_registration_source', true );

		if ( 'membership' !== $user_source ) {
			return $items;
		}
		$new_items                  = array();
		$new_items['ur-membership'] = __( 'Membership', 'user-registration' );
		$items                      = array_merge( $items, $new_items );

		return $this->delete_account_insert_before_helper( $items, $new_items, 'user-logout' );
	}

	/**
	 * Delete Account insert after helper.
	 *
	 * @param mixed $items Items.
	 * @param mixed $new_items New items.
	 * @param mixed $before Before item.
	 */
	public function delete_account_insert_before_helper( $items, $new_items, $before ) {

		// Search for the item position.
		$position = array_search( $before, array_keys( $items ), true );

		// Insert the new item.
		$return_items  = array_slice( $items, 0, $position, true );
		$return_items += $new_items;
		$return_items += array_slice( $items, $position, count( $items ) - $position, true );

		return $return_items;
	}

	/**
	 * Membership tab content.
	 */
	public function user_registration_membership_tab_endpoint_content() {
		$user_id = get_current_user_id();
		$this->load_scripts();
		$membership_repositories    = new \WPEverest\URMembership\Admin\Repositories\MembersRepository();
		$membership                 = $membership_repositories->get_member_membership_by_id( $user_id );
		$membership['post_content'] = json_decode( $membership['post_content'], true );

		ur_get_template(
			'myaccount/membership.php',
			array(
				'user'       => get_user_by( 'id', get_current_user_id() ),
				'membership' => $membership,
			)
		);
	}

	/**
	 * Add Membership tab endpoint.
	 */
	public function ur_add_membership_tab_endpoint() {

		$current_user_id = get_current_user_id();
		$user_source     = get_user_meta( $current_user_id, 'ur_registration_source', true );

		if ( 'membership' !== $user_source ) {
			return;
		}
		$mask = Ur()->query->get_endpoints_mask();

		add_rewrite_endpoint( 'ur-membership', $mask );
		flush_rewrite_rules();
	}

	/**
	 * Enqueue scripts
	 *
	 * @since 1.0.0
	 */
	public function load_scripts() {

		// Enqueue frontend scripts here.
		$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
		wp_enqueue_script( 'sweetalert2' );

		wp_register_script( 'user-registration-membership-frontend-script', UR_MEMBERSHIP_JS_ASSETS_URL . '/frontend/user-registration-membership-frontend' . $suffix . '.js', array( 'jquery' ), '1.0.0', true );
		wp_enqueue_script( 'user-registration-membership-frontend-script' );
		// Enqueue frontend styles here.
		wp_register_style( 'user-registration-membership-frontend-style', UR_MEMBERSHIP_CSS_ASSETS_URL . '/user-registration-membership-frontend.css', array(), UR_MEMBERSHIP_VERSION );
		wp_enqueue_style( 'user-registration-membership-frontend-style' );

		wp_enqueue_script( 'user-registration-membership-stripe-v3', 'https://js.stripe.com/v3/', array() );
		$this->localize_scripts();
	}

	/**
	 * Localize the frontend scripts with necessary data.
	 *
	 * This function uses the wp_localize_script function to add a JavaScript object
	 * to the frontend script. The object contains several properties:
	 * - `_nonce`: A WordPress nonce generated using wp_create_nonce function.
	 * - `ajax_url`: The URL of the admin-ajax.php file generated using admin_url function.
	 * - `login_url`: The URL of the login page generated using wp_login_url function.
	 * - `labels`: An array of internationalized labels generated by the get_i18_labels method.
	 *
	 * @return void
	 */
	public function localize_scripts() {
		$currency             = get_option( 'user_registration_payment_currency', 'USD' );
		$currencies           = ur_payment_integration_get_currencies();
		$symbol               = $currencies[ $currency ]['symbol'];
		$registration_page_id = get_option( 'user_registration_member_registration_page_id' );
		$redirect_page_url    = get_permalink( $registration_page_id );
		$thank_you_page_id    = get_option( 'user_registration_thank_you_page_id' );
		$thank_you_page       = get_permalink( $thank_you_page_id );
		$stripe_settings      = \WPEverest\URMembership\Admin\Services\Stripe\StripeService::get_stripe_settings();

		wp_localize_script(
			'user-registration-membership-frontend-script',
			'ur_membership_frontend_localized_data',
			array(
				'_nonce'                           => wp_create_nonce( 'ur_members_frontend' ),
				'_confirm_payment_nonce'           => wp_create_nonce( 'ur_membership_confirm_payment' ),
				'ajax_url'                         => admin_url( 'admin-ajax.php' ),
				'login_url'                        => wp_login_url(),
				'labels'                           => $this->get_i18_labels(),
				'currency_symbol'                  => $symbol,
				'membership_registration_page_url' => $redirect_page_url,
				'thank_you_page_url'               => $thank_you_page,
				'stripe_publishable_key'           => $stripe_settings['publishable_key'],
			)
		);
	}

	/**
	 * Retrieves an array of internationalized labels used in the frontend.
	 *
	 * @return array An associative array of internationalized labels.
	 */
	public function get_i18_labels() {

		return array(
			'network_error'                                => esc_html__( 'Network error', 'user-registration' ),
			'i18n_field_is_required'                       => _x( 'field is required.', 'user registration membership.', 'user-registration' ),
			'i18n_field_password_empty_validation'         => _x( 'Password cannot be empty', 'user registration membership.', 'user-registration' ),
			'i18n_field_email_field_validation'            => _x( 'Please enter a valid email address.', 'user registration membership.', 'user-registration' ),
			'i18n_field_confirm_password_field_validation' => _x( 'Password does not match with confirm password.', 'user registration membership.', 'user-registration' ),
			'i18n_field_password_field_length_validation'  => _x( 'Password must be at least 8 characters long', 'user registration membership.', 'user-registration' ),
			'i18n_field_password_field_regex_validation'   => _x( 'Password must contain at least one lowercase letter, one uppercase letter, one number, and one special character.', 'user registration membership', 'user-registration' ),
			'i18n_field_payment_gateway_field_validation'  => _x( 'Please select a Payment Gateway.', 'user registration membership', 'user-registration' ),
			'i18n_thank_you'                               => _x( 'Thank You', 'user registration membership', 'user-registration' ),
			'i18n_sign_in'                                 => _x( 'Sign In', 'user registration membership', 'user-registration' ),
			'i18n_order_successful'                        => _x( 'Your order has been successfully placed.', 'user registration membership', 'user-registration' ),
			'i18n_transaction_id'                          => _x( 'Please use this transaction ID for future references.', 'user registration membership', 'user-registration' ),
			'i18n_membership_required'                     => _x( 'Membership field is required.', 'user registration membership', 'user-registration' ),
			'i18n_coupon_invalid_error'                    => _x( 'Coupon is Invalid.', 'user registration membership', 'user-registration' ),
			'i18n_coupon_discount_message'                 => _x( 'discount on membership has been applied.', 'user registration membership', 'user-registration' ),
			'i18n_coupon_empty_error'                      => _x( 'Coupon Field is empty.', 'user registration membership', 'user-registration' ),
			'i18n_coupon_free_membership_error'            => _x( 'Invalid membership type (Free).', 'user registration membership', 'user-registration' ),
			'i18n_incomplete_stripe_setup_error'           => _x( 'Stripe Payment stopped. Incomplete Stripe setup.', 'user registration membership', 'user-registration' ),
			'i18n_error'                                   => _x( 'Error', 'user registration membership', 'user-registration' ),
			'i18n_empty_card_details'                      => __( 'Your card number is incomplete.', 'user-registration' ),
			'i18n_cancel_membership_text'                  => _x( 'Cancel membership.', 'user registration membership', 'user-registration' ),
			'i18n_cancel_membership_subtitle'              => _x( 'Are you sure you want to cancel membership permanently?', 'user registration membership', 'user-registration' ),
			'i18n_sending_text'                            => __( 'Sending ...', 'user-registration' ),
		);
	}
}
