<?php
/**
 * EMC Admin Settings Class.
 */

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

if ( ! class_exists( 'emc_admin_settings' ) ) :

/**
 * emc_admin_settings
 */
class emc_admin_settings {

    /**
	 * Get settings array
	 * @param $memory_limit limit ressources usage (for activation only)
	 * @return array
	 */
	public function get_settings($memory_limit = false) {}

    /**
	 * Add setting to tabs.
	 */
	public function add_tab( $tabs ) {
		$tabs[ $this->id ] = $this->label;

		return $tabs;
	}

    /**
	 * Output admin fields.
	 */
	public function output() {
        $sections = $this->get_settings();
        foreach ($sections as $section) {
            echo '<h2>'.$section['section_title'].'</h2>';
            if (isset($section['section_description'])) {
                echo '<p>'.$section['section_description'].'</p>';
            }
            ?>
                <table class="form-table">
                    <tbody>
                    <?php
                    foreach ($section['fields'] as $field) {
                        $this->output_fields($field);
                    }
                    ?>
                    </tbody>
                </table>
            <?php
        }
    }

    /**
	 * Output settings tabs.
	 */
	public function output_subtabs() {
        $subtabs = $this->get_subtabs();
        $current_subtab = isset($_GET['subtab']) ? $_GET['subtab'] : '';
        $array_keys = array_keys( $subtabs );

        echo '<ul class="subsubsub">';
        foreach ( $subtabs as $id => $label ) {
			echo '<li><a href="' . admin_url( 'admin.php?page=envoimoinscher-settings&tab=' . $this->id . '&subtab=' . sanitize_title( $id ) ) . '" class="' . ( $current_subtab == $id ? 'current' : '' ) . '">' . $label . '</a> ' . ( end( $array_keys ) == $id ? '' : '|' ) . ' </li>';
		}
        echo '</ul><br class="clear" />';
    }

    /**
	 * Output admin fields.
	 *
	 * @param array $field
	 */
	public function output_fields( $field ) {
        if ( ! isset( $field['type'] ) ) {
            return;
        }
        if ( ! isset( $field['id'] ) ) {
            $field['id'] = '';
        }
        if ( ! isset( $field['title'] ) ) {
            $field['title'] = isset( $field['name'] ) ? $field['name'] : '';
        }
        if ( ! isset( $field['class'] ) ) {
            $field['class'] = '';
        }
        if ( ! isset( $field['css'] ) ) {
            $field['css'] = '';
        }
        if ( ! isset( $field['default'] ) ) {
            $field['default'] = '';
        }
        if ( ! isset( $field['desc'] ) ) {
            $field['desc'] = '';
        }
        if ( ! isset( $field['desc_tip'] ) ) {
            $field['desc_tip'] = false;
        }
        if ( ! isset( $field['placeholder'] ) ) {
            $field['placeholder'] = '';
        }

        // Custom attribute handling
        $field['attributes'] = array();

        if ( ! empty( $field['custom_attributes'] ) && is_array( $field['custom_attributes'] ) ) {
            foreach ( $field['custom_attributes'] as $attribute => $attribute_value ) {
                $field['attributes'][] = esc_attr( $attribute ) . '="' . esc_attr( $attribute_value ) . '"';
            }
        }

        // Description handling
        $field = self::get_field_description( $field );

        // Output field if method exists
        if (method_exists($this, 'output_'.$field['type'].'_field' )) {
            call_user_func(array($this, 'output_'.$field['type'].'_field'), $field);
        }
    }

