<?php

namespace HulkPlugins\Woo\AccountPages\Admin\Services;

use HulkPlugins\Woo\AccountPages\Core\SingletonTrait;
use HulkPlugins\Woo\AccountPages\Frontend\Services\WooMyAccountService;
use const HulkPlugins\Woo\AccountPages\VERSION;

defined( 'ABSPATH' ) || exit;

class AccountPagesService {

    use SingletonTrait;

	public string $post_type = 'hulk_woo_ap_page';

	// Get my-account belong permalink
	public function get_permalink( $post ): string {
		$accountService = WooMyAccountService::getInstance();
		$slug = get_post_field( 'post_name', $accountService->get_my_account_page_id() );
		$title            = _draft_or_post_title();
		$post_link = str_replace(
			'/' . $post->post_type . '/',
			'/' . $slug . '/',
			get_permalink( $post->ID )
		);
		return sprintf(
			/** @lang text */            '<a href="%s" rel="bookmark" aria-label="%s">%s</a>',
			$post_link,
			/* translators: %s: Post title. */
			esc_attr( sprintf( __( 'View &#8220;%s&#8221;', 'hulk-account-pages-for-woocommerce' ), $title ) ),
			__( 'View', 'hulk-account-pages-for-woocommerce' )
		);
	}

	// Delete all CPT posts
	public function delete_all_posts( $force_delete = false ): void {
		// Get all posts (including drafts, private, etc.)
		$posts = get_posts(
			[
				'post_type'     => $this->post_type,
				'post_status'   => 'any',
				'numberposts'   => -1,
				'fields'        => 'ids',
				'no_found_rows' => true,
			]
		);

		foreach ( $posts as $post_id ) {
			wp_delete_post( $post_id, $force_delete );
		}
	}

	/**
	 * Add inline style
	 */
	public function addInlineStyle( $data ): ?bool {
		static $style = null;

		if ( $style !== null ) {
			return $style;
		}

		wp_register_style( 'hulk_woo_ap_inline_style', false, [], VERSION );
		wp_enqueue_style( 'hulk_woo_ap_inline_style' );
		$style = wp_add_inline_style( 'hulk_woo_ap_inline_style', esc_attr( $data ) );
		return $style;
	}
}
