<?php
namespace SabaiApps\Directories\Component\Form\Field;

use SabaiApps\Directories\Component\Form\Form;

/**
 * TokenField provides a hidden field for CSRF protection using form tokens.
 * Supports configurable token lifetime and reuse.
 */
class TokenField extends AbstractField {

	/**
	 * Initializes the Token field and sets the token ID.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		if ( empty( $data['#token_id'] ) ) {
			$data['#token_id'] = isset( $form->settings['#name'] ) ? $form->settings['#name'] : $form->settings['#id'];
		}
	}

	/**
	 * Handles token validation for CSRF protection on form submit.
	 *
	 * @param mixed $value
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldSubmit( &$value, array &$data, Form $form ) {
		if ( ! $this->_application->Form_Form_validateToken( $value, $data['#token_id'], ! empty( $data['#token_reuseable'] ) ) ) {
			$form->setError( __( 'Your session has expired or the form token is invalid. Please try again.', 'directories-pro' ) );
		}
	}

	/**
	 * Renders the Token field as a hidden input with generated token value.
	 *
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldRender( array &$data, Form $form ) {
		if ( empty( $data['#token_lifetime'] ) ) {
			$data['#token_lifetime'] = 1800;
		}
		$data['#default_value']                = $data['#value'] = $this->_application->Form_Form_createToken(
			$data['#token_id'],
			$data['#token_lifetime'],
			! empty( $data['#token_reobtainable'] )
		);
		$form->settings['#rendered_hiddens'][] = sprintf(
			'<input type="hidden" name="%s" value="%s"%s>',
			$this->_application->H( $data['#name'] ),
			$this->_application->H( $data['#default_value'] ),
			$this->_application->Attr( $data['#attributes'] )
		);
	}
}
