<?php
/**
 * Markup Post Reference field
 * IMPORTANT: all data-wpt-* fields are required to support legacy functions, like field conditons.
 *
 * @since m2m
 */
    $field_value = $field->get_value();

    $validation_rules = json_decode( $field->get_formatted_validation_data(), true );

    // for select2 we simply use html5 required
    $html_attr_validation_required = isset( $validation_rules['required'] )
        ? ' required'
        : '';

    // custom message for html5 required field
    $html_attr_validation_required .= $html_attr_validation_required != '' && isset( $validation_rules['required']['message'] )
        ?  ' oninvalid="this.setCustomValidity(\'' . $validation_rules['required']['message'] .'\')" onchange="this.setCustomValidity(\'\')"'
        : '';
?>

<div class="js-wpt-field wpt-field toolset-post-reference-field <?php echo $additional_css_classes;?>" data-wpt-type="select" data-wpt-id="wpcf-<?php echo $field->get_slug();?>">
    <div class="js-wpt-field-items">
        <div class="js-wpt-field-item wpt-field-item">
    <label class="wpt-form-label wpt-form-textfield-label"><?php echo $field->get_title(); if( ! empty( $html_attr_validation_required ) ) echo '*'; ?>
        <?php if ( $disabled ) { ?>
            <i class="fa fa-question-circle icon-question-sign js-show-tooltip" data-header="<?php echo __( 'Post Reference Field disabled', 'wpcf' ); ?>" data-content="<?php echo __( 'This post has to be translated to default language in order to connect a post', 'wpcf' ); ?>" ></i>
        <?php } ?>
    </label>
    <select data-placeholder="<?php printf( __( 'Connect with %s', 'wpcf' ), $field->get_post_type()->label ); ?>"
            <?php if ( $disabled ) {
                echo ' disabled="disabled" ';
            } ?>
            data-types-post-reference="<?php echo $field->get_post_type()->name ?>" name="wpcf[<?php echo $field->get_slug() ?>]"
            data-wpt-type="select" data-wpt-id="wpcf-<?php echo $field->get_slug();?>" data-wpt-name="wpcf[<?php echo $field->get_slug();?>]"<?php echo $html_attr_validation_required; ?>>
        <option value=""></option>
		<?php if( $post = $field->get_post() ): ?>
			<?php $selected = $post->ID == $field_value ? ' selected="selected"' : ''; ?>
            <option value="<?php echo $post->ID;?>"<?php echo $selected; ?> data-url="<?php echo get_permalink( $post->ID ); ?>"><?php echo $post->post_title ?></option>
		<?php endif; ?>
    </select>
        </div>
    </div>
</div>
