<?php

namespace HulkPlugins\Woo\AccountPages\Frontend\Services;

use HulkPlugins\Woo\AccountPages\Admin\Services\AccountPageMetaBoxService;
use HulkPlugins\Woo\AccountPages\Admin\Services\AccountPagesService;
use HulkPlugins\Woo\AccountPages\Core\SingletonTrait;
use WP_Post;
use WP_Query;
use function HulkPlugins\Woo\AccountPages\hulk_woo_ap_fs;

defined( 'ABSPATH' ) || exit;

class WooMyAccountService {

	use SingletonTrait;

	public string $query_var = 'hulk_woo_ap_endpoint';

	/**
	 * Get subpages of My Account.
	 */
	public function get_account_subpages(): array {
		static $subpages = [];

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

		$pageService = AccountPagesService::getInstance();

		$args = [
			'post_type'      => $pageService->post_type,
			'posts_per_page' => - 1,
			'post_parent'    => 0,
			'orderby'        => 'menu_order',
			'order'          => 'ASC',
			'post_status'    => 'publish',
		];

		$query = new WP_Query( $args );

		if ( ! $query->have_posts() ) {
			return $subpages;
		}

		$subpages = $query->posts;

		return $subpages;
	}

	/**
	 * Get my account page ID.
	 */
	public function get_my_account_page_id(): ?int {
		static $page_id = null;

		if ( is_null( $page_id ) ) {
			$page_id = (int) get_option( 'woocommerce_myaccount_page_id' );
		}

		return $page_id;
	}

	/**
	 * Is the page visible for the current user?
	 */
	public function is_visible( $slug ): bool {
		$hidden = apply_filters( 'hulk_woo_ap_hidden_pages', [] );

		if ( empty( $hidden ) ) {
			return true;
		}

		return ! in_array( $slug, $hidden, true );
	}

	/**
	 * Checks if the given page is allowed for the logged-in user.
	 */
	public function is_page_allowed_for_user_role( $page_id ) {
		$user          = wp_get_current_user();
		$metaService   = AccountPageMetaBoxService::getInstance();
		$allowed_roles = $metaService->get_allowed_user_roles( $page_id );
		$intersect     = array_intersect( $allowed_roles, $user->roles );
		$allowed       = ! empty( $intersect );

		// Allowed user role always if not using premium code
        if ( ! hulk_woo_ap_fs()->can_use_premium_code() ) {
            return true;
        }

		return apply_filters(
			'hulk_woo_ap_page_allowed_for_user',
			$allowed,
            $page_id,
            $user,
            $allowed_roles
		);
	}

	/**
	 * Get current endpoint page object.
	 */
	public function get_current_endpoint_page_object() {
		$endpoint_id = $this->is_endpoint();

		if ( ! $endpoint_id ) {
			return false;
		}

		$endpoint_post = get_post( $endpoint_id );

		if (
			! $endpoint_post instanceof WP_Post ||
			$endpoint_post->post_status !== 'publish'
		) {
			return false;
		}

		return $endpoint_post;
	}

	/**
	 * Is endpoint.
	 */
	public function is_endpoint() {
		$endpoint_id = get_query_var( $this->query_var );

		if ( ! $endpoint_id ) {
			return false;
		}

		return $endpoint_id;
	}
}
