<?php

namespace WeDevs\AppBridge\Integrations\Dokan;

use WeDevs\AppBridge\Core\Contracts\Hookable;
use WP_Error;

class DokanHooks implements Hookable {

	public function register_hooks(): void {
		add_filter( 'rest_pre_dispatch', [ $this, 'check_license_on_rest' ], 10, 3 );
		add_filter( 'dokan_rest_product_object_query', [ $this, 'filter_product_query' ] );
		add_filter( 'dokan_all_products_query', [ $this, 'filter_product_query' ] );
	}

	/**
	 * Check license for requests with X-Dokan-App header.
	 */
	public function check_license_on_rest( $response, $item, $request ) {
		if ( wc_string_to_bool( $request->get_header( 'X-Dokan-App' ) ) ) {
			$license = pocket_store()->dokan()->get_license_manager()->get_license();
			if ( ! $license->is_valid() ) {
				return new WP_Error( 'invalid-license', __( 'Your Dokan App license key is invalid', 'app-bridge' ), [ 'status' => 401 ] );
			}
		}

		return $response;
	}

	/**
	 * Filter Dokan product queries in REST API.
	 */
	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;
	}
}
