<?php
/**
 * Listing Status Controller
 *
 * Polls Amazon's Listing Item endpoint after submission and exposes an AJAX
 * endpoint to retrieve issues/status for the admin UI without REST routes.
 *
 * @package MOMCS_Sync
 * @subpackage MOMCS_Sync\includes\common\controllers\sync
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Controllers\Sync;

use MOMCS_Sync\Includes\Common\Handlers\Listing_Status_Handler;
use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Class Listing_Status_Controller
 */
class Listing_Status_Controller {

	/** Action Scheduler hook name. */
	public const ACTION = 'momcs_amz_check_listing_status';

	/** Polling interval in seconds (10 minutes). */
	private const DEFAULT_INTERVAL = 600;

	/**
	 * Schedule first poll for a product.
	 *
	 * @param int    $product_id     Woo product ID.
	 * @param string $seller_id      Amazon seller ID.
	 * @param string $sku            Product SKU.
	 * @param string $marketplace_id Amazon marketplace/region identifier.
	 *
	 * @return void
	 */
	public static function schedule( int $product_id, string $seller_id, string $sku, string $marketplace_id ): void {
		if ( function_exists( 'as_next_scheduled_action' ) && as_next_scheduled_action( self::ACTION, array( $product_id, $seller_id, $sku, $marketplace_id ), 'momcs' ) ) {
			return; // Already scheduled.
		}
		as_schedule_single_action( time() + self::DEFAULT_INTERVAL, self::ACTION, array( $product_id, $seller_id, $sku, $marketplace_id ), 'momcs' );
	}

	/**
	 * Action Scheduler: poll SP-API.
	 *
	 * @param int    $product_id     Woo product ID.
	 * @param string $seller_id      Amazon seller ID.
	 * @param string $sku            Product SKU.
	 * @param string $marketplace_id Amazon marketplace/region identifier.
	 *
	 * @return mixed Listing status or error.
	 */
	public static function check_status( int $product_id, string $seller_id, string $sku, string $marketplace_id ) {
		$handler = new Listing_Status_Handler();
		return $handler->check_status( $product_id, $seller_id, $sku, $marketplace_id );
	}

	/**
	 * AJAX: return issues grouped by severity.
	 */
	public static function get_issues(): void {
		check_ajax_referer( Plugin_Constants::NONCE_MAIN, 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Permission denied' ) );
		}
		$product_id = isset( $_POST['product_id'] ) ? (int) sanitize_text_field( wp_unslash( $_POST['product_id'] ) ) : 0;
		if ( ! $product_id ) {
			wp_send_json_error( array( 'message' => 'Invalid product ID' ) );
		}

		$handler = new Listing_Status_Handler();
		$issues  = $handler->get_issues( $product_id );
		wp_send_json_success( array( 'issues' => $issues ) );
	}

	/**
	 * Get channel details from momcs_multichannels table.
	 *
	 * @return array|null Channel details with marketplace_id and channel_id, or null if not found.
	 */
	private static function get_channel_details(): ?array {
		$handler = new Listing_Status_Handler();
		return $handler->get_channel_details();
	}

	/**
	 * AJAX: Refresh product status for multiple products.
	 */
	public static function refresh_status(): void {
		check_ajax_referer( Plugin_Constants::NONCE_MAIN, 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Permission denied' ) );
		}
		$product_ids = isset( $_POST['product_ids'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['product_ids'] ) ) : array();
		if ( empty( $product_ids ) ) {
			wp_send_json_error( array( 'message' => 'No product IDs provided' ) );
		}

		// Get channel details from database.
		try {
			$handler = new Listing_Status_Handler();
			$results = $handler->refresh_status( $product_ids );
			wp_send_json_success( array( 'results' => $results ) );
		} catch ( \RuntimeException $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ) );
		}
	}
}
