<?php
/**
 * This file holds an object for a table field.
 *
 * @package easy-settings-for-wordpress
 */

namespace easySettingsForWordPress\Fields;

// prevent direct access.
defined( 'ABSPATH' ) || exit;

use easySettingsForWordPress\Field_Base;
use easySettingsForWordPress\Setting;

/**
 * Object to handle a table for a setting.
 */
class Table extends Field_Base {
	/**
	 * The type name.
	 *
	 * @var string
	 */
	protected string $type_name = 'Table';

	/**
	 * List of options for each entry.
	 *
	 * @var array<string,mixed>
	 */
	private array $table_options = array();

	/**
	 * Return the HTML-code to display this field.
	 *
	 * @param array<string,mixed> $attr Attributes for this field.
	 *
	 * @return void
	 */
	public function display( array $attr ): void {
		// bail if no attributes are set.
		if ( empty( $attr ) ) {
			return;
		}

		// bail if no setting object is set.
		if ( empty( $attr['setting'] ) ) {
			return;
		}

		// bail if field is not a Setting object.
		if ( ! $attr['setting'] instanceof Setting ) {
			return;
		}

		// get the setting object.
		$setting = $attr['setting'];

		// get values.
		$values = get_option( $setting->get_name() );
		if ( ! is_array( $values ) || empty( $values[0] ) ) {
			$values = array();
		}

		// create table object.
		$table_obj = new \easySettingsForWordPress\Tables\Table();
		$table_obj->set_settings_obj( $this->get_settings_obj() );
		$table_obj->set_table_data( $values );
		$table_obj->set_table_options( $this->table_options );
		$table_obj->prepare_items();
		$table_obj->display();

		// add each item as setting.
		foreach ( $values as $value ) {
			?><input type="hidden" name="<?php echo esc_attr( $setting->get_name() ); ?>[]" value="<?php echo esc_attr( $value ); ?>">
			<?php
		}

		// show optional description for this checkbox.
		if ( ! empty( $this->get_description() ) ) {
			echo '<p>' . wp_kses_post( $this->get_description() ) . '</p>';
		}
	}

	/**
	 * Set options for each entry in the table.
	 *
	 * Format:
	 * array(
	 *     'url' => 'url_to_use',
	 *     'icon' => 'icon_to_use'
	 * )
	 *
	 * @param array<string,mixed> $options List of options.
	 *
	 * @return void
	 */
	public function set_table_options( array $options ): void {
		$this->table_options = $options;
	}

	/**
	 * The sanitize callback for this field.
	 *
	 * @param mixed $value The value to save.
	 *
	 * @return mixed
	 */
	public function default_sanitize_callback( mixed $value ): mixed {
		return $value;
	}
}
