<?php
/**
 * Dashboard functions
 *
 * @package wpstream-theme
 */

add_action( 'wp_ajax_wpstream_remove_post_id', 'wpstream_theme_remove_post_id_callback' );

if ( ! function_exists( 'wpstream_theme_remove_post_id_callback' ) ) {
	/**
	 * Callback handler to remove a post ID from the "watch later" list.
	 */
	function wpstream_theme_remove_post_id_callback() {
		if ( ! is_user_logged_in() ) {
			wp_send_json_error( 'You must be logged in to perform this action.' );
			die();
		}

		// Verify the nonce.
		if ( isset( $_POST['wpstream_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['wpstream_nonce'] ) ), 'wpstream-watch-later-nonce' ) ) {
			if ( isset( $_POST['postID'] ) ) {
				$post_id_to_remove = intval( $_POST['postID'] );
				$meta_key          = 'wpstream_user_watch_later_items';
				$current_user      = wp_get_current_user();
				$user_id           = $current_user->ID;

				// Get the current array of post IDs.
				$watch_later_item_ids = get_user_meta( $user_id, $meta_key, true );

				// Remove the specific ID from the array.
				$watch_later_item_ids = array_filter(
					$watch_later_item_ids,
					function ( $id ) use ( $post_id_to_remove ) {
						return $id !== $post_id_to_remove;
					}
				);

				// Update the user's metadata with the modified array.
				update_user_meta( $user_id, $meta_key, $watch_later_item_ids );

				$response = array(
					'success' => true,
					'message' => 'Item removed',
				);

			} else {
				$response = array(
					'success' => false,
					'message' => 'Invalid postID format.',
				);
			}
		} else {
			$response = array(
				'success' => false,
				'message' => 'Nonce verification failed.',
			);
		}

		wp_send_json( $response );

		wp_die();
	}
}

//add_action( 'wp_ajax_wpstream_dashboard_save_channel_data', 'wpstream_dashboard_save_channel_data' );
/**
 * Saves channel data from the dashboard.
 *
 * Handles the saving of channel data from the dashboard, including title, description,
 * thumbnail ID, images, category terms, and whether the channel is paid.
 */
function wpstream_dashboard_save_channel_data() {
	// Verify the nonce for security
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'wpstream_edit_channel_nonce' ) ) {
		die( 'Permission denied.' );
	}
	if ( ! is_user_logged_in() ) {
		wp_send_json_error( array( 'error' => 'User is not logged in.' ) );
		die();
	}

	$thumb_id     = isset( $_POST['thumb_id'] ) ? intval( $_POST['thumb_id'] ) : 0;
	$title        = sanitize_text_field( $_POST['title'] );
	$description  = sanitize_text_field( $_POST['description'] );
	$channel_paid = intval( $_POST['channel_paid'] );
	$images       = sanitize_text_field( $_POST['images'] );
        $images       = trim($images,',');
        $channel_price=0;
	if ( isset( $_POST['channel_price'] ) ) {
		$channel_price = floatval( $_POST['channel_price'] );
	}
	$postID = intval( $_POST['postID'] );
    $trailer_video = isset( $_POST['trailer_video'] ) ? sanitize_text_field( $_POST['trailer_video'] ) : '';
    $preview_video = isset( $_POST['preview_video'] ) ? sanitize_text_field( $_POST['preview_video'] ) : '';

	$new_post_type = 'wpstream_product';
	if ( $channel_paid == 1 ) {
		$new_post_type = 'product';
		update_post_meta( $postID, '_price', $channel_price );
		update_post_meta( $postID, '_regular_price', $channel_price );

	}

    if ( $trailer_video ) {
        update_post_meta( $postID, 'video_trailer', $trailer_video );
    }
	if ( $preview_video ) {
		update_post_meta( $postID, 'video_preview', $preview_video );
	}

	if ( $postID != '0' ) {
		$post_data = array(
			'ID'           => $postID,
			'post_title'   => $title,
			'post_content' => $description,
			'post_type'    => $new_post_type,
		);
		wp_update_post( $post_data );
		set_post_thumbnail( $postID, $thumb_id );


		/*
		* Manage images
		*/
		if ( $channel_paid == 1 ) {
			update_post_meta( $postID, '_product_type', 'live_stream' );
			wp_set_post_terms( $postID, 'live_stream', 'product_type' );
			update_post_meta( $postID, '_product_image_gallery', $images );
		} else {

			$images_array = explode( ',', $images );
                        delete_post_meta( $postID, 'wpstream_theme_gallery' );
			foreach ( $images_array as $key => $value ) :
                            add_post_meta( $postID, 'wpstream_theme_gallery', $value, false );
			endforeach;
		}
		$gallery_images = wpstream_theme_return_image_gallery( $postID );




		/*
		* Manage categories
		*/
		if(isset( $_POST['selected_categories'])):
			$categories = $_POST['selected_categories'];
			foreach ( $categories as $taxonomy => $term_ids ) {

				if ( ! is_array( $term_ids ) ) {
					$term_ids = array( $term_ids );
				}
				$term_ids = array_map( 'intval', $term_ids );

				wp_set_object_terms( $postID, $term_ids, $taxonomy );
			}
		endif;

		$taxonomy_information = wpstream_theme_return_taxoomy_information( $postID );

        $video_trailer = wpstream_theme_return_trailer_video( $postID );

        $video_preview = wpstream_theme_return_preview_video( $postID );

		wp_send_json_success(
			array(
				'succes'     => true,
				's'          => $images,
				'thumburl'   => get_the_post_thumbnail_url( $postID, 'wpstream_featured_unit_cards' ),
				'images'     => wpstream_theme_build_html_gallery_dashboard( $gallery_images ),
				'taxonomies' => $taxonomy_information['html'],
                                'channel_paid'=>$channel_paid,
                                'channel_price'=>$channel_price,
                'video_trailer' => $video_trailer,
                'video_preview' => $video_preview,
				'message'    => esc_html__( 'Changes saved successfully.', 'hello-wpstream' ),
			)
		);
		die();

	}
}