    /**
	 * Output text field.
	 *
	 * @param $field
	 */
	public function output_text_field($field) {
        if (isset($field['donotsave']) && $field['donotsave'] === true) {
            $option_value = $field['default'];
        } else {
            $option_value = get_option( $field['id'], $field['default'] );
        }
        ?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label for="<?php echo esc_attr( $field['id'] ); ?>"><?php echo esc_html( $field['title'] ); ?></label>
                <?php echo $field['tooltip_html']; ?>
            </th>
            <td class="forminp forminp-<?php echo sanitize_title( $field['type'] ) ?>">
                <input
                name="<?php echo esc_attr( $field['id'] ); ?>"
                id="<?php echo esc_attr( $field['id'] ); ?>"
                type="<?php echo esc_attr( $field['type'] ); ?>"
                style="<?php echo esc_attr( $field['css'] ); ?>"
                value="<?php echo esc_attr( $option_value ); ?>"
                class="<?php echo esc_attr( $field['class'] ); ?>"
                placeholder="<?php echo esc_attr( $field['placeholder'] ); ?>"
                <?php echo implode( ' ', $field['attributes'] ); ?>
                /> <?php echo $field['description']; ?>
            </td>
        </tr>
        <?php
    }

    /**
	 * Output password field.
	 *
	 * @param $field
	 */
	public function output_password_field($field) {
        return $this->output_text_field($field);
    }

    /**
	 * Output radio_inline field.
	 *
	 * @param $field
	 */
	public function output_radio_inline_field($field) {
        if (isset($field['donotsave']) && $field['donotsave'] === true) {
            $option_value = $field['default'];
        } else {
            $option_value = get_option( $field['id'], $field['default'] );
        }
        ?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label for="<?php echo esc_attr( $field['id'] ); ?>"><?php echo esc_html( $field['title'] ); ?></label>
                <?php echo $field['tooltip_html']; ?>
            </th>
            <td class="forminp forminp-<?php echo sanitize_title( $field['type'] ) ?>">
                <fieldset>
                    <?php echo $field['description']; ?>
                    <ul style="margin-top:2px;">
                    <?php
                        foreach ( $field['options'] as $key => $val ) {
                            ?>
                            <li style="float:left;padding-right:20px;">
                                <label><input
                                    name="<?php echo esc_attr( $field['id'] ); ?>"
                                    value="<?php echo $key; ?>"
                                    type="radio"
                                    style="<?php echo esc_attr( $field['css'] ); ?>"
                                    class="<?php echo esc_attr( $field['class'] ); ?>"
                                    <?php echo implode( ' ', $field['attributes'] ); ?>
                                    <?php checked( $key, $option_value ); ?>
                                    /> <?php echo $val ?></label>
                            </li>
                            <?php
                        }
                    ?>
                    </ul>
                </fieldset>
            </td>
        </tr>
        <?php
    }

    /**
	 * Output checkbox field.
	 *
	 * @param $field
	 */
	public function output_checkbox_field($field) {
        if (isset($field['donotsave']) && $field['donotsave'] === true) {
            $option_value = $field['default'];
        } else {
            $option_value = get_option( $field['id'], $field['default'] );
        }
        ?>
        <tr valign="top">
            <th scope="row" class="titledesc"><?php echo esc_html( $field['title'] ) ?></th>
            <td class="forminp forminp-<?php echo sanitize_title( $field['type'] ) ?>">
                <fieldset>
                    <label for="<?php echo $field['id'] ?>">
                        <input
                            name="<?php echo esc_attr( $field['id'] ); ?>"
                            id="<?php echo esc_attr( $field['id'] ); ?>"
                            type="checkbox"
                            class="<?php echo esc_attr( isset( $field['class'] ) ? $field['class'] : '' ); ?>"
                            value="1"
                            <?php checked( $option_value, 'yes'); ?>
                            <?php echo implode( ' ', $field['attributes'] ); ?>
                        /> <?php echo $field['description']; ?>
                    </label> <?php echo $field['tooltip_html']; ?>
                </fieldset>
            </td>
        </tr>
        <?php
    }

