<?php

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

/**
 * Commercebird Purchase Order Class - Automation
 *
 * @since 1.0.0
 */
class CMBIRD_Purchase_Orders_Automation {

	public function __construct() {
		add_action( 'cmbird_purchase_order_auto', array( $this, 'create_purchase_order' ) );
	}

	/**
	 * Create purchase order for matching products based on automation settings.
	 *
	 * @since 1.0.0
	 */
	public function create_purchase_order() {
		$settings = get_option( 'cmbird_po_automation_settings' );

		// Check if automation is enabled.
		if ( empty( $settings ) || empty( $settings['enable_automation'] ) || ! $settings['enable_automation'] ) {
			return;
		}

		$selected_statuses = isset( $settings['product_stock_status'] ) ? (array) $settings['product_stock_status'] : array();

		$products = array();

		if ( in_array( 'out_of_stock', $selected_statuses, true ) ) {
			$products = array_merge(
				$products,
				wc_get_products(
					array(
						'status'       => 'publish',
						'limit'        => -1,
						'stock_status' => 'outofstock',
					)
				)
			);
		}

		if ( in_array( 'low_stock', $selected_statuses, true ) ) {
			$products = array_merge(
				$products,
				wc_get_products(
					array(
						'status'       => 'publish',
						'limit'        => -1,
						'stock_status' => 'lowstock',
					)
				)
			);
		}

		if ( in_array( 'on_backorder', $selected_statuses, true ) ) {
			$products = array_merge(
				$products,
				wc_get_products(
					array(
						'status'       => 'publish',
						'limit'        => -1,
						'stock_status' => 'onbackorder',
					)
				)
			);
		}

		// Remove duplicates.
		$products = array_unique( $products, SORT_REGULAR );

		if ( empty( $products ) ) {
			return;
		}

		// Optionally group by vendor in the future using this meta key.
		// $vendor_id = get_post_meta( $product->get_id(), 'vendor_id', true );

		// Get existing purchase orders with specific statuses.
		$existing_purchase_orders = wc_get_orders(
			array(
				'type'   => 'shop_purchase',
				'status' => array( 'pending', 'awaiting-approval', 'approved' ),
				'limit'  => 5,
				'return' => 'objects',
			)
		);

		// Collect product IDs already in pending/awaiting/approved purchase orders.
		$excluded_product_ids = array();

		foreach ( $existing_purchase_orders as $po_order ) {
			foreach ( $po_order->get_items() as $item ) {
				$excluded_product_ids[] = $item->get_product_id();
			}
		}

		$included_product_ids = array();
		// Then process each product, skipping the excluded ones.
		foreach ( $products as $product ) {
			if ( in_array( $product->get_id(), $excluded_product_ids, true ) ) {
				continue; // Skip this product.
			}

			$stock_quantity    = $product->get_stock_quantity();
			$low_stock_amount  = $product->get_low_stock_amount();
			$quantity_to_order = 1;

			if ( $product->is_on_backorder( 1 ) || $product->get_stock_status() === 'onbackorder' ) {
				$target_stock      = 10;
				$quantity_to_order = max( 1, $target_stock - intval( $stock_quantity ) );
			} elseif ( $product->get_stock_status() === 'outofstock' ) {
				$quantity_to_order = 5;
			} elseif ( null !== $stock_quantity && null !== $low_stock_amount && $low_stock_amount >= $stock_quantity ) {
				$target_stock      = $low_stock_amount + 5;
				$quantity_to_order = max( 1, $target_stock - intval( $stock_quantity ) );
			}
			// add product and quantity to the included product IDs.
			$included_product_ids[ $product->get_id() ] = array(
				'product'  => $product,
				'quantity' => $quantity_to_order,
			);
		}

		// If no products to include, exit.
		if ( empty( $included_product_ids ) ) {
			return;
		}

		// Create a shop_purchase order.
		$order = new CMBIRD_Purchase_Order();
		// add the products to the order.
		foreach ( $included_product_ids as $product_id => $product_data ) {
			$product  = $product_data['product'];
			$quantity = $product_data['quantity'];
			$order->add_product( $product, $quantity );
		}
		$order->calculate_totals();
		$order->update_status( 'awaiting-approval' );
		$order->save();
	}
}