if ( ! function_exists( 'wpstream_theme_return_taxoomy_information' ) ) {
	/**
	 * Returns information about taxonomies for the specified post.
	 *
	 * @param int $post_id The post ID.
	 * @return array An array containing information about taxonomies and HTML markup.
	 */
	function wpstream_theme_return_taxoomy_information( $post_id ) {
		$post_type    = get_post_type( $post_id );
		$taxonomies   = get_object_taxonomies( $post_type );
		$all_terms    = array();
		$return_array = array();

		// Loop through each taxonomy and get terms attached to the post.
		foreach ( $taxonomies as $taxonomy_slug ) {
			if ( 'product_type' !== $taxonomy_slug && 'product_visibility' !== $taxonomy_slug ) {
				$taxonomy_obj  = get_taxonomy( $taxonomy_slug );
				$taxonomy_name = $taxonomy_obj->labels->name; // This fetches the name of the taxonomy.
				$terms         = wp_get_post_terms( $post_id, $taxonomy_slug, array( 'fields' => 'all' ) ); // fetch all fields of the term.

				if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
					$all_terms[ $taxonomy_name ] = $terms;
				}
			}
		}

		$return_html = '';

		foreach ( $all_terms as $taxonomy => $terms ) {
			$return_html .= ' <div  class="wpstream-dashboard-details" >';
			$return_html .= '<div class="wpstream-dashboard-details-header">' . $taxonomy . '</div>';
			$return_html .= '<div class="wpstream_account_details_value" id="wpstream_' . sanitize_key( $taxonomy ) . '">';

			foreach ( $terms as $term ) {
				$return_html .= '<span class="wpstream_term_selected">' . $term->name . '</span>';
			}

			$return_html .= ' </div>
 
            </div>  ';
		}

		$return_array['tax_information'] = $all_terms;
		$return_array['html']            = $return_html;

		return $return_array;
	}
}

/**
 * Display address modal.
 *
 * This function generates and displays the address modal with provided parameters.
 *
 * @param string $modal_id       The ID of the modal.
 * @param string $button_id      The ID of the button that triggers the modal.
 * @param string $title          The title of the modal.
 * @param array  $address_fields An array of address fields.
 * @param int    $user_id        The ID of the user.
 *
 * @return string The HTML string of the address modal.
 */
function wpstream_address_modal_display( $modal_id, $button_id, $title, $address_fields, $user_id ) {
	$return_string = '<button type="button" class="edit wpstream-dashboard-address__edit-link" data-bs-toggle="modal" data-bs-target="#' . esc_attr( $modal_id ) . '">'
		. wpstream_theme_get_svg_icon( 'edit_icon_black.svg' ) .
		esc_html( $title ) .
		'</button>';

	$return_string .= '<div class="modal fade wpstream-modal" id="' . esc_attr( $modal_id ) . '" tabindex="-1"

    aria-labelledby="wpstream_edit_addr_modal_label" aria-hidden="true">

    <div class="modal-dialog">

    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">
              ' . esc_html( $title ) . '
            </h5>

            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="modal-body wpstream-modal-body">';

	ob_start();

	foreach ( $address_fields as $key => $field ) {
		$saved_value = get_user_meta( $user_id, $key, true );

		woocommerce_form_field( $key, $field, wc_get_post_data_by_key( $key, $saved_value ) );
	}

	$return_string .= ob_get_contents();

	ob_end_clean();

	$return_string .= '<input type="hidden" name="wpstream_nonce" value="' . wp_create_nonce( 'wpstream_edit_addr_nonce' ) . '" />
      </div>

      <div class="modal-footer">
        <button type="button" class="wpstream-button wpstream-button--transparent" data-bs-dismiss="modal">
        ' . esc_html__( 'Close', 'hello-wpstream' ) . '
        </button>

        <button type="button" id="' . esc_attr( $button_id ) . '" class="wpstream-gradient-button">
        ' . esc_html__( 'Save Changes', 'hello-wpstream' ) . '
        </button>
      </div>
    </div>
  </div>
</div>';

	return $return_string;
}

if ( ! function_exists( 'wpstream_is_dashboard_page' ) ) {
	/**
	 * Check if the current page is the dashboard page.
	 *
	 * This function checks if the current page is the dashboard page. It can also
	 * optionally accept extra conditions.
	 *
	 * @return bool True if the current page is the dashboard page, false otherwise.
	 */
	function wpstream_is_dashboard_page() {
		if ( wpstream_check_woo_active() && is_account_page() ) {
			return true;
		} elseif ( get_page_template_slug() === 'wpstream-theme-dashboard.php' ) {
			return true;
		}

		return false;
	}
}

if ( ! function_exists( 'wpstream_non_woo_get_account_endpoint_url' ) ) {
	/**
	 * Retrieves the URL for a given account endpoint.
	 *
	 * @param string $endpoint Optional. Endpoint to append to the URL.
	 * @return string URL for the account endpoint.
	 */
	function wpstream_non_woo_get_account_endpoint_url($endpoint = '')
	{
		$url = wpstream_return_dashboard_page();

		if ($endpoint) {
			$url = add_query_arg('endpoint', $endpoint, $url);
		}

		return esc_url_raw($url);
	}
}

