<?php
/**
 * Help & FAQ admin page — the plugin's self-serve support surface. Ships in
 * BOTH builds: free users are pointed to the wp.org community forum, licensed
 * Pro users to the Freemius Contact page. Pure PHP (details/summary accordion),
 * no React needed.
 *
 * @package ErenLabs\SmartCategories
 */

defined( 'ABSPATH' ) || exit;

/**
 * Help & FAQ page.
 */
class SCWC_Help {

	const SLUG = 'scwc-help';

	/**
	 * Hook everything up.
	 */
	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'register_menu' ), 11 );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'assets' ) );
	}

	/**
	 * Register the submenu (after Overview/Tree, before the Upgrade entry that
	 * SCWC_Upgrade appends at a later priority).
	 */
	public static function register_menu() {
		add_submenu_page(
			'scwc-overview',
			__( 'Help & FAQ', 'smart-categories-for-woocommerce' ),
			__( 'Help & FAQ', 'smart-categories-for-woocommerce' ),
			'manage_woocommerce',
			self::SLUG,
			array( __CLASS__, 'render' )
		);
	}

	/**
	 * Page stylesheet.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public static function assets( $hook ) {
		if ( false === strpos( (string) $hook, self::SLUG ) ) {
			return;
		}
		wp_enqueue_style( 'scwc-help', SCWC_URL . 'assets/help.css', array(), SCWC_VERSION );
	}

	/**
	 * The FAQ content: sections of question/answer pairs. Answers may carry
	 * limited inline HTML (links, code) — escaped through wp_kses on output.
	 *
	 * @return array<int,array{title:string,items:array<int,array{q:string,a:string}>}>
	 */
	private static function sections() {
		$overview_url = esc_url( admin_url( 'admin.php?page=scwc-overview' ) );
		$upgrade_url  = esc_url( function_exists( 'scwc_upgrade_url' ) ? scwc_upgrade_url() : admin_url( 'admin.php?page=scwc-overview' ) );
		$forum_url    = 'https://wordpress.org/support/plugin/smart-categories-for-woocommerce/';

		$sections = array();

		$sections[] = array(
			'title' => __( 'Getting started', 'smart-categories-for-woocommerce' ),
			'items' => array(
				array(
					'q' => __( 'What is a smart category?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'A smart category is a product category that defines itself with rules instead of a hand-picked list. You describe the products — for example “on sale AND under 50” — and every matching product is added automatically. When a product stops matching, it leaves on its own. It is the WooCommerce equivalent of Shopify’s Smart Collections.', 'smart-categories-for-woocommerce' ),
				),
				array(
					'q' => __( 'How do I create my first smart category?', 'smart-categories-for-woocommerce' ),
					'a' => sprintf(
						/* translators: %s: overview page URL */
						__( 'Open <a href="%s">Overview</a> and click “New Smart Category”. Pick a ready-made template or build your own rules; the live preview shows exactly which products match while you compose. “Create and populate” creates the category and assigns the matching products immediately — you land on a result screen with the live count and a link to view it on your store.', 'smart-categories-for-woocommerce' ),
						$overview_url
					),
				),
				array(
					'q' => __( 'Which ready-made templates are included?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'New Arrivals, Best Sellers, On Sale, Big Discount, Back in Stock, Low Stock, Featured, Premium, Out of Stock and Missing Image (a catalog-maintenance helper). Each is a starting point — after applying one you can adjust every rule before creating.', 'smart-categories-for-woocommerce' ),
				),
				array(
					'q' => __( 'Can I turn an existing category into a smart category?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'Yes. Edit any product category (Products → Categories) and you will find the Smart Category Rules panel on its edit screen. Add rules and save — products you had assigned by hand stay untouched, and matching products are added alongside them.', 'smart-categories-for-woocommerce' ),
				),
			),
		);

		$sections[] = array(
			'title' => __( 'Rules & matching', 'smart-categories-for-woocommerce' ),
			'items' => array(
				array(
					'q' => __( 'Which fields can I match on?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'More than 35 fields: title, SKU, description, price, sale price, discount percentage, stock status and quantity, global attributes (colour, size…), tags, brand, product type, shipping class, rating, review count, all-time sales, created/modified dates, featured flag, image presence, dimensions, weight and custom fields (meta). Attribute fields appear automatically for every global attribute your store defines.', 'smart-categories-for-woocommerce' ),
				),
				array(
					'q' => __( 'How does the AND / OR / NOT logic work?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'Rules live in groups. A group either requires ALL of its conditions (AND) or ANY of them (OR), and any group can be negated (NOT) or nested inside another group without depth limits. Example: (Colour is Black OR Red) AND price &lt; 50 AND NOT (tag is Clearance).', 'smart-categories-for-woocommerce' ),
				),
				array(
					'q' => __( 'Will the plugin remove products I assigned by hand?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'Never. The plugin keeps its own ledger of the memberships it created and only ever removes those. Anything you assigned manually — before or after adding rules — is treated as yours and left alone.', 'smart-categories-for-woocommerce' ),
				),
				array(
					'q' => __( 'When do the rules run?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'Automatically: whenever a product is saved and when its price or stock changes, plus a daily background sweep that catches anything indirect (e.g. a sale schedule starting at midnight). Manually: every category card has a “Refresh now” button — useful right after a bulk import.', 'smart-categories-for-woocommerce' ),
				),
				array(
					'q' => __( 'Why is a product not matching my rules?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'The usual suspects: the group requires ALL conditions while you meant ANY; the product is not published (only published products are evaluated); or the value differs subtly (e.g. attribute value vs. tag). Open the category’s edit screen and use the product check field under the preview — it explains condition by condition why a specific product matches or fails.', 'smart-categories-for-woocommerce' ),
				),
			),
		);

		$sections[] = array(
			'title' => __( 'Performance', 'smart-categories-for-woocommerce' ),
			'items' => array(
				array(
					'q' => __( 'Does it slow down my storefront?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'No. Shoppers read plain WordPress category relationships — exactly as if you had assigned every product by hand. All matching happens in the admin and in background jobs; nothing runs on your product or category pages.', 'smart-categories-for-woocommerce' ),
				),
				array(
					'q' => __( 'How does it behave on large catalogs?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'Small and medium stores are populated instantly when you create a category. Very large catalogs are processed in queued background batches (Action Scheduler) so nothing times out — the result screen tells you when population continues in the background. Developers can tune the threshold with the scwc_sync_threshold filter.', 'smart-categories-for-woocommerce' ),
				),
			),
		);

		$sections[] = array(
			'title' => __( 'Storefront', 'smart-categories-for-woocommerce' ),
			'items' => array(
				array(
					'q' => __( 'Can I control the product order on a smart category page?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'Yes — per category. On the category edit screen choose the storefront order (best-selling, newest, price, rating…) and what happens to out-of-stock products: keep them in place, push them to the end, or hide them entirely. This only affects display order, never membership.', 'smart-categories-for-woocommerce' ),
				),
				array(
					'q' => __( 'How do I show a smart category’s products elsewhere?', 'smart-categories-for-woocommerce' ),
					'a' => __( 'Use the “Smart Category Products” block in the editor, or the [scwc_products] shortcode in classic content. Both take the category, a product limit and an order — handy for landing pages and campaign posts.', 'smart-categories-for-woocommerce' ),
				),
			),
		);

		// Pro usage questions ship only in the pro build; the free build instead
		// gets a single pointer question to the Upgrade page (the one allowed
		// upsell surface) — added below, outside this array.
		$pro_items = array();

		if ( $pro_items ) {
			$sections[] = array(
				'title' => __( 'Pro features', 'smart-categories-for-woocommerce' ),
				'items' => $pro_items,
			);
		} elseif ( function_exists( 'scwc_is_pro' ) && ! scwc_is_pro() ) {
			$sections[] = array(
				'title' => __( 'Pro features', 'smart-categories-for-woocommerce' ),
				'items' => array(
					array(
						'q' => __( 'What is the difference between Free and Pro?', 'smart-categories-for-woocommerce' ),
						'a' => sprintf(
							/* translators: %s: upgrade page URL */
							__( 'The complete nested rule engine is free, without limits. Pro adds the automatic subcategory generator (one smart child per attribute value or combination), the Category Tree page and time-window sales fields. See the full comparison on the <a href="%s">Upgrade page</a>.', 'smart-categories-for-woocommerce' ),
							$upgrade_url
						),
					),
				),
			);
		}

		$support_items = array(
			array(
				'q' => __( 'A category looks empty or its count seems stale — what should I check?', 'smart-categories-for-woocommerce' ),
				'a' => __( 'First click “Refresh now” on the category card — especially after a bulk import. Then verify the rules with the live preview (an ALL group with contradictory conditions matches nothing) and remember only published products are evaluated. Counts update as background jobs finish; on very quiet sites they run on the next visit.', 'smart-categories-for-woocommerce' ),
			),
			array(
				'q' => __( 'What happens to my categories if I deactivate or delete the plugin?', 'smart-categories-for-woocommerce' ),
				'a' => __( 'Deactivating pauses all automation — nothing is added or removed. Deleting the plugin removes its own data (rules, settings, its membership ledger) but never your categories or product assignments: every category simply becomes an ordinary WooCommerce category with its current products.', 'smart-categories-for-woocommerce' ),
			),
			array(
				'q' => __( 'Does the plugin send any data to external services?', 'smart-categories-for-woocommerce' ),
				'a' => __( 'No telemetry. The only optional connection is Freemius, which powers licensing and updates for the paid version — and only if you explicitly opt in. If you skip the opt-in, nothing is ever transmitted.', 'smart-categories-for-woocommerce' ),
			),
			array(
				'q' => __( 'Where do I get support or report a bug?', 'smart-categories-for-woocommerce' ),
				'a' => sprintf(
					/* translators: %s: wordpress.org support forum URL */
					__( 'The community forum on <a href="%s" target="_blank" rel="noopener noreferrer">wordpress.org</a> is the fastest route for the free version — we watch it actively. Please include your WordPress/WooCommerce versions and, if possible, the rule set that misbehaves.', 'smart-categories-for-woocommerce' ),
					esc_url( $forum_url )
				),
			),
		);

		$sections[] = array(
			'title' => __( 'Troubleshooting, data & support', 'smart-categories-for-woocommerce' ),
			'items' => $support_items,
		);

		return $sections;
	}

	/**
	 * Render the page.
	 */
	public static function render() {
		$allowed = array(
			'a'    => array(
				'href'   => true,
				'target' => true,
				'rel'    => true,
			),
			'code' => array(),
			'b'    => array(),
			'em'   => array(),
		);
		?>
		<div class="wrap scwc-help-wrap">
			<h1 class="scwc-help-title"><?php esc_html_e( 'Help & FAQ', 'smart-categories-for-woocommerce' ); ?></h1>
			<p class="scwc-help-sub">
				<?php esc_html_e( 'Everything about smart categories in one place — how matching works, performance, the storefront and troubleshooting.', 'smart-categories-for-woocommerce' ); ?>
			</p>

			<?php foreach ( self::sections() as $section ) : ?>
				<h2 class="scwc-help-section"><?php echo esc_html( $section['title'] ); ?></h2>
				<div class="scwc-help-group">
					<?php foreach ( $section['items'] as $item ) : ?>
						<details class="scwc-help-item">
							<summary>
								<span class="scwc-help-q"><?php echo esc_html( $item['q'] ); ?></span>
								<span class="scwc-help-caret" aria-hidden="true"></span>
							</summary>
							<div class="scwc-help-a"><?php echo wp_kses( wpautop( $item['a'] ), array_merge( $allowed, array( 'p' => array() ) ) ); ?></div>
						</details>
					<?php endforeach; ?>
				</div>
			<?php endforeach; ?>
		</div>
		<?php
	}
}