    /**
	 * Output hidden select type field.
	 *
	 * @param $field
	 */
	public function output_hidden_select_field ($field){
		if (isset($field['donotsave']) && $field['donotsave'] === true) {
            $option_value = $field['default'];
        } else {
            $option_value = get_option( $field['id'], $field['default'] );
        }
        ?><tr valign="top" class="<?php echo sanitize_title( $field['type'] ) ?>">
            <th scope="row" class="titledesc">
                <label for="<?php echo esc_attr( $field['id'] ); ?>"><?php echo esc_html( $field['title'] ); ?></label>
            </th>
            <td class="forminp forminp-<?php echo sanitize_title( $field['type'] ) ?>">
                <select
                    name="<?php echo esc_attr( $field['id'] ); ?>"
                    id="<?php echo esc_attr( $field['id'] ); ?>"
                    style="<?php echo esc_attr( $field['css'] ); ?>"
                    class="<?php echo esc_attr( $field['class'] ); ?>"
                    <?php echo implode( ' ', $field['attributes'] ); ?>
                    >
                    <?php
                        foreach ( $field['options'] as $key => $val ) {
                            ?>
                            <option value="<?php echo esc_attr( $key ); ?>" <?php

                                if ( is_array( $option_value ) ) {
                                    selected( in_array( $key, $option_value ), true );
                                } else {
                                    selected( $option_value, $key );
                                }

                            ?>><?php echo $val ?></option>
                            <?php
                        }
                    ?>
               </select> <?php echo $field['description']; ?>
            </td>
        </tr><?php
	}


    /**
	 * Output multilingual text type field.
	 *
	 * @param $field
	 */
	public function output_multilingual_text_field ($field){

        if (isset($field['donotsave']) && $field['donotsave'] === true) {
            $option_value = $field['default'];
        } else {
            $option_value = get_option( $field['id'], $field['default'] );
        }

        // get installed languages
        $languages = get_available_languages();
        array_push($languages, 'en_US'); // 'en_US' is always added by default and not returned by get_available_languages

		?><tr valign="top" class="<?php echo sanitize_title( $field['type'] ) ?> multilingual_fieldset">
			<th scope="row" class="titledesc">
				<label for="<?php echo esc_attr( $field['id'][0] ); ?>"><?php echo esc_html( $field['title'] ); ?></label>
				<?php echo $field['tooltip_html']; ?>
			</th>
			<td class="forminp forminp-<?php echo sanitize_title( $field['type'] ) ?>">
                <?php
                    foreach ($languages as $key => $language) {
                        echo '<input type="text" class="multilingual_field multilingual_field_'.$language.'" name="'.$field['id'].'_'.$language.'" value="';
                        echo envoimoinscher_model::get_translation($option_value, $language, false).'" ';
                        if ($key != 0) {
                            echo 'style="display:none"';
                        }
                        echo '>';
                    }
                ?>
				<select class="multilingual_field_select">
                    <?php
                        foreach ($languages as $key => $language) {
                            echo '<option value="'.$language.'">'.substr($language, 0, 2).'</option>';
                        }
                    ?>
				</select>
                <div style="padding-top:15px"><?php echo ( $field['description'] ) ? $field['description'] : ''; ?></div>
			</td>
		</tr><?php
	}

    /**
	 * Output select type field.
	 *
	 * @param $field
	 */
	public function output_select_field ($field){
		if (isset($field['donotsave']) && $field['donotsave'] === true) {
            $option_value = $field['default'];
        } else {
            $option_value = get_option( $field['id'], $field['default'] );
        }

        ?><tr valign="top"">
            <th scope="row" class="titledesc">
                <label for="<?php echo esc_attr( $field['id'] ); ?>"><?php echo esc_html( $field['title'] ); ?></label>
                <?php echo $field['tooltip_html']; ?>
            </th>
            <td class="forminp forminp-<?php echo sanitize_title( $field['type'] ) ?>">
                <select
                    name="<?php echo esc_attr( $field['id'] ); ?>"
                    id="<?php echo esc_attr( $field['id'] ); ?>"
                    style="<?php echo esc_attr( $field['css'] ); ?>"
                    class="<?php echo esc_attr( $field['class'] ); ?>"
                    <?php echo implode( ' ', $field['attributes'] ); ?>
                    >
                    <?php
                        foreach ( $field['options'] as $key => $val ) {
                            ?>
                            <option value="<?php echo esc_attr( $key ); ?>" <?php

                                if ( is_array( $option_value ) ) {
                                    selected( in_array( $key, $option_value ), true );
                                } else {
                                    selected( $option_value, $key );
                                }

                            ?>><?php echo $val ?></option>
                            <?php
                        }
                    ?>
               </select> <?php echo $field['description']; ?>
            </td>
        </tr><?php
	}