if ( ! function_exists( 'wpstream_generate_user_menu' ) ) {
	/**
	 * Generate user menu
	 */
	function wpstream_generate_user_menu() {
		$return_string = '';

		$svg_icons = [
			'dashboard' => wpstream_theme_get_svg_icon('dashboard.svg'),
			'orders' => wpstream_theme_get_svg_icon('orders-icon.svg'),
			'subscriptions' => wpstream_theme_get_svg_icon('orders-subscription.svg'),
			'edit-address' => wpstream_theme_get_svg_icon('location-icon.svg'),
			'edit-account' => wpstream_theme_get_svg_icon('edit-account-icon.svg'),
			'event-list' => wpstream_theme_get_svg_icon('purchased-events-icon.svg'),
			'video-list' => wpstream_theme_get_svg_icon('purchased-video-icon.svg'),
			'start-streaming' => wpstream_theme_get_svg_icon('go-to-live-icon.svg'),
			'watch-later' => wpstream_theme_get_svg_icon('watch-later-icon.svg'),
			'customer-logout' => wpstream_theme_get_svg_icon('logout_icon.svg'),
			'logout' => wpstream_theme_get_svg_icon('logout_icon.svg'),
		];

		ob_start();

		if ( function_exists( 'wc_get_account_menu_items' ) ) {
			$menu_items = wc_get_account_menu_items();

			if ( ! wpstream_check_if_user_can_stream()) {
				unset($menu_items['start-streaming']);
			}

			foreach ( $menu_items as $endpoint => $label ) :
				$menu_link= wc_get_account_endpoint_url( $endpoint ) ;
				if($endpoint === 'subscriptions') {
				   $menu_link = home_url('/dashboard/subscriptions/');
				}
				?>
				<a href="<?php echo esc_url($menu_link); ?>" class="list-group-item list-group-item-action wpstream-account-item-<?php echo esc_attr( $endpoint ); ?>">
                    <?php echo isset($svg_icons[$endpoint]) ? trim($svg_icons[$endpoint]) : ''; ?>
                    <?php echo trim( esc_html( $label ));?>
                </a>
				<?php
			endforeach;

		} else {
			$menu_items = array(
				'dashboard'       => esc_html__( 'Dashboard', 'hello-wpstream' ),
				'start-streaming' => esc_html__( 'Go Live', 'hello-wpstream' ),
				'edit-account'    => esc_html__( 'Edit Account', 'hello-wpstream' ),
				'watch-later'     => esc_html__( 'Watch Later', 'hello-wpstream' ),
				'logout'          => esc_html__( 'Logout', 'hello-wpstream' ),
			);

			if ( ! wpstream_check_if_user_can_stream()) {
				unset($menu_items['start-streaming']);
			}

			foreach ( $menu_items as $endpoint => $label ) :
				$item_link = wpstream_non_woo_get_account_endpoint_url( $endpoint );
				if ( 'logout' === $endpoint ) {
					$item_link = wp_logout_url( home_url() );
				}
				?>

				<a href="<?php echo esc_url( $item_link ); ?>"
					class="list-group-item list-group-item-action wpstream-account-item-<?php echo esc_attr( $endpoint ); ?>">
					<?php echo trim($svg_icons[ $endpoint ]) ?? ''; ?>
                    <?php echo esc_html( $label ); ?>
                </a>
				<?php

			endforeach;

		}

		$return_string = ob_get_contents();

		ob_end_clean();

		return $return_string;
	}
}

if ( ! function_exists( 'wpstream_show_live_streaming_controls' ) ) {
	/**
	 * Show live streaming controls.
	 *
	 * This function displays the live streaming controls if the current user is allowed to stream.
	 *
	 * @param WP_User $current_user The current user object.
	 * @param int     $post_id      The ID of the post.
	 * @return string|null The HTML string of live streaming controls, or null if the current user is not allowed to stream.
	 */
	function wpstream_show_live_streaming_controls( $current_user, $post_id ) {
		if ( wpstream_users_allowed_to_stream() ) {
			ob_start();

			global $wpstream_plugin;
			
			if (isset($wpstream_plugin) && method_exists($wpstream_plugin, 'wpstream_live_stream_unit_wrapper_for_theme')) {
				$wpstream_plugin->wpstream_live_stream_unit_wrapper_for_theme($post_id, 'front');
			} else {
				esc_html__('You need to activate the WPStream plugin to use this feature.', 'hello-wpstream');
			}

			$return_string = ob_get_contents();

			ob_end_clean();

		}

		return $return_string;
	}
}

if ( ! function_exists( 'wpstream_theme_create_channel' ) ) {
	/**
	 * Create channel for the theme.
	 */
	function wpstream_theme_create_channel() {
		$maxim_channels_per_user  = wpstream_return_max_channels_per_user();
		$allow_user_paid_channels = wpstream_return_user_can_create_paid();
		$how_many_posts           = wpstream_theme_return_user_channel_list( '', 'found_posts' );

	
		?>

		<?php if ( ( $how_many_posts < $maxim_channels_per_user ) || current_user_can( 'manage_options' ) ) : ?>
			<div class="wpstream-dashboard-start-streaming__cta-wrapper_buttons">
				<div class="wpstream_theme_button_dashboard wpstream_user_create_new_channel">
					<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path fill-rule="evenodd" clip-rule="evenodd" d="M12 6.25C12.4142 6.25 12.75 6.58579 12.75 7V11.25H17C17.4142 11.25 17.75 11.5858 17.75 12C17.75 12.4142 17.4142 12.75 17 12.75H12.75V17C12.75 17.4142 12.4142 17.75 12 17.75C11.5858 17.75 11.25 17.4142 11.25 17V12.75H7C6.58579 12.75 6.25 12.4142 6.25 12C6.25 11.5858 6.58579 11.25 7 11.25H11.25V7C11.25 6.58579 11.5858 6.25 12 6.25Z" fill="#0F0F0F"/>
					</svg>

					<?php echo esc_html__( 'New Free Channel', 'hello-wpstream' ); ?>
				</div>

				<?php if ( class_exists( 'WooCommerce' ) && ( $allow_user_paid_channels || current_user_can( 'manage_options' ) ) ) : ?>
					<div class="wpstream_theme_button_dashboard wpstream_user_create_new_paid_channel">
						<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
							<path fill-rule="evenodd" clip-rule="evenodd" d="M12 6.25C12.4142 6.25 12.75 6.58579 12.75 7V11.25H17C17.4142 11.25 17.75 11.5858 17.75 12C17.75 12.4142 17.4142 12.75 17 12.75H12.75V17C12.75 17.4142 12.4142 17.75 12 17.75C11.5858 17.75 11.25 17.4142 11.25 17V12.75H7C6.58579 12.75 6.25 12.4142 6.25 12C6.25 11.5858 6.58579 11.25 7 11.25H11.25V7C11.25 6.58579 11.5858 6.25 12 6.25Z" fill="#0F0F0F"/>
						</svg>

						<?php echo esc_html__( 'New Paid Channel', 'hello-wpstream' ); ?>
					</div>
				<?php endif; ?>
			</div>		
			<?php
				if ( ! current_user_can( 'manage_options' ) ) {
					/* translators: %1$s - number of channels, %2$s - maximum number of channels */
					$translated_string = sprintf( esc_html__( 'You have, %1$s channels from %2$s possible', 'hello-wpstream' ), $how_many_posts, $maxim_channels_per_user );
					echo esc_html( $translated_string );
				}
			?>	



		<?php else : ?>
			<?php $translated_string = sprintf( esc_html__( 'You reach the maximum no of channels allowed.', 'hello-wpstream' ), $how_many_posts, $maxim_channels_per_user ); ?>

			<?php echo esc_html( $translated_string ); ?>
		<?php endif; ?>

		<?php
	}
}

