<?php

namespace PostenBringCheckout\admin\api\handlers;

use Exception;
use PostenBringCheckout\admin\bring\CheckoutApi;
use RuntimeException;
use WC_Product_Attribute;
use WP_REST_Request;
use WP_REST_Response;

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

/**
 * Handles HS code suggestions and registration
 */
class CustomsHandler {

	/**
	 * @param WP_REST_Request $request
	 *
	 * @return WP_REST_Response
	 * @throws Exception
	 */
	public function get_hs_codes( WP_REST_Request $request ) {
		$query = trim( (string) $request->get_param( 'q' ) );

		if ( $query === '' ) {
			return new WP_REST_Response( array(), 200 );
		}

		try {
			$suggestions = CheckoutApi::get_instance()->query_hs_code( $query );

			return new WP_REST_Response( $suggestions, 200 );
		} catch ( Exception $exception ) {
			wc_get_logger()->warning( esc_html($exception->getMessage()), array( 'source' => 'posten-bring-checkout' ) );
			return new WP_REST_Response(null, 500);
		}
	}

	/**
	 * @param WP_REST_Request $request
	 *
	 * @return WP_REST_Response
	 * @throws Exception
	 */
	public function register_hs_codes( WP_REST_Request $request ) {
		try {
			$request_body = json_decode( $request->get_body(), true );

			if ( ! is_array( $request_body ) ) {
				return new WP_REST_Response( array( 'error' => 'Invalid request body' ), 400 );
			}

			$taxonomy = self::ensure_hs_code_attribute_exists();

			foreach ( $request_body as $product_and_hs_code ) {
				if ( ! isset( $product_and_hs_code['productId'] ) ) {
					continue;
				}

				$product = wc_get_product( $product_and_hs_code['productId'] );
				$hs_code = sanitize_text_field( $product_and_hs_code['hsCode'] ?? '' );

				if ( ! $product || ! $hs_code ) {
					continue;
				}

				$current = trim(
					wp_strip_all_tags(
						$product->get_attribute( $taxonomy )
					)
				);

				if ( $current === $hs_code ) {
					continue;
				}

				wp_set_object_terms( $product->get_id(), $hs_code, $taxonomy, false );

				$attributes = $product->get_attributes();

				$attribute = new WC_Product_Attribute();
				$attribute->set_id( wc_attribute_taxonomy_id_by_name( $taxonomy ) );
				$attribute->set_name( $taxonomy );
				$term = get_term_by( 'name', $hs_code, $taxonomy );
				$attribute->set_options( [ $term->term_id ] );
				$attribute->set_visible( false );
				$attribute->set_variation( false );

				$attributes[ $taxonomy ] = $attribute;

				$product->set_attributes( $attributes );
				$product->save();

			}

			return new WP_REST_Response(array(), 200);
		} catch (Exception $exception) {
			wc_get_logger()->error( esc_html($exception->getMessage()), array( 'source' => 'posten-bring-checkout' ) );
			return new WP_REST_Response(null, 500);
		}
	}

	private static function ensure_hs_code_attribute_exists(): string {
		$attribute_names = array(
			'hscode',
			'hs-code',
			'htscode',
			'hts-code',
		);

		foreach ( $attribute_names as $attribute_name ) {
			$taxonomy = wc_attribute_taxonomy_name( $attribute_name );

			if ( taxonomy_exists( $taxonomy ) ) {
				return $taxonomy;
			}

			$attribute_id = wc_attribute_taxonomy_id_by_name( $attribute_name );

			if ( $attribute_id ) {
				self::register_hs_code_taxonomy( $taxonomy );
				return $taxonomy;
			}
		}

		$attribute_name = 'hscode';
		$taxonomy       = wc_attribute_taxonomy_name( $attribute_name );

		$attribute_id = wc_create_attribute( array(
			'name'         => __( 'HS Code', 'posten-bring-checkout' ),
			'slug'         => $attribute_name,
			'type'         => 'select',
			'order_by'     => 'name',
			'has_archives' => false,
		) );

		if ( is_wp_error( $attribute_id ) ) {
			throw new RuntimeException( $attribute_id->get_error_message() );
		}

		self::register_hs_code_taxonomy( $taxonomy );

		delete_transient( 'wc_attribute_taxonomies' );

		return $taxonomy;
	}

	private static function register_hs_code_taxonomy( string $taxonomy ): void {
		if ( taxonomy_exists( $taxonomy ) ) {
			return;
		}

		register_taxonomy(
			$taxonomy,
			array( 'product' ),
			array(
				'hierarchical' => false,
				'show_ui'      => false,
				'query_var'    => true,
				'rewrite'      => false,
			)
		);
	}
}
