<?php
/**
 * Input trait
 *
 * @package     AffiliateWP
 * @subpackage  Utils\Traits
 * @copyright   Copyright (c) 2026, Sandhills Development, LLC
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       2.33.0
 */

namespace AffiliateWP\Utils\Traits;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Input trait
 *
 * Renders text-style <input> and <textarea> elements styled to match the AffiliateWP
 * admin Tailwind aesthetic. Consolidates the `px-4 py-2 ... rounded-lg border ...` idiom
 * that was previously copy-pasted across the stripe/paypal/emails/fraud-prevention panels.
 *
 * @since 2.33.0
 */
trait Input {

	/**
	 * Render an <input> element.
	 *
	 * @since 2.33.0
	 *
	 * @param array $args {
	 *     Input arguments.
	 *
	 *     @type string      $name         Input name attribute. Required.
	 *     @type string      $type         HTML input type. Default 'text'. Supports text, number,
	 *                                     email, url, password, tel, search.
	 *     @type string      $value        Current value.
	 *     @type string      $id           ID attribute. Derived from name when empty.
	 *     @type string      $placeholder  Placeholder text.
	 *     @type string      $size         'sm' (text-sm py-1.5) or 'md' (text-base py-2). Default 'md'.
	 *     @type string      $width        'full' (w-full), 'narrow' (w-24), or 'auto' (no width
	 *                                     utility, e.g. for flex children). Default 'full'.
	 *     @type bool        $mono         Render with a monospace font (useful for regex / keys).
	 *     @type bool        $secret       Credential-field hints: autocomplete="new-password",
	 *                                     data-lpignore, data-1p-ignore. Default false.
	 *     @type string      $autocomplete Explicit autocomplete value (overrides $secret's default).
	 *     @type string      $alpine_model Alpine x-model binding.
	 *     @type bool        $disabled     Whether the input is disabled.
	 *     @type bool        $required     Whether the input is required.
	 *     @type int|string  $min          Minimum value (number inputs).
	 *     @type int|string  $max          Maximum value (number inputs).
	 *     @type int|string  $step         Step value (number inputs).
	 *     @type string      $class        Extra classes on the <input>.
	 *     @type array       $attributes   Additional attributes (supports Alpine directives).
	 * }
	 * @return string The rendered input HTML.
	 */
	public function render_input( $args = array() ) {

		$args = $this->normalize_input_args( $args );

		if ( '' === $args['name'] ) {
			return '';
		}

		$attrs = $this->build_input_attributes( $args );

		return sprintf( '<input %s />', $attrs );
	}

	/**
	 * Render a <textarea> element.
	 *
	 * Same styling vocabulary as render_input(); adds a `rows` argument.
	 *
	 * @since 2.33.0
	 *
	 * @param array $args See render_input(). Additional keys:
	 *     @type int $rows Default 4.
	 * @return string The rendered textarea HTML.
	 */
	public function render_textarea( $args = array() ) {

		$args         = $this->normalize_input_args( $args );
		$args['rows'] = isset( $args['rows'] ) ? (int) $args['rows'] : 4;

		if ( '' === $args['name'] ) {
			return '';
		}

		$value  = isset( $args['value'] ) ? (string) $args['value'] : '';
		$attrs  = $this->build_input_attributes( $args, true );

		return sprintf(
			'<textarea %s rows="%d">%s</textarea>',
			$attrs,
			$args['rows'],
			esc_textarea( $value )
		);
	}

	/**
	 * Normalize shared input/textarea args.
	 *
	 * @since 2.33.0
	 *
	 * @param array $args Raw caller args.
	 * @return array Normalized args.
	 */
	protected function normalize_input_args( $args ) {

		$defaults = array(
			'name'         => '',
			'type'         => 'text',
			'value'        => '',
			'id'           => '',
			'placeholder'  => '',
			'size'         => 'md',
			'width'        => 'full',
			'mono'         => false,
			'secret'       => false,
			'autocomplete' => '',
			'alpine_model' => '',
			'disabled'     => false,
			'required'     => false,
			'min'          => null,
			'max'          => null,
			'step'         => null,
			'class'        => '',
			'attributes'   => array(),
		);

		$args = wp_parse_args( $args, $defaults );

		if ( empty( $args['id'] ) && ! empty( $args['name'] ) ) {
			$args['id'] = sanitize_key( $args['name'] );
		}

		return $args;
	}