/**
 * Recursively sanitize a variable or array of variables.
 *
 * This function recursively sanitizes a variable or array of variables. It strips all HTML tags and then allows only safe HTML
 * through wp_kses_post() to prevent XSS vulnerabilities.
 *
 * @param mixed $value The variable or array of variables to sanitize.
 * @return mixed The sanitized variable or array of variables.
 */
function wpstream_sanitize_recursive( $value ) {
	if ( is_array( $value ) ) {
		return array_map( 'wpstream_sanitize_recursive', $value );
	} else {
		return wp_kses_post( wp_strip_all_tags( $value ) );
	}
}

add_action( 'wp_ajax_wpstream_handle_channel_details_saving', 'wpstream_handle_channel_details_saving' );
/**
 * Handle AJAX request to save channel details.
 *
 * This function handles the AJAX request to save the details of a channel, including its title, description,
 * price, images, featured status, and taxonomies.
 *
 * @return void Outputs JSON-encoded response indicating success or failure of the operation.
 */
function wpstream_handle_channel_details_saving() {
	if ( ! is_user_logged_in() ) {
		wp_die();
	}

	check_ajax_referer( 'wpstream_user_channel_list', 'security' );

	if ( isset( $_POST['postID'] ) ) {
		$post_id = intval( $_POST['postID'] );
	}
	$current_user   = wp_get_current_user();
	$post_author_id = intval( get_post_field( 'post_author', $post_id ) );

	if ( $current_user->ID !== $post_author_id ) {
		echo wp_json_encode(
			array(
				'success'         => false,
				'$postID'         => $post_id,
				'$post_author_id' => $post_author_id,
				'message'         => esc_html__( 'You are not the owner of this channel', 'hello-wpstream' ),
			)
		);
	} else {
		if ( isset( $_POST['title'] ) ) {
			$title = sanitize_text_field( wp_unslash( $_POST['title'] ) );
		}
		if ( isset( $_POST['description'] ) ) {
			$sanitized_content = wp_kses_post( wp_unslash( $_POST['description'] ) );
		}
		$price = 0;

		if ( isset( $_POST['price'] ) ) {
			$price = sanitize_text_field( wp_unslash( $_POST['price'] ) );
		}

		if ( isset( $_POST['images'] ) ) {
			$images = sanitize_text_field( wp_unslash( $_POST['images'] ) );
		}

		if ( isset( $_POST['featured'] ) ) {
			$featured = intval( $_POST['featured'] );
		}

		if ( isset( $_POST['taxonomies'] ) ) {
			$taxonomies_raw = sanitize_text_field( wp_unslash( $_POST['taxonomies'] ) );
			$taxonomies     = is_array( $taxonomies_raw ) ? array_map( 'wpstream_sanitize_recursive', $taxonomies_raw ) : array();
		}
		$images = rtrim( ltrim( trim( $images ), ',' ), ',' );

		if ( get_post_type( $post_id ) === 'product' ) {
			update_post_meta( $post_id, '_product_image_gallery', $images );
			update_post_meta( $post_id, '_regular_price', $price );
		} else {
			$images_array = wpstream_get_attachment_data( $images );
			$images_array = explode( ',', $images );
			foreach ( $images_array as $key => $value ) :
				add_post_meta( $post_id, 'wpstream_theme_gallery', $value );
			endforeach;
		}

		if ( isset( $_POST['videoTrailer'] ) ) {
            var_dump( $_POST );
            var_dump( $_POST['videoTrailer'] );
			update_post_meta( $post_id, 'video_trailer', $_POST['videoTrailer'] );
		}

		set_post_thumbnail( $post_id, $featured );

		$post_data = array(
			'ID'           => $post_id,
			'post_title'   => $title,
			'post_content' => $sanitized_content,
		);

		// Update the post.
		wp_update_post( $post_data );

		foreach ( $taxonomies as $taxonomy => $term_ids ) {
			wp_remove_object_terms( $post_id, '', $taxonomy );

			if ( is_array( $term_ids ) ) {
				foreach ( $term_ids as $key => $term_id ) {
					if ( 'product_tag' === $taxonomy || 'post_tag' === $taxonomy ) {
						$tagterm = get_term( $term_id );

						if ( $tagterm && ! is_wp_error( $tagterm ) ) {
							$tag_term_name = $tagterm->name;
							wp_set_post_terms( $post_id, $tag_term_name, $taxonomy, true );
						}
					} elseif ( -1 !== $term_id ) {
						wp_set_post_terms( $post_id, intval( $term_id ), $taxonomy, true );
					}
				}
			}
		}

		echo wp_json_encode(
			array(
				'success'            => true,
				'$price'             => $price,
				'message'            => esc_html__( 'Channel updated', 'hello-wpstream' ),
				'title'              => $title,
				'$sanitized_content' => $sanitized_content,
				'$images'            => $images,
				'$featured'          => $featured,
				'$taxonomies'        => $taxonomies,
				'$videoTrailer'      => $_POST['videoTrailer'],
			)
		);
	}

	wp_die();
}

/**
 * Return user channel edit form.
 *
 * This function generates and returns the edit form for a user channel.
 *
 * @param int $user_id           The ID of the user.
 * @param int $current_selection The ID of the current selection (post).
 * @return string|null The HTML string of the user channel edit form, or null if the user is not authorized to edit the channel.
 */
