<?php
/**
 * Orders Controller
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/controllers
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Controllers;

use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handles orders related AJAX endpoints.
 */
class Orders_Controller {
	/**
	 * Handle AJAX: fetch orders and/or fetch-new orders.
	 */
	public static function handle_fetch_orders(): void {
		check_ajax_referer( Plugin_Constants::NONCE_MAIN, 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Permission denied', 'multi-channel-for-woocommerce' ) ) );
		}

		try {
			$page               = isset( $_POST['page'] ) ? (int) sanitize_text_field( wp_unslash( $_POST['page'] ) ) : 1;
			$per_page           = isset( $_POST['per_page'] ) ? (int) sanitize_text_field( wp_unslash( $_POST['per_page'] ) ) : 10;
			$status_filter      = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';
			$fulfillment_filter = isset( $_POST['fulfillment'] ) ? sanitize_text_field( wp_unslash( $_POST['fulfillment'] ) ) : '';
			$search             = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '';
			$fetch_new          = isset( $_POST['fetch_new'] ) && in_array( sanitize_text_field( wp_unslash( $_POST['fetch_new'] ) ), array( '1', 1, true, 'true' ), true );
			$date_from          = isset( $_POST['date_from'] ) ? sanitize_text_field( wp_unslash( $_POST['date_from'] ) ) : '';
			$date_to            = isset( $_POST['date_to'] ) ? sanitize_text_field( wp_unslash( $_POST['date_to'] ) ) : '';

			// For free users: restrict to 24-hour date range for new order fetching.
			if ( $fetch_new && ! \MOMCS_Sync\Includes\Common\Utils\Utils::is_premium_plan() ) {
				// Override with 24-hour range.
				$date_from = gmdate( 'Y-m-d', strtotime( '-1 day' ) );
				$date_to   = gmdate( 'Y-m-d' );
			}

			// Convert dates to ISO 8601 format for Amazon API if fetching new orders.
			if ( $fetch_new ) {
				if ( ! empty( $date_from ) ) {
					$date_from = gmdate( 'Y-m-d\TH:i:s\Z', strtotime( $date_from ) );
				}
				if ( ! empty( $date_to ) ) {
					$date_to = gmdate( 'Y-m-d\TH:i:s\Z', strtotime( $date_to . ' 23:59:59' ) );
				}
			}

			$handler = new \MOMCS_Sync\Includes\Common\Handlers\Dashboard_Handler();
			$result  = $handler->fetch_orders( $page, $per_page, $status_filter, $fulfillment_filter, $search, $fetch_new, $date_from, $date_to );

			if ( $fetch_new ) {
				$created           = isset( $result['created_orders'] ) ? (int) $result['created_orders'] : 0;
				$failed            = isset( $result['failed_orders'] ) ? (int) $result['failed_orders'] : 0;
				$result['message'] = sprintf(
					/* translators: 1: number of orders created, 2: number of orders failed */
					__( 'Created %1$d new WooCommerce orders. Failed to create %2$d orders.', 'multi-channel-for-woocommerce' ),
					$created,
					$failed
				);
				$result['orders']    = isset( $result['orders'] ) ? $result['orders'] : array();
				$result['total']     = isset( $result['total'] ) ? (int) $result['total'] : 0;
				$result['max_pages'] = isset( $result['max_pages'] ) ? (int) $result['max_pages'] : 0;
			} else {
				$order_count       = ( isset( $result['orders'] ) && is_array( $result['orders'] ) ) ? count( $result['orders'] ) : 0;
				$result['message'] = sprintf(
					/* translators: %d: number of orders found */
					__( 'Found %d orders.', 'multi-channel-for-woocommerce' ),
					$order_count
				);
			}

			wp_send_json_success( $result );
		} catch ( \Throwable $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ) );
		}
	}
}
