<?php

namespace StoreEngine\API;

use stdClass;
use StoreEngine\Classes\Exceptions\StoreEngineException;
use StoreEngine\Utils\Formatting;
use StoreEngine\Utils\Helper;
use WP_Error;
use WP_REST_Request;

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

class Coupon {

	public static function init() {
		$self = new self();
		add_filter( 'rest_pre_insert_storeengine_coupon', [ $self, 'validate_request_data' ], 10, 2 );
	}

	public function validate_request_data( stdClass $prepared_post, WP_REST_Request $request ) {
		$meta = $request->get_param( 'meta' );

		$customers = $meta['_storeengine_coupon_valid_customers'] ?? [];
		foreach ( $customers as $customer_id ) {
			if ( ! is_numeric( $customer_id ) || ! get_user( $customer_id ) ) {
				return new WP_Error( 'invalid_customer_id', esc_html__( 'Invalid customer ID provided.', 'storeengine' ), [ 'status' => 400 ] );
			}
		}

		$prices = $meta['_storeengine_coupon_valid_prices'] ?? [];

		foreach ( $prices as $index => $price_data ) {
			$product_id = absint( $price_data['product_id'] );
			if ( ! $product_id || ! get_post( $product_id ) ) {
				return new WP_Error( 'invalid_product_id', esc_html(
					sprintf(
						// translators: %s. Item index.
						__( 'Invalid product ID provided at %s item', 'storeengine' ),
						Formatting::append_numeral_suffix( $index + 1 )
					)
				), [ 'status' => 400 ] );
			}

			$price_ids = array_map( 'absint', $price_data['price_ids'] );
			foreach ( $price_ids as $price_id ) {
				try {
					$price = Helper::get_price( $price_id );
					if ( $price->get_product_id() !== $product_id ) {
						return new WP_Error(
							'invalid_price_id',
							esc_html(
								sprintf(
									// translators: %s. Item index.
									__( 'Invalid product & price combination at %s item.', 'storeengine' ),
									Formatting::append_numeral_suffix( $index + 1 )
								)
							),
							[ 'status' => 400 ]
						);
					}
				} catch ( StoreEngineException $e ) {
					return new WP_Error( 'invalid_price_id', esc_html(
						sprintf(
							// translators: %s. Item index.
							__( 'Invalid price selected at %s item.', 'storeengine' ),
							Formatting::append_numeral_suffix( $index + 1 )
						)
					), [ 'status' => 400 ] );
				}
			}
		}

		return $prepared_post;
	}

}