function wpstream_theme_return_user_channel_edit_form( $user_id, $current_selection ) {
	$post_author_id = intval( get_post_field( 'post_author', $current_selection ) );

	if ( $user_id !== $post_author_id ) {
		return;
	}

	ob_start();

	?>

	<div class="wpstream_theme_return_user_channel_edit_form_wrapper">
		<label><?php esc_html_e( 'Channel Name', 'hello-wpstream' ); ?></label>

		<input type="text" id="wpstream_channel_name" name="wpstream_channel_name"
				value="<?php echo esc_html( get_the_title( $current_selection ) ); ?>">

		<?php

		if ( get_post_type( $current_selection ) === 'product' ) {
			$regular_price = get_post_meta( $current_selection, '_regular_price', true );
			?>

			<label><?php esc_html_e( 'Price', 'hello-wpstream' ); ?></label>
			<input type="text" id="wpstream_channel_price" name="wpstream_channel_price"
					value="<?php echo floatval( $regular_price ); ?>">

		<?php } ?>

		<label><?php esc_html_e( 'Channel Description', 'hello-wpstream' ); ?></label>

		<?php
		$submit_description = get_post_field( 'post_content', $current_selection );

		wp_editor(
			stripslashes( $submit_description ),
			'wstream_description',
			array(
				'textarea_rows' => 6,
				'textarea_name' => 'wstream_description',
				'wpautop'       => true, // use wpautop?.
				'media_buttons' => false, // show insert/upload button(s).
				'tabindex'      => '',
				'editor_css'    => '',
				'editor_class'  => '',
				'teeny'         => false,
				'dfw'           => false,
				'tinymce'       => false,
				'quicktags'     => array( 'buttons' => 'strong,em,block,ins,ul,li,ol,close' ),
			)
		);
		?>

	</div>

	<?php
	$return = ob_get_contents();

	ob_end_clean();

	return $return;
}

/**
 * Retrieve attachment data for given attachment IDs.
 *
 * This function retrieves attachment data (metadata) for the given attachment IDs.
 *
 * @param string $attachment_ids Comma-separated list of attachment IDs.
 * @return array An array of attachment data indexed by attachment ID.
 */
function wpstream_get_attachment_data( $attachment_ids ) {
	$attachment_ids = explode( ',', $attachment_ids ); // Convert comma-separated IDs to an array.

	$attachment_data = array();

	foreach ( $attachment_ids as $attachment_id ) {
		$attachment = wp_get_attachment_metadata( $attachment_id );

		if ( $attachment ) {
			$attachment_data[ $attachment_id ] = $attachment;
		}
	}

	return $attachment_data;
}

if ( ! function_exists( 'wpstream_theme_return_image_gallery' ) ) {
	/**
	 * Return the image gallery for a post.
	 *
	 * This function returns the image gallery for a post based on the post type.
	 *
	 * @param int $post_id The ID of the post.
	 * @return array The array of image gallery for the post.
	 */
	function wpstream_theme_return_image_gallery( $post_id ) {
		$post_type      = get_post_type( $post_id );
		$gallery_images = array();

		if ( 'product' === $post_type ) {
			$gallery_images_source = get_post_meta( $post_id, '_product_image_gallery', true );
			$gallery_images        = explode( ',', $gallery_images_source );
		} else {
			if(function_exists('rwmb_meta')){
				$gallery_images = rwmb_meta( 'wpstream_theme_gallery', array(), $post_id );

				if ( is_array( $gallery_images ) ) {
					$gallery_images = array_keys( $gallery_images );
				} elseif ( ! empty( $gallery_images ) ) {
					$gallery_images = array( $gallery_images );
				} else {
					$gallery_images = array();
				}
			}
		}

		return array_filter( $gallery_images );
	}
}

if ( ! function_exists( 'wpstream_theme_build_html_gallery_dashboard' ) ) {
	/**
	 * Build HTML for the gallery in the dashboard.
	 *
	 * This function builds HTML for the gallery in the dashboard based on the provided array of image IDs.
	 *
	 * @param array $gallery_images An array of image IDs.
	 * @return string The HTML string for the gallery.
	 */
	function wpstream_theme_build_html_gallery_dashboard( $gallery_images ) {
		$return_string = '';

		if ( is_array( $gallery_images ) ) {
			foreach ( $gallery_images as $attachment_id ) {
				$preview = wp_get_attachment_image_src( $attachment_id, 'wpstream_featured_unit_cards' );

				if ( $preview && '' !== $preview[0] ) {
					$return_string .= '<div class="wpstream_uploaded_images" data-imageid="' . esc_attr( $attachment_id ) . '">';
					$return_string .= '<img src="' . esc_url( $preview[0] ) . '" alt="' . esc_html__( 'thumb', 'hello-wpstream' ) . '" /></div>';
				}
			}
		}

		return $return_string;
	}
}

if ( ! function_exists( 'wpstream_theme_return_trailer_video' ) ) {
    /**
     * Return the trailer video for a post.
     *
     * This function returns the trailer video for a post based on the post type.
     *
     * @param int $post_id The ID of the post.
     * @return string The URL of the trailer video.
     */
    function wpstream_theme_return_trailer_video( $post_id ) {
        $trailer_video_id = get_post_meta( $post_id, 'video_trailer', true );
	    $attachment_url   = wp_get_attachment_url( $trailer_video_id );

        if ( ! empty( $attachment_url ) ) {;
            return $attachment_url;
        }

        return '';
    }
}

if ( ! function_exists( 'wpstream_theme_build_html_video_trailer_dashboard' ) ) {
    /**
     * Build HTML for the video trailer in the dashboard.
     *
     * This function builds HTML for the video trailer in the dashboard based on the provided video URL.
     *
     * @param string $video_url The URL of the video.
     * @return string The HTML string for the video trailer.
     */
    function wpstream_theme_build_html_video_trailer_dashboard( $video_url ) {
        if ( ! empty( $video_url ) ) {
            return '<div class="wpstream-video-trailer" id="wpstream-video-trailer"><video height="240" controls><source src="' . esc_url( $video_url ) . '" type="video/mp4"></video></div>';
        }

        return '';
    }
}


if ( ! function_exists( 'wpstream_theme_return_preview_video' ) ) {
	/**
	 * Return the trailer video for a post.
	 *
	 * This function returns the trailer video for a post based on the post type.
	 *
	 * @param int $post_id The ID of the post.
	 * @return string The URL of the trailer video.
	 */
	function wpstream_theme_return_preview_video( $post_id ) {
		$preview_video_id = get_post_meta( $post_id, 'video_preview', true );
		$attachment_url   = wp_get_attachment_url( $preview_video_id );

		if ( ! empty( $attachment_url ) ) {;
			return $attachment_url;
		}

		return '';
	}
}

