<?php
/**
 * Postomatic Plugin - Product Handler class.
 *
 * PHP Version 5.6
 *
 * @package  Postomatic
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.0.0
 */

namespace Postomatic\Api;

/**
 * Product Handler class.
 *
 * This class handles the product-related functionality.
 *
 * Product retrieval is delegated to Product_Source_Detector, which picks the
 * active e-commerce platform (WooCommerce, Easy Digital Downloads, or
 * SureCart) using each platform's own documented markers. This class no
 * longer contains any platform-specific logic, and — critically — no longer
 * falls back to treating an arbitrary `product` post type as a store. That
 * fallback was the source of conflicts on sites where an unrelated plugin or
 * theme happens to register its own `product` post type for something else;
 * Postomatic would previously read/display that unrelated content as if it
 * were e-commerce products.
 *
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.0.0
 */
class Product_Handler {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'wp_ajax_postomatic_get_products', array( $this, 'get_products' ) );
	}

	/**
	 * Get products.
	 *
	 * This method returns the products.
	 *
	 * @return void
	 */
	public function get_products() {
		// Check nonce for security.
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'postomatic_admin_nonce' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );

			return;
		}

		// Check if user has permission.
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( 'Permission denied', 403 );

			return;
		}

		// Get search query if provided.
		$search_query = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '';

		// Get page number for pagination.
		$page = isset( $_POST['page'] ) ? intval( $_POST['page'] ) : 1;
		$page = max( 1, $page );

		// Get products with search and pagination.
		$products = $this->get_products_data( $search_query, $page );

		wp_send_json_success( $products );
	}

	/**
	 * Get products data from whichever supported e-commerce platform is active.
	 *
	 * @param  string $search_query Optional search query to filter products.
	 * @param  int    $page         Optional page number for pagination.
	 * @return array  Products + pagination, in the shape documented on
	 *                Product_Source_Interface::get_products().
	 */
	private function get_products_data( $search_query = '', $page = 1 ) {
		$per_page = 20; // Number of products per page.

		$source = Product_Source_Detector::get_active_source();

		if ( ! $source ) {
			// No supported platform (WooCommerce, Easy Digital Downloads, or
			// SureCart) is active on this site. Returning an empty, correctly
			// shaped result — rather than guessing at an unrelated 'product'
			// post type — is what prevents this feature from misfiring on
			// sites that don't actually run an e-commerce plugin.
			return array(
				'products'   => array(),
				'pagination' => array(
					'total'        => 0,
					'per_page'     => $per_page,
					'current_page' => $page,
					'total_pages'  => 0,
				),
			);
		}

		return $source->get_products( $search_query, $page, $per_page );
	}
}
