<?php
/**
 * Model for rendering a tool in the admin sync page.
 *
 * @package northmill-online-shared
 */

declare( strict_types=1 );

namespace Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Sync\Models;

use Closure;
use Northmill_Online_Shared\Abstract_Shared_Base;

defined( 'ABSPATH' ) || exit;

/**
 * Class Admin_Sync_Custom_Tool_Model
 */
readonly class Admin_Sync_Tool_Model {

	/**
	 * Key for the ajax action.
	 *
	 * @var string
	 */
	private string $ajax_key;

	/**
	 * Constructor.
	 *
	 * @param string             $id            The ID of the tool.
	 * @param array|Closure      $title         Function to get the title of the tool.
	 * @param array|Closure      $button_text   Function to get t text for the button.
	 * @param array              $tool_function Callable for when the button is clicked.
	 * @param array|Closure|null $description   Function to get t description of the tool.
	 */
	public function __construct(
		private string $id,
		private array|Closure $title,
		private array|Closure $button_text,
		private array $tool_function,
		private null|array|Closure $description = null,
	) {
		$this->ajax_key = 'admin_sync_tool_' . $this->id;
	}

	/**
	 * Renders the tool.
	 *
	 * @return void
	 */
	public function render(): void {
		Abstract_Shared_Base::base_instance()->template_loader->get_admin_template_part(
			'sync/tool',
			array(
				'id'          => $this->id,
				'title'       => $this->get_title(),
				'description' => $this->get_description(),
				'button_text' => $this->get_button_text(),
			),
			false,
		);
	}

	/**
	 * Adds the AJAX action for the tool.
	 *
	 * @return void
	 */
	public function add_ajax_action(): void {
		Abstract_Shared_Base::base_instance()->ajax->add_action(
			$this->ajax_key,
			$this->tool_function
		);
	}

	/**
	 * Gets the ID of the tool, for usage in JS.
	 *
	 * @return string
	 */
	public function get_id_for_js(): string {
		return esc_attr( $this->id ); // Escaped to ensure same as in HTML.
	}

	/**
	 * Gets the data for JavaScript.
	 *
	 * @return array
	 */
	public function get_data_for_js(): array {
		return array_merge(
			array(
				'title' => esc_attr( $this->get_title() ),
			),
			Abstract_Shared_Base::base_instance()->ajax->get_action( $this->ajax_key )?->get_data_for_js(),
		);
	}

	/**
	 * Gets the title of the tool.
	 *
	 * @return string
	 */
	public function get_title(): string {
		if ( is_callable( $this->title ) ) {
			return call_user_func( $this->title );
		}
		return '';
	}

	/**
	 * Gets the button text of the tool.
	 *
	 * @return string
	 */
	public function get_button_text(): string {
		if ( is_callable( $this->button_text ) ) {
			return call_user_func( $this->button_text );
		}
		return '';
	}

	/**
	 * Gets the description of the tool.
	 */
	public function get_description(): string {
		if ( is_callable( $this->description ) ) {
			return call_user_func( $this->description );
		}
		return '';
	}
}