if ( ! function_exists( 'wpstream_theme_build_html_video_preview_dashboard' ) ) {
	/**
	 * Build HTML for the video preview in the dashboard.
	 *
	 * This function builds HTML for the video preview in the dashboard based on the provided video URL.
	 *
	 * @param string $video_url The URL of the video.
	 * @return string The HTML string for the video preview.
	 */
	function wpstream_theme_build_html_video_preview_dashboard( $video_url ) {
		if ( ! empty( $video_url ) ) {
			return '<div class="wpstream-video-preview" id="wpstream-video-preview"><video height="240" controls><source src="' . esc_url( $video_url ) . '" type="video/mp4"></video></div>';
		}

		return '';
	}
}

if ( ! function_exists( 'wpstream_theme_return_image_upload_markup' ) ) {
	/**
	 * Return the markup for image upload.
	 *
	 * This function generates and returns the markup for image upload based on the provided post ID.
	 *
	 * @param int $user_id The ID of the user.
	 * @param int $post_id The ID of the post.
	 * @return string The HTML markup for image upload.
	 */
	function wpstream_theme_return_image_upload_markup( $user_id, $post_id ) {
		$post_type      = get_post_type( $post_id );
		$gallery_images = '';

		if ( 'product' === $post_type ) {
			$gallery_images_source = get_post_meta( $post_id, '_product_image_gallery', true );
			$gallery_images        = explode( ',', $gallery_images_source );
		} else {
			if(function_exists('rwmb_meta')){
				$gallery_images = rwmb_meta( 'wpstream_theme_gallery', array(), $post_id );

				if ( is_array( $gallery_images ) ) {
					$gallery_images = array_keys( $gallery_images );
				}
			}
		}

		$gallery_images = wpstream_theme_return_image_gallery( $post_id );

		$thumbid = get_post_thumbnail_id( $post_id );
		$images  = '';

		if ( is_array( $gallery_images ) ) {
			foreach ( $gallery_images as $attachment_id ) {

				$preview = wp_get_attachment_image_src( $attachment_id, 'wpstream_featured_unit_cards' );

				if ( $preview && $preview[0] != '' ) {
					$images .= '<div class="wpstream_uploaded_images" data-imageid="' . esc_attr( $attachment_id ) . '">'
						. '<img src="' . esc_url( $preview[0] ) . '" alt="' . esc_html__( 'thumb', 'hello-wpstream' ) . '" />'
						. '<i class="far fa-trash-alt wpstream_delete_image"></i>';

					$images .= '</div>';
				}
			}
		}

		$gallery_images_string = '';
		if ( is_array( $gallery_images ) ) {
			$gallery_images_string = implode( ',', $gallery_images );
		}

		$return_string = '';
		ob_start();
		?>

		<div id="upload-container" class="upload-container">
			<div id="aaiu-upload-container upload-container__body">
				<h3><?php echo esc_html__( 'Image list', 'hello-wpstream' ); ?></h3>
				<div id="aaiu-upload-imagelist">
					<ul id="aaiu-ul-list" class="aaiu-upload-list"></ul>
				</div>

				<div id="wpstream_imagelist">
					<?php
					$ajax_nonce = wp_create_nonce( 'wpstream_image_upload' );
					print '<input type="hidden" id="wpstream_image_upload" value="' . esc_html( $ajax_nonce ) . '" />    ';
					if ( '' !== $images ) {
						print trim( $images ); //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					}
					?>
				</div>

				<div class="upload-container__actions-wrap upload-container__actions-wrap--row">
					<div id="drag-and-drop" class="rh_drag_and_drop_wrapper ">
						<div id="aaiu-uploader" class="wpstream_theme_button_dashboard">
							<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
								<path fill-rule="evenodd" clip-rule="evenodd" d="M10.7379 16.6273C9.96427 16.6273 9.31895 16.036 9.2514 15.2654C9.11015 13.6541 9.07441 12.0356 9.14427 10.4203C9.05994 10.4147 8.97563 10.4088 8.89133 10.4026L7.40178 10.2941C6.44973 10.2247 5.91752 9.16309 6.43151 8.35871C7.5277 6.6432 9.53693 4.72314 11.1904 3.53541C11.6742 3.18786 12.3258 3.18786 12.8097 3.53541C14.4631 4.72314 16.4723 6.64319 17.5685 8.35871C18.0825 9.16309 17.5503 10.2247 16.5983 10.2941L15.1087 10.4026C15.0244 10.4088 14.9401 10.4147 14.8558 10.4203C14.9256 12.0356 14.8899 13.6541 14.7486 15.2654C14.6811 16.036 14.0358 16.6273 13.2622 16.6273H10.7379ZM10.6815 9.76253C10.5678 11.5498 10.589 13.3431 10.745 15.1273H13.255C13.411 13.3431 13.4323 11.5498 13.3186 9.76253C13.3058 9.56216 13.3739 9.36505 13.5077 9.21531C13.6414 9.06556 13.8296 8.9757 14.0301 8.96582C14.3535 8.94989 14.6767 8.93015 14.9997 8.90661L16.0815 8.82775C15.1219 7.41445 13.9204 6.1802 12.5313 5.18235L12 4.80071L11.4687 5.18235C10.0796 6.1802 8.87813 7.41446 7.91858 8.82775L9.00038 8.90661C9.32337 8.93015 9.64656 8.94989 9.9699 8.96582C10.1704 8.9757 10.3586 9.06556 10.4924 9.21531C10.6261 9.36505 10.6942 9.56216 10.6815 9.76253Z" fill="#0F0F0F"/>
								<path d="M5.75 17C5.75 16.5858 5.41421 16.25 5 16.25C4.58579 16.25 4.25 16.5858 4.25 17V19C4.25 19.9665 5.0335 20.75 6 20.75H18C18.9665 20.75 19.75 19.9665 19.75 19V17C19.75 16.5858 19.4142 16.25 19 16.25C18.5858 16.25 18.25 16.5858 18.25 17V19C18.25 19.1381 18.1381 19.25 18 19.25H6C5.86193 19.25 5.75 19.1381 5.75 19V17Z" fill="#0F0F0F"/>
							</svg>

							<?php esc_html_e( 'Upload More', 'hello-wpstream' ); ?>
						</div>
					</div>

					<input type="hidden" name="attachid" id="attachid" value="<?php print esc_html( $gallery_images_string ); ?>">
					<input type="hidden" name="attachthumb" id="attachthumb" value="<?php print esc_html( $thumbid ); ?>">
					<p class="full_form full_form_image">
						<?php
						esc_html_e(
							"It's recommended to use a picture that's at least 1280 x 720 pixels and 4MB or less. 
                        Use a PNG or GIF (no animations) file.",
							'hello-wpstream'
						);
						?>
					</p>
				</div>
			</div>
		</div>
		<?php
		$return_string .= ob_get_contents();
		ob_end_clean();

		return $return_string;
	}
}

if ( ! function_exists( 'wpstream_theme_return_taxonomies_on_edit' ) ) {
	/**
	 * Return the taxonomies for editing.
	 *
	 * This function generates and returns the taxonomies for editing based on the provided post ID.
	 *
	 * @param int $user_id The ID of the user.
	 * @param int $post_id The ID of the post.
	 * @return string The HTML markup for taxonomies editing.
	 */
	function wpstream_theme_return_taxonomies_on_edit( $user_id, $post_id ) {
		$taxonomy_array = wpstream_return_all_categories_array();
		$post_type      = get_post_type( $post_id );
		$taxonomy_array = get_object_taxonomies( $post_type, 'objects' );

		unset( $taxonomy_array['product_type'] );
		unset( $taxonomy_array['product_visibility'] );
		unset( $taxonomy_array['product_shipping_class'] );

		$return_string = '';

		foreach ( $taxonomy_array as $taxonomy_slug => $taxonomy ) {
			$return_string .= '<div class="wpstream_edit_channel_taxonomy_wrapper wpstream-modal-body-row-full" data-taxonomy="' . esc_html( $taxonomy_slug ) . '" >';
			$return_string .= '<label>' . esc_html__( 'Selection for', 'hello-wpstream' ) . ' ' . $taxonomy->label . '</label>';
			$return_string .= wpstream_build_taxonomy_select( $taxonomy_slug, $post_id );
			$return_string .= '</div>';
		}

		return $return_string;
	}
}

/**
 * Build a taxonomy select field.
 *
 * This function generates and returns HTML markup for a taxonomy select field based on the provided taxonomy and post ID.
 *
 * @param string $taxonomy The taxonomy to retrieve terms for.
 * @param int    $post_id The ID of the post.
 * @return string The HTML markup for the taxonomy select field.
 */
function wpstream_build_taxonomy_select( $taxonomy, $post_id ) {
	$terms = get_terms(
		array(
			'taxonomy'   => $taxonomy,
			'hide_empty' => false,
		)
	);

	$return = ' <div class="wpstream-select2">';

	if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
		$return .= '<select id="wpstream_edit_' . esc_attr( $taxonomy ) . '" class="wpstream_taxonomies form-select" data-tax="' . esc_attr( $taxonomy ) . '"  data-placeholder="' . esc_html__( 'Select the terms', 'hello-wpstream' ) . '" multiple >';

		foreach ( $terms as $term ) {
			$selected = has_term( $term->term_id, $taxonomy, $post_id ) ? 'selected' : '';
			$return  .= '<option value="' . $term->term_id . '"  ' . $selected . '>' . $term->name . '</option>';
		}

		$return .= '</select>';
	}

	$return .= '</div>';

	return $return;
}