    /**
	 * Output text field.
	 *
	 * @param $field
	 */
	public function output_float_field($field) {
        if (isset($field['donotsave']) && $field['donotsave'] === true) {
            $option_value = $field['default'];
        } else {
            $option_value = get_option( $field['id'], $field['default'] );
        }
        ?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label for="<?php echo esc_attr( $field['id'] ); ?>"><?php echo esc_html( $field['title'] ); ?></label>
                <?php echo $field['tooltip_html']; ?>
            </th>
            <td class="forminp forminp-<?php echo sanitize_title( $field['type'] ) ?>">
                <input
                name="<?php echo esc_attr( $field['id'] ); ?>"
                id="<?php echo esc_attr( $field['id'] ); ?>"
                type="<?php echo esc_attr( $field['type'] ); ?>"
                style="<?php echo esc_attr( $field['css'] ); ?>"
                value="<?php echo esc_attr( $option_value ); ?>"
                class="<?php echo esc_attr( $field['class'] ); ?> emc_input_decimal"
                placeholder="<?php echo esc_attr( $field['placeholder'] ); ?>"
                <?php echo implode( ' ', $field['attributes'] ); ?>
                /> <?php echo $field['description']; ?>
            </td>
        </tr>
        <?php
    }

    /**
	 * Process additional_output.
	 */
	public function additional_output() {}

    /**
	 * Process additional_output.
	 */
	public function validate_additional_output() {}

    /**
	 * Save admin fields.
	 */
	public function save() {
        $sections = $this->get_settings();
        foreach ($sections as $section) {
            foreach ($section['fields'] as $field) {
                if (method_exists($this, 'save_'.$field['type'].'_field')) {
                    call_user_func(array($this, 'save_'.$field['type'].'_field'), $field);
                }
            }
        }
        $notice = array(
            'type' => "simple-notice",
            'status' => 'success',
            'message' => 'Your settings have been saved.',
            'placeholders' => array(),
            'autodestruct' => 1
        );
        emc_admin_notices::add_custom_notice('settings_saved', $notice);
    }

    /**
	 * Save admin text fields.
	 */
	public function save_text_field($field) {
        if (!isset($_POST[$field['id']])) {
            return;
        }
        // check if required field
        if(isset($field['required']) && ($field['required'] == true) && (null == $_POST[$field['id']])) {
            $notice = array(
                'type' => "simple-notice",
                'status' => 'failure',
                'message' => '%s is a required field.',
                'placeholders' => array(
                    str_replace('*', '', $field['title'])
                ),
                'autodestruct' => 1
            );
            emc_admin_notices::add_custom_notice('required'.$field['id'], $notice);
        }

        $value = sanitize_text_field($_POST[$field['id']]);
        update_option($field['id'], $value);
        return;
    }

    /**
	 * Save admin password fields.
	 */
	public function save_password_field($field) {
        if (!isset($_POST[$field['id']])) {
            return;
        }
        $value = $_POST[$field['id']];
        update_option($field['id'], $value);
        return;
    }

    /**
	 * Save admin radio_inline fields.
	 */
	public function save_radio_inline_field($field) {
        if (!isset($_POST[$field['id']])) {
            return;
        }

        // check if required field
        if(isset($field['required']) && ($field['required'] == true) && (null == $_POST[$field['id']])) {
            $notice = array(
                'type' => "simple-notice",
                'status' => 'failure',
                'message' => '%s is a required field.',
                'placeholders' => array(
                    str_replace('*', '', $field['title'])
                ),
                'autodestruct' => 1
            );
            emc_admin_notices::add_custom_notice('required'.$field['id'], $notice);
        }
        $value = $_POST[$field['id']];
        update_option($field['id'], $value);
        return;
    }

