<?php

namespace WPDRMS\ASP\BlockEditor;

use WPDRMS\ASP\Statistics\ORM\Search;

if ( !defined('ABSPATH') ) {
	die("You can't access this file directly.");
}

class UserSearchesBlock implements BlockInterface {
	public function register(): void {
		if ( !function_exists('register_block_type') || defined('ASP_UNIT_TEST') ) {
			return;
		}

		if ( !wp_script_is('wdo-asp-block-editor', 'registered') ) {
			$metadata = require_once ASP_PATH . '/build/js/block-editor.asset.php'; // @phpstan-ignore-line
			wp_register_script(
				'wdo-asp-block-editor',
				ASP_URL_NP . 'build/js/block-editor.js',
				$metadata['dependencies'],
				$metadata['version'],
				array( 'in_footer' => true )
			);
		}

		$view_meta = require ASP_PATH . '/build/js/user-searches-view.asset.php'; // @phpstan-ignore-line
		wp_register_script(
			'wdo-asp-user-searches-view',
			ASP_URL_NP . 'build/js/user-searches-view.js',
			$view_meta['dependencies'],
			$view_meta['version'],
			array( 'in_footer' => true )
		);

		register_block_type(
			'ajax-search-pro/user-searches',
			array(
				'api_version'     => 3,
				'editor_script'   => 'wdo-asp-block-editor',
				'render_callback' => array( $this, 'render' ),
				'supports'        => array(
					'color'      => array( 'text' => true, 'background' => false, 'link' => true ),
					'typography' => array( 'fontSize' => true ),
				),
				'attributes'      => array(
					'mode'      => array( 'default' => 'popular', 'type' => 'string' ),
					'asp_id'    => array( 'default' => 0, 'type' => 'integer' ),
					'limit'     => array( 'default' => 10, 'type' => 'integer' ),
					'separator' => array( 'default' => ', ', 'type' => 'string' ),
					'action'    => array( 'default' => 'none', 'type' => 'string' ),
					'target_id' => array( 'default' => 0, 'type' => 'integer' ),
				),
			)
		);
	}

	/**
	 * @param array{mode: string, asp_id: int, limit: int, separator: string, action: string, target_id: int} $attributes
	 * @return string
	 */
	public function render( array $attributes ): string {
		global $wpdb;

		$table     = Search::getTableName();
		$mode      = in_array( $attributes['mode'] ?? '', array( 'popular', 'latest' ), true ) ? $attributes['mode'] : 'popular';
		$asp_id    = (int) ( $attributes['asp_id'] ?? 0 );
		$limit     = min( 100, max( 1, (int) ( $attributes['limit'] ?? 10 ) ) );
		$separator = esc_html( $attributes['separator'] ?? ', ' );
		$action    = in_array( $attributes['action'] ?? '', array( 'none', 'redirect', 'trigger' ), true ) ? $attributes['action'] : 'none';
		$target_id = (int) ( $attributes['target_id'] ?? 0 );
		$order     = $mode === 'popular' ? 'COUNT(*) DESC' : 'MAX(date) DESC';

		if ( $asp_id > 0 ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
			$phrases = $wpdb->get_col(
				$wpdb->prepare(
					"SELECT phrase FROM {$table} WHERE phrase != '' AND asp_id = %d GROUP BY phrase ORDER BY {$order} LIMIT %d",
					$asp_id,
					$limit
				)
			);
		} else {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
			$phrases = $wpdb->get_col(
				$wpdb->prepare(
					"SELECT phrase FROM {$table} WHERE phrase != '' GROUP BY phrase ORDER BY {$order} LIMIT %d",
					$limit
				)
			);
		}

		if ( empty( $phrases ) ) {
			return '';
		}

		$items = array();
		foreach ( $phrases as $phrase ) {
			$phrase_esc = esc_html( $phrase );
			if ( $action !== 'none' ) {
				$items[] = '<span class="asp-us-phrase"'
					. ' data-asp-phrase="' . esc_attr( $phrase ) . '"'
					. ' data-asp-action="' . esc_attr( $action ) . '"'
					. ' data-asp-id="' . esc_attr( (string) $target_id ) . '"'
					. ' style="cursor:pointer">'
					. $phrase_esc . '</span>';
			} else {
				$items[] = '<span class="asp-us-phrase">' . $phrase_esc . '</span>';
			}
		}

		if ( $action !== 'none' ) {
			wp_enqueue_script( 'wdo-asp-user-searches-view' );
		}

		$wrapper = get_block_wrapper_attributes( array( 'class' => 'wp-block-ajax-search-pro-user-searches' ) );
		return '<div ' . $wrapper . '>' . implode( $separator, $items ) . '</div>';
	}
}