if ( ! function_exists( 'wpstream_users_allowed_to_stream' ) ) {
	/**
	 * Users allowed to stream
	 */
	function wpstream_users_allowed_to_stream() {
		return true;
	}
}

if ( ! function_exists( 'wpstream_return_user_can_create_paid' ) ) {
	/**
	 * Return user can create paid
	 */
	function wpstream_return_user_can_create_paid() {
		$wpstream_user_can_create_paid = get_theme_mod('wpstream_user_can_create_paid', false);
	
		if ($wpstream_user_can_create_paid) {
			return true;
		} else {
			return false;
		}
	
	}
}

if ( ! function_exists( 'wpstream_return_max_channels_per_user' ) ) {
	/**
	 * Return max channels per user
	 */
	function wpstream_return_max_channels_per_user() {
		$value = intval( get_theme_mod( 'wpstream_return_max_channels_per_user' ) );

		if ( 0 === $value ) {
			return 999;
		}

		return $value;
	}
}

if ( ! function_exists( 'wpstream_theme_localize_upload_script_images' ) ) {
	/**
	 * Localize the upload script for images.
	 *
	 * @param string $button_upload The ID of the upload button.
	 */
	function wpstream_theme_localize_upload_script_images($button_upload)
	{
		$plup_url = add_query_arg(
			array(
				'action' => 'wpstream_me_upload',
				'nonce' => wp_create_nonce('aaiu_allow'),
			),
			esc_url(admin_url('admin-ajax.php'))
		);

		$max_file_size = 100 * 1000 * 1000;

		$plupload_values = array(
			'runtimes' => 'html5,flash,html4',
			'max_file_size' => $max_file_size . 'b',
			'url' => $plup_url,
			'file_data_name' => 'aaiu_upload_file',
			'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
			'filters' => array(
				array(
					'title' => esc_html__('Allowed Files', 'hello-wpstream'),
					'extensions' => 'jpeg,jpg,gif,png,pdf,webp,mp4,mov',
				),
			),
			'multipart' => true,
			'urlstream_upload' => true,
			'multipart_params' => array('button_id' => $button_upload),
		);

		$tmp_plupload_values = array(
			'browse_button' => $button_upload,
			'container' => 'aaiu-upload-container',
		);

		$plupload_values = wp_parse_args($plupload_values, $tmp_plupload_values);
		$uploader_js = 'ajax-upload';
		$plupload_values['drop_element'] = 'drag-and-drop';
		$max_images = 20;

		wp_localize_script(
			'ajax-upload',
			'ajax_vars',
			array(
				'ajaxurl' => esc_url(admin_url('admin-ajax.php')),
				'nonce' => wp_create_nonce('aaiu_upload'),
				'remove' => wp_create_nonce('aaiu_remove'),
				'number' => 1,
				'upload_enabled' => true,
				'warning' => __('Image needs to be at least 500px height  x 500px wide!', 'hello-wpstream'),
				'max_images' => $max_images,
				'warning_max' => __('You cannot upload more than', 'hello-wpstream') . ' ' . $max_images . ' ' . __('images', 'hello-wpstream'),
				'path' => trailingslashit(get_template_directory_uri()),
				'confirmMsg' => esc_html__('Are you sure you want to delete this?', 'hello-wpstream'),
				'plupload' => $plupload_values,
			)
		);
	}
}