	/**
	 * Build the shared class list for inputs and textareas.
	 *
	 * @since 2.33.0
	 *
	 * @param array $args       Normalized args.
	 * @param bool  $is_textarea Whether rendering a textarea (width handling differs).
	 * @return string
	 */
	protected function get_input_classes( $args, $is_textarea = false ) {

		$classes = array(
			'px-4',
			'text-gray-900',
			'bg-white',
			'rounded-lg',
			'border',
			'border-gray-300',
			'transition-colors',
			'focus:outline-hidden',
			'focus:border-affwp-brand-500',
			'focus:ring-1',
			'focus:ring-affwp-brand-500',
			'hover:border-gray-400',
		);

		// Size-specific classes.
		if ( 'sm' === $args['size'] ) {
			$classes[] = 'py-1.5';
			$classes[] = 'text-sm';
		} else {
			$classes[] = 'py-2';
			$classes[] = 'text-base';
		}

		// Width utility. Textareas are effectively always full-width.
		if ( $is_textarea ) {
			$classes[] = 'w-full';
		} else {
			switch ( $args['width'] ) {
				case 'narrow':
					$classes[] = 'w-24';
					break;
				case 'auto':
					// No width utility — caller is responsible (e.g. flex-1 via $class).
					break;
				case 'full':
				default:
					$classes[] = 'w-full';
					break;
			}
		}

		if ( $args['mono'] ) {
			$classes[] = 'font-mono';
		}

		if ( $args['disabled'] ) {
			$classes[] = 'opacity-50';
			$classes[] = 'cursor-not-allowed';
		}

		if ( ! empty( $args['class'] ) ) {
			$classes[] = $args['class'];
		}

		return implode( ' ', array_unique( $classes ) );
	}

	/**
	 * Build the attribute string for the input or textarea element.
	 *
	 * @since 2.33.0
	 *
	 * @param array $args        Normalized args.
	 * @param bool  $is_textarea Whether rendering a textarea.
	 * @return string
	 */
	protected function build_input_attributes( $args, $is_textarea = false ) {

		$attrs = array(
			'id'   => esc_attr( $args['id'] ),
			'name' => esc_attr( $args['name'] ),
		);

		if ( ! $is_textarea ) {
			$attrs['type']  = esc_attr( $args['type'] );
			$attrs['value'] = esc_attr( (string) $args['value'] );
		}

		$attrs['class'] = esc_attr( $this->get_input_classes( $args, $is_textarea ) );

		if ( '' !== $args['placeholder'] ) {
			$attrs['placeholder'] = esc_attr( $args['placeholder'] );
		}

		// Password-manager-friendly credential fields. Explicit autocomplete wins.
		if ( '' !== $args['autocomplete'] ) {
			$attrs['autocomplete'] = esc_attr( $args['autocomplete'] );
		} elseif ( $args['secret'] ) {
			$attrs['autocomplete'] = 'new-password';
		}

		if ( $args['secret'] ) {
			$attrs['data-lpignore'] = 'true';
			// data-1p-ignore is a valueless attribute; 1Password recognizes presence.
			$attrs['data-1p-ignore'] = '';
		}

		if ( ! empty( $args['alpine_model'] ) ) {
			$attrs['x-model'] = esc_attr( $args['alpine_model'] );
		}

		if ( $args['disabled'] ) {
			$attrs['disabled'] = 'disabled';
		}

		if ( $args['required'] ) {
			$attrs['required'] = 'required';
		}

		// Number-input constraints.
		if ( ! $is_textarea && 'number' === $args['type'] ) {
			if ( null !== $args['min'] ) {
				$attrs['min'] = esc_attr( (string) $args['min'] );
			}
			if ( null !== $args['max'] ) {
				$attrs['max'] = esc_attr( (string) $args['max'] );
			}
			if ( null !== $args['step'] ) {
				$attrs['step'] = esc_attr( (string) $args['step'] );
			}
		}

		// Custom attributes (Alpine directives pass through verbatim).
		if ( ! empty( $args['attributes'] ) && is_array( $args['attributes'] ) ) {
			foreach ( $args['attributes'] as $key => $value ) {
				if ( 0 === strpos( $key, '@' ) || 0 === strpos( $key, 'x-' ) || 0 === strpos( $key, ':' ) ) {
					$attrs[ $key ] = $value;
				} else {
					$attrs[ $key ] = esc_attr( $value );
				}
			}
		}

		$pieces = array();
		foreach ( $attrs as $key => $value ) {
			if ( 'disabled' === $value || 'required' === $value ) {
				$pieces[] = $key;
			} elseif ( '' === $value && in_array( $key, array( 'data-1p-ignore' ), true ) ) {
				// Valueless attribute.
				$pieces[] = $key;
			} else {
				$pieces[] = sprintf( '%s="%s"', $key, $value );
			}
		}

		return implode( ' ', $pieces );
	}
}
