<?php

namespace HulkPlugins\Woo\AccountPages\Frontend\Controllers;

use HulkPlugins\Woo\AccountPages\Core\BaseController;
use HulkPlugins\Woo\AccountPages\Core\SingletonTrait;
use HulkPlugins\Woo\AccountPages\Frontend\Services\WooMyAccountService;
use WP_Post;
use const HulkPlugins\Woo\AccountPages\PLUGIN_DIR_PATH;

defined( 'ABSPATH' ) || exit;

class WooMyAccountController extends BaseController {

	use SingletonTrait;

	protected WooMyAccountService $service;

	public function init_hooks(): void {
		$this->service = WooMyAccountService::getInstance();

        add_filter( 'woocommerce_account_menu_items', [ $this, 'account_menu_items' ] );
        add_filter( 'woocommerce_account_menu_item_classes', [ $this, 'account_menu_item_classes' ], 10, 2 );
        add_filter( 'query_vars', [ $this, 'register_query_var' ] );
		add_action( "woocommerce_account_{$this->service->query_var}_endpoint", [ $this, 'endpoint_content' ] );
		add_filter( 'the_title', [ $this, 'endpoint_title' ], 10, 2 );
		add_filter( 'woocommerce_get_breadcrumb', [ $this, 'get_breadcrumb' ] );
		add_filter( 'wp_robots', [ $this, 'prevent_indexing_endpoints' ] );
		add_action( 'init', [ $this, 'add_my_account_endpoints' ] );
	}

	// Account menu items.
	public function account_menu_items( $items ) {
		$subpages = $this->service->get_account_subpages();
		$logout_item = $items['customer-logout'] ?? false;

		/** @var WP_Post $subpage */
		foreach ( $subpages as $subpage ) {
			$postName = esc_attr( $subpage->post_name );

			if ( ! $this->service->is_visible( $postName ) ) {
				continue;
			}

			if ( ! $this->service->is_page_allowed_for_user_role( $subpage->ID ) ) {
				continue;
			}

			$items[ $postName ] = esc_html( $subpage->post_title );
		}

		if ( $logout_item ) {
			unset( $items['customer-logout'] );
			$items['customer-logout'] = $logout_item;
		}

		return $items;
	}

	// Account menu item classes.
	public function account_menu_item_classes( $classes, $endpoint ) {
		$endpoint_id = $this->service->is_endpoint();

		if ( ! $endpoint_id ) {
			return $classes;
		}

		$endpoint_slug = get_post_field( 'post_name', $endpoint_id );

		if ( $endpoint_slug !== $endpoint ) {
			return $classes;
		}

		$classes[] = 'is-active';

		return $classes;
	}

	// Add endpoint.
	public function add_my_account_endpoints(): void {
		$subpages = $this->service->get_account_subpages();

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

		$account_page_id   = wc_get_page_id( 'myaccount' );
		$account_page_path = get_page_uri( $account_page_id );

		/** @var WP_Post $subpage */
		foreach ( $subpages as $subpage ) {
			$uri      = sprintf( '%s/%s', $account_page_path, esc_attr( $subpage->post_name ) );
			$redirect = sprintf(
                'index.php?page_id=%d&%s=%d',
				$account_page_id,
                $this->service->query_var,
                $subpage->ID
			);

			add_rewrite_rule(
				'^' . preg_quote( $uri, '/' ) . '/?$',
				$redirect,
				'top'
			);
		}
	}

	// Register query var.
	public function register_query_var( $vars ) {
		$vars[] = $this->service->query_var;
		return $vars;
	}

	// Output endpoint content.
	public function endpoint_content(): void {
		$post = $this->service->get_current_endpoint_page_object();

		if ( empty( $post->ID ) ) {
			require PLUGIN_DIR_PATH . '/templates/access-denied-markup.php';
			return;
		}

		if ( ! $this->service->is_page_allowed_for_user_role( $post->ID ) ) {
			require PLUGIN_DIR_PATH . '/templates/access-denied-markup.php';
			return;
		}

		$content = apply_filters( 'the_content', $post->post_content );

		echo wp_kses_post( $content );
	}

	// Change endpoint title.
	public function endpoint_title( $title, $post_id ): string {
		if ( ! $post_id ) {
			global $post;
			$post_id = $post->ID;
		}
		if ( is_account_page() && is_main_query() && in_the_loop() && is_page() ) {
			$account_page_id = $this->service->get_my_account_page_id();
			if ( $post_id === $account_page_id ) {
				$endpoint = $this->service->get_current_endpoint_page_object();
				if ( $endpoint ) {
					return esc_html( $endpoint->post_title );
				}
			}
		}
		return esc_html( $title );
	}

	// Prevent indexing custom endpoints.
	public function prevent_indexing_endpoints( $robots ): array {
		if ( $this->service->is_endpoint() ) {
			// Return a noindex, follow directive
			return wp_robots_no_robots( $robots );
		}
		return $robots;
	}

	// Force no-cache headers for custom account pages
	public function nocache_headers(): void {
		if ( ! $this->service->is_endpoint() ) {
			return;
		}
		nocache_headers();
	}

	// Add page to breadcrumbs.
	public function get_breadcrumb( $crumbs ) {
		$post = $this->service->get_current_endpoint_page_object();

		if ( empty( $post->ID ) ) {
			return $crumbs;
		}

		$crumbs[] = [ esc_html( $post->post_title ), '' ];

		return $crumbs;
	}
}