/**
 * Get the content of the specified post.
 *
 * @param int $current_selection The ID of the post.
 * @return string The content of the post.
 */
function wpstream_get_content_edit( $current_selection ) {
	$content = '';
	$query   = new WP_Query(
		array(
			'post_type' => 'any',
			'p'         => $current_selection,
		)
	);

	if ( $query->have_posts() ) {
		while ( $query->have_posts() ) {
			$query->the_post();
			the_content();
		}
		wp_reset_postdata();
	}

	ob_start();
	$content = ob_get_contents();
	ob_end_clean();
	return $content;
}

if ( ! function_exists( 'wpstream_theme_purchased_video_list' ) ) {
	/**
	 * Display the list of purchased video items.
	 */
	function wpstream_theme_purchased_video_list() {
		$user_id = get_current_user_id();
		$paged   = ( get_query_var( 'video-list' ) );

		if ( '' !== $paged ) {
			$paged = intval( str_replace( 'page/', '', $paged ) );
		} else {
			$paged = 1;
		}

		$page     = 1;
		$per_page = get_option( 'posts_per_page' );
		$result   = wpstream_dashboard_get_products_by_user( $user_id, 'video_on_demand', $paged, $per_page );

		print '<div class="wpstream_dashboard_items_list_wrapper">';

		foreach ( $result['products'] as $product_array ) {
			include get_template_directory() . '/template-parts/dashboard-templates/items-purchased-list.php';
		}

		print '</div>';

		wpstream_theme_pagination( $result['max_num_pages'], $range = 2, $paged );
	}
}

if ( ! function_exists( 'wpstream_theme_purchased_event_list' ) ) {
	/**
	 * Theme purchased event list
	 */
	function wpstream_theme_purchased_event_list() {
		$user_id = get_current_user_id();
		$paged   = ( get_query_var( 'event-list' ) );

		if ( '' !== $paged ) {
			$paged = intval( str_replace( 'page/', '', $paged ) );
		} else {
			$paged = 1;
		}

		$per_page = get_option( 'posts_per_page' );
		$result   = wpstream_dashboard_get_products_by_user( $user_id, 'live_stream', $paged, $per_page );

		print '<div class="wpstream_dashboard_items_list_wrapper">';

		foreach ( $result['products'] as $product_array ) {
			include get_template_directory() . '/template-parts/dashboard-templates/items-purchased-list.php';
		}

		print '</div>';

		wpstream_theme_pagination( $result['max_num_pages'], $range = 2, $paged );
	}
}

if ( ! function_exists( 'wpstream_dashboard_get_products_by_user' ) ) {
	/**
	 * Retrieve products purchased by a specific user.
	 *
	 * Retrieves all products of a specific type (default: 'video_on_demand') purchased by a user.
	 *
	 * @param int    $user_id      The ID of the user.
	 * @param string $product_type The type of products to retrieve. Default is 'video_on_demand'.
	 * @param int    $page         Optional. The page number of the results. Default is 1.
	 * @param int    $per_page     Optional. The number of products to retrieve per page. Default is 10.
	 * @return array An array containing paginated products, total number of products, and maximum number of pages.
	 */
	function wpstream_dashboard_get_products_by_user( $user_id, $product_type = 'video_on_demand', $page = 1, $per_page = 10 ) {
		$all_products = array();

		// Get all customer orders.
		$customer_orders = wc_get_orders(
			array(
				'customer_id' => $user_id,
				'status'      => 'completed',
				'limit' 	=> -1
			)
		);

		// Loop through each customer order.
		foreach ( $customer_orders as $customer_order ) {
			$order_items    = $customer_order->get_items();
			$order          = wc_get_order( $customer_order );
			$order_id       = $order->get_id();
			$order_date     = $order->get_date_created();
			$formatted_date = wc_format_datetime( $order_date );

			foreach ( $order_items as $item ) {
				$product = $item->get_product();

				if ( $product && $product_type === $product->get_type() ) {
					$total_paid = $item->get_total();
					$temp_array = array(
						'price'      => $total_paid,
						'order_id'   => $order_id,
						'order_date' => $formatted_date,
						'product'    => $product,
					);

					$all_products[$product->get_id()] = $temp_array;
				}
			}
		}

		if(intval($per_page) === -1){
			return $all_products;
		}

		// Calculate offset for pagination.
		$offset             = ( $page - 1 ) * $per_page;
		$paginated_products = array_slice( $all_products, $offset, $per_page );

		return array(
			'products'      => $paginated_products,
			'total'         => count( $all_products ),
			'max_num_pages' => ceil( count( $all_products ) / $per_page ),
		);
	}
}

/**
 * Retrieve the URL to view a specific order in the My Account area.
 *
 * @param int $order_id The ID of the order.
 * @return string|WP_Error The URL to view the order or an error message.
 */
function wpstream_get_my_account_order_url( $order_id ) {
	$order = wc_get_order( $order_id );

	if ( ! $order ) {
		return 'Order not found';
	}

	$user_id = $order->get_user_id();

	// Ensure the user is logged in and trying to view their own order.
	if ( get_current_user_id() !== $user_id ) {
		return 'You do not have permission to view this order';
	}

	$view_order_url = wc_get_endpoint_url( 'view-order', $order_id, wc_get_page_permalink( 'myaccount' ) );

	return $view_order_url;
}
?>
