<?php

namespace WeDevs\AppBridge\Integrations\WooCommerce;

use Automattic\WooCommerce\StoreApi\Schemas\ExtendSchema;
use Automattic\WooCommerce\StoreApi\StoreApi;
use WeDevs\AppBridge\Core\Contracts\Hookable;
use WeDevs\AppBridge\Core\Auth\JwtAuth;
use WeDevs\AppBridge\Integrations\WooCommerce\Session\SessionHandler;
use WeDevs\AppBridge\Integrations\WooCommerce\StoreApi\CartPaymentExtension;

class WooCommerceHooks implements Hookable {

	public function register_hooks(): void {
		add_action( 'woocommerce_init', [ $this, 'on_wc_init' ] );
		add_filter( 'woocommerce_rest_product_object_query', [ $this, 'filter_product_query' ], 99 );
		add_filter( 'woocommerce_rest_prepare_shop_order_object', [ $this, 'add_image_in_order' ], 10, 3 );
		add_filter( 'woocommerce_rest_product_object_query', [ $this, 'add_author_query_support' ], 10, 2 );
		add_filter( 'rest_product_collection_params', [ $this, 'add_author_support_collection_param' ], 10, 2 );
		add_action( 'pre_get_posts', [ $this, 'add_auction_product_in_product_query' ], 100, 2 );
		add_action( 'woocommerce_blocks_loaded', [ $this, 'woocommerce_blocks_loaded' ], 100, 2 );
	}

	public function on_wc_init(): void {
		if ( ! wc()->is_rest_api_request() ) {
			return;
		}

		$namespace  = '/dokan/v1/';
		$rest_bases = [
			'cart/coupons',
			'cart/items',
			'cart/shipping',
			'customers',
			'payment',
			'checkout',
		];

		$load_cart_session = false;

		foreach ( $rest_bases as $rest_base ) {
			if ( strpos( $_SERVER['REQUEST_URI'], $namespace . $rest_base ) ) { // phpcs:ignore
				$load_cart_session = true;
				break;
			}
		}

		if ( strpos( $_SERVER['REQUEST_URI'], '/wc/v3/orders' ) ) { // phpcs:ignore
			$load_cart_session = true;
		}

		if ( $load_cart_session ) {
			$this->load_cart_session();
		}
	}

	private function load_cart_session(): void {
		if ( ! isset( $_REQUEST['dokan_app_token'] ) && ! get_current_user_id() ) { // phpcs:ignore
			return;
		}

		$jwt_auth = new JwtAuth();

		$token = $jwt_auth->validate_token_for_request(null, $_REQUEST['dokan_app_token'] ?? ''); // phpcs:ignore

		if ( is_wp_error( $token ) && ! get_current_user_id() ) {
			return;
		}

		add_filter(
			'woocommerce_session_handler',
			fn() => SessionHandler::class
		);

		include_once WC_ABSPATH . 'includes/wc-notice-functions.php';

		if ( ! wc()->cart ) {
			include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
			wc_load_cart();
		}
	}

	public function filter_product_query( array $args ): array {
		if ( ! wc()->is_rest_api_request() ) {
			return $args;
		}

		$tax_query = $args['tax_query'] ?? [];

		if ( ! isset( $tax_query['relation'] ) ) {
			$tax_query['relation'] = 'AND';
		}

		$args['tax_query'] = wc()->query->get_tax_query( $tax_query, false ); // phpcs:ignore

		return $args;
	}

	public function add_image_in_order( $response, $object, $request ) { // phpcs:ignore
		$image_url = '';
		foreach ( $object->get_items( 'line_item' ) as $item ) {
			$product = wc_get_product( $item->get_product_id() );

			if ( '' === $image_url && $product && $product->get_image_id() ) {
				$image_url = wp_get_attachment_image_url( $product->get_image_id() );
			}
		}

		$response->data['image'] = $image_url;

		return $response;
	}

	public function add_author_query_support( array $args, $request ): array {
		$author_id = $request->get_param( 'author' );
		if ( ! empty( $author_id ) ) {
			$args['author'] = $author_id;
		}

		return $args;
	}

	public function add_author_support_collection_param( array $params, $post_type ): array {
		if ( 'product' === $post_type ) {
			$params['author'] = [
				'description'       => __( 'Limit result set to items assigned to specific authors.', 'app-bridge' ),
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
				'validate_callback' => 'rest_validate_request_arg',
				'minimum'           => 1,
			];
		}

		return $params;
	}

	public function add_auction_product_in_product_query( $q ): void {
		if ( ! wc()->is_rest_api_request() ) {
			return;
		}

		$tax_queries = $q->get( 'tax_query' );

		if ( ! empty( $tax_queries ) ) {
			foreach ( $tax_queries as $key => $tax_query ) {
				if ( is_array( $tax_query ) && 'product_type' === $tax_query['taxonomy'] && 'auction' === $tax_query['terms'] ) {
					unset( $tax_queries[ $key ] );
				}
			}
		}

		$q->set( 'tax_query', $tax_queries );
	}

	public function woocommerce_blocks_loaded(): void {
		$extend = StoreApi::container()->get( ExtendSchema::class );
		CartPaymentExtension::init( $extend );
	}
}
