<?php

if ( !defined( 'ABSPATH' ) ) {
    die( 'No direct access allowed' );
}

/**
 * Validate theme options before save
 * @param string $input
 * @param string $type
 * @param string $field_id
 * @return string
 */
function leap_validate_theme_options( $input, $type, $field_id ) {
    /**
     * Validate text type
     */
    if ( 'text' == $type ) {
        /**
         * Validate positive integer inputs
         */
        $fields = array( 'fb_comments_num', 'google_map_zoom', 'excerpt_length' );
        if ( in_array( $field_id, $fields ) ) {
            if ( !ctype_digit( $input ) || ($input < 1) ) {
                $input = '';
                add_settings_error( 'option-tree', 'invalid_positive_integer', sprintf( __( 'The input field for %s only allows positive integer values.', 'wiz' ), '<code>' . leap_get_setting_label_by_id( $field_id ) . '</code>' ), 'error' );
            }
        }

        /**
         * Validate email inputs
         */
        if ( 'contact_email_to' == $field_id ) {
            if ( !is_email( $input ) ) {
                $input = '';
                add_settings_error( 'option-tree', 'invalid_email', sprintf( __( 'The input field for %s is not a valid email address.', 'wiz' ), '<code>' . leap_get_setting_label_by_id( $field_id ) . '</code>' ), 'error' );
            }
        }
    }


    return $input;
}

add_filter( 'ot_validate_setting', 'leap_validate_theme_options', 10, 3 );