    /**
	 * Save admin checkbox fields.
	 */
	public function save_checkbox_field($field) {
        $value = isset($_POST[$field['id']]) ? 'yes' : 'no';
        update_option($field['id'], $value);
        return;
    }

    /**
	 * Save admin hidden_select fields.
	 */
	public function save_hidden_select_field($field) {
        if (!isset($_POST[$field['id']])) {
            return;
        }
        $value = $_POST[$field['id']];
        update_option($field['id'], $value);
        return;
    }

	/**
	 * Save multilingual text type field.
	 */
	public function save_multilingual_text_field($field) {
        $multilingual_value = array();
        foreach ($_POST as $key => $value) {
			if (strpos($key, $field['id']."_") !== false) {
                $multilingual_value[str_replace($field['id']."_", "", $key)] = $value;
            }
		}
        update_option($field['id'], $multilingual_value);
	}

    /**
	 * Save admin select fields.
	 */
	public function save_select_field($field) {
        if (!isset($_POST[$field['id']])) {
            return;
        }
        $value = $_POST[$field['id']];
        update_option($field['id'], $value);
        return;
    }

    /**
	 * Save admin text fields.
	 */
	public function save_float_field($field) {
        if (!isset($_POST[$field['id']])) {
            return;
        }
        // check if required field
        if(isset($field['required']) && ($field['required'] == true) && (null == $_POST[$field['id']])) {
            $notice = array(
                'type' => "simple-notice",
                'status' => 'failure',
                'message' => '%s is a required field.',
                'placeholders' => array(
                    str_replace('*', '', $field['title'])
                ),
                'autodestruct' => 1
            );
            emc_admin_notices::add_custom_notice('required'.$field['id'], $notice);
        }
        
        if (null != $_POST[$field['id']]) {
            $value = (float)sanitize_text_field($_POST[$field['id']]);
        } else {
            $value = null; // sometimes we just want the option to remain null
        }
        update_option($field['id'], $value);
        return;
    }

    /**
	 * Helper function to get the formated description and tip HTML for a
	 * given form field.
	 *
	 * @param  array $field The form field value array
	 * @return array The description and tip as a 2 element array
	 */
	public static function get_field_description( $field ) {
		$field['description']  = '';
		$field['tooltip_html'] = '';

		if ( true === $field['desc_tip'] ) {
			$field['tooltip_html'] = $field['desc'];
		} elseif ( ! empty( $field['desc_tip'] ) ) {
			$field['description']  = $field['desc'];
			$field['tooltip_html'] = $field['desc_tip'];
		} elseif ( ! empty( $field['desc'] ) ) {
			$field['description']  = $field['desc'];
		}

		if ( $field['description'] && in_array( $field['type'], array( 'textarea', 'radio' ) ) ) {
			$field['description'] = '<p style="margin-top:0">' . wp_kses_post( $field['description'] ) . '</p>';
		} elseif ( $field['description'] && in_array( $field['type'], array( 'checkbox' ) ) ) {
			$field['description'] = wp_kses_post( $field['description'] );
		} elseif ( $field['description'] ) {
			$field['description'] = '<span class="description">' . wp_kses_post( $field['description'] ) . '</span>';
		}

		if ( $field['tooltip_html'] && in_array( $field['type'], array( 'checkbox' ) ) ) {
			$field['tooltip_html'] = '<p class="description">' . $field['tooltip_html'] . '</p>';
		} elseif ( $field['tooltip_html'] ) {
            if (function_exists('wc_help_tip')) {
                $field['tooltip_html'] = wc_help_tip( $field['tooltip_html'] );
            } else {
                $field['tooltip_html'] = '<img class="help_tip" data-tip="' . esc_attr( $field['tooltip_html'] ) . '" src="' . WC()->plugin_url() . '/assets/images/help.png" height="16" width="16" />';
            }
		}
		return $field;
	}

    /**
	 * Action buttons.
	 */
	public function action_buttons() {
       ?>
        <input name="save" class="button-primary" type="submit" value="<?php _e( 'Save changes', 'envoimoinscher' ); ?>" />
       <?php
    }

}

endif;
