<?php

if (!defined('ABSPATH')) {
    exit;
}

/*----------------------------------------
メールフォーム：ショートコード
----------------------------------------*/
function immf_shortcode($atts) {

    $atts = shortcode_atts(
        [
            'id' => '',
        ],
        $atts,
        'im_mail_form'
    );

    $form_id = sanitize_key(
        $atts['id']
    );

    if ($form_id === '') {
        return '';
    }

    $forms = get_posts([
        'post_type'      => 'im_mail_form',
        'post_status'    => 'publish',
        'posts_per_page' => 1,
        'meta_key'       => 'immf_id',
        'meta_value'     => $form_id,
    ]);

    if (empty($forms)) {
        return '';
    }

    $post_id = $forms[0]->ID;


    /*----------------------------------------
    確認画面の使用設定を取得
    ----------------------------------------*/
    $use_confirm = get_post_meta(
        $post_id,
        'immf_use_confirm',
        true
    );

    $confirm_button_label = get_post_meta(
        $post_id,
        'immf_confirm_button_label',
        true
    );

    if (
        !metadata_exists(
            'post',
            $post_id,
            'immf_confirm_button_label'
        )
    ) {
        $confirm_button_label = __(
            'Confirm',
            'im-mail-form'
        );
    }

    $back_button_label = get_post_meta(
        $post_id,
        'immf_back_button_label',
        true
    );

    if (
        !metadata_exists(
            'post',
            $post_id,
            'immf_back_button_label'
        )
    ) {
        $back_button_label = __(
            'Edit',
            'im-mail-form'
        );
    }

    $submit_button_label = get_post_meta(
        $post_id,
        'immf_submit_button_label',
        true
    );

    if (
        !metadata_exists(
            'post',
            $post_id,
            'immf_submit_button_label'
        )
    ) {
        $submit_button_label = __(
            'Submit',
            'im-mail-form'
        );
    }


    /*----------------------------------------
    必須項目の表記を取得
    ----------------------------------------*/
    $required_label = get_post_meta(
        $post_id,
        'immf_required_label',
        true
    );

    if (
        !metadata_exists(
            'post',
            $post_id,
            'immf_required_label'
        )
    ) {
        $required_label = _x(
            '*',
            'Default required field label',
            'im-mail-form'
        );
    }

    /*----------------------------------------
    フォーム項目を取得
    ----------------------------------------*/
    $fields = get_post_meta(
        $post_id,
        'immf_fields',
        true
    );

    if (
        !is_array($fields) ||
        empty($fields)
    ) {
        return '';
    }

    /*----------------------------------------
    送信完了情報を取得
    ----------------------------------------*/
    $completed_post_id = 0;
    $completed_inquiry_number = '';
    $completed_display_data = [];

    if (
        isset(
            // The single-use completion token only reads temporary display data.
            // phpcs:disable WordPress.Security.NonceVerification.Recommended
            $_GET['im_mail_form_completed']
        )
    ) {

        $completion_token =
            sanitize_text_field(
                wp_unslash(
                    $_GET[
                        'im_mail_form_completed'
                    ]
                )
            );
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        $completion_key =
            'immf_completed_'
            . $completion_token;

        $completion_data =
            get_transient(
                $completion_key
            );

        if (
            is_array($completion_data) &&
            isset($completion_data['post_id'])
        ) {

            $completed_post_id = absint(
                $completion_data['post_id']
            );

            if (
                isset(
                    $completion_data['inquiry_number']
                )
            ) {
                $completed_inquiry_number =
                    sanitize_text_field(
                        $completion_data[
                            'inquiry_number'
                        ]
                    );
            }

            if (
                isset(
                    $completion_data['display_data']
                )
                && is_array(
                    $completion_data['display_data']
                )
            ) {
                $completed_display_data =
                    $completion_data['display_data'];
            }

            /*
            * 現在のフォームの完了情報だけ削除する
            */
            if (
                $completed_post_id === (int) $post_id
            ) {

                delete_transient(
                    $completion_key
                );
            }
        }
    }

    /*----------------------------------------
    送信結果を取得
    ----------------------------------------*/
    $submission = $GLOBALS['immf_submission'] ?? [];

    $submitted_data = [];
    $errors = [];
    $success = false;
    $mail_error = false;
    $confirm = false;
    $confirm_files = [];
    $form_timestamp = 0;

    /*----------------------------------------
    完了情報が現在のフォームと一致するか確認
    ----------------------------------------*/
    if (
        $completed_post_id > 0 &&
        $completed_post_id === (int) $post_id
    ) {
        $success = true;
    }

    if (
        isset($submission['post_id']) &&
        (int) $submission['post_id'] === (int) $post_id
    ) {
        $submitted_data = is_array(
            $submission['data'] ?? null
        )
            ? $submission['data']
            : [];

        $errors = is_array(
            $submission['errors'] ?? null
        )
            ? $submission['errors']
            : [];

        $success =
            $success ||
            (
                ($submission['success'] ?? false) === true
            );

        $mail_error =
            ($submission['mail_error'] ?? false) === true;

        $confirm =
            ($submission['confirm'] ?? false) === true;

        $confirm_files = is_array(
            $submission['confirm_files'] ?? null
        )
            ? $submission['confirm_files']
            : [];

        $form_timestamp = absint(
            $submission['form_timestamp'] ?? 0
        );
    }

ob_start();
?>

<?php if ($success) : ?>

    <?php
    $complete_message = get_post_meta(
        $post_id,
        'immf_complete_message',
        true
    );

    $complete_message =
        immf_replace_contact_form_mail_tags(
            $complete_message,
            $completed_display_data
        );
    ?>

    <div
        class="im-mail-form__success"
        id="im-mail-form-<?php echo esc_attr($form_id); ?>"
        role="status"
    >
        <?php
        echo wp_kses_post(
            wpautop($complete_message)
        );
        ?>
    </div>

    <?php return ob_get_clean(); ?>

<?php endif; ?>


<?php
/*----------------------------------------
確認画面
----------------------------------------*/
if ($confirm) :
?>

        <form
            class="im-mail-form-confirm"
            id="im-mail-form-<?php echo esc_attr($form_id); ?>"
            method="post"
            action="<?php echo esc_url(
                get_permalink()
            ); ?>"
            enctype="multipart/form-data"
            novalidate
        >

        <?php
        wp_nonce_field(
            'im_mail_form_submit_' . $post_id,
            'im_mail_form_nonce'
        );
        ?>

        <input
            type="hidden"
            name="im_mail_form_post_id"
            value="<?php echo esc_attr($post_id); ?>"
        >

        <p class="im-mail-form-confirm__message">
            <?php
            esc_html_e(
                'Your message will be sent with the following information.',
                'im-mail-form'
            );
            ?>
            <br>
            <?php
            esc_html_e(
                'Please review the details before submitting.',
                'im-mail-form'
            );
            ?>
        </p>

        <dl class="im-mail-form-confirm__list">

            <?php foreach ($fields as $field) : ?>

                <?php
                $label = $field['label'] ?? '';
                $name = $field['name'] ?? '';
                $type = $field['type'] ?? 'text';
                $options = $field['options'] ?? '';

                // フィールド名がない項目は表示しない
                if ($name === '') {
                    continue;
                }

                // hidden項目は確認画面に表示しない
                if ($type === 'hidden') {
                    continue;
                }

                // 入力値を取得
                $value =
                    $submitted_data[$name] ?? '';

                /*----------------------------------------
                選択肢の値と表示名を取得
                ----------------------------------------*/
                $option_labels = [];

                if (
                    in_array(
                        $type,
                        [
                            'select',
                            'radio',
                            'checkbox',
                        ],
                        true
                    )
                ) {

                    $option_values = preg_split(
                        '/\r\n|\r|\n/',
                        $options
                    );

                    foreach ($option_values as $option) {

                        $option = trim($option);

                        if ($option === '') {
                            continue;
                        }

                        $parts = array_map(
                            'trim',
                            explode(
                                '|',
                                $option,
                                2
                            )
                        );

                        $option_value = $parts[0];

                        $option_label = $parts[1]
                            ?? $parts[0];

                        $option_labels[$option_value] =
                            $option_label;
                    }
                }

                // 確認画面用の表示値を生成
                if (
                    is_array($value) &&
                    array_is_list($value)
                ) {

                    $display_values = array_map(
                        static function ($item) use (
                            $option_labels
                        ) {

                            return $option_labels[$item]
                                ?? sanitize_text_field(
                                    $item
                                );
                        },
                        $value
                    );

                    $display_value = implode(
                        '、',
                        $display_values
                    );

                } elseif (is_scalar($value)) {

                    $display_value =
                        $option_labels[$value]
                        ?? (string) $value;

                } else {

                    // 添付ファイルなど
                    $display_value = '';
                }
                ?>

                <dt class="im-mail-form-confirm__label">
                    <?php echo esc_html($label); ?>
                </dt>

                <dd class="im-mail-form-confirm__value">

                    <?php if ($type === 'file') : ?>

                        <?php
                        $file_name = is_array($value)
                            ? sanitize_file_name(
                                $value['name'] ?? ''
                            )
                            : '';
                        ?>

                        <?php if ($file_name !== '') : ?>

                            <?php echo esc_html($file_name); ?>

                        <?php else : ?>

                            <span class="im-mail-form-confirm__empty">
                                <?php
                                esc_html_e(
                                    'Not selected',
                                    'im-mail-form'
                                );
                                ?>
                            </span>

                        <?php endif; ?>

                    <?php elseif ($display_value !== '') : ?>

                        <?php
                        echo nl2br(
                            esc_html($display_value)
                        );
                        ?>

                    <?php else : ?>

                        <span class="im-mail-form-confirm__empty">
                            <?php
                            esc_html_e(
                                'Not entered',
                                'im-mail-form'
                            );
                            ?>
                        </span>

                    <?php endif; ?>

                </dd>

            <?php endforeach; ?>

        </dl>

            <?php
            /*----------------------------------------
            入力値を送信処理へ引き継ぐ
            ----------------------------------------*/
            foreach ($fields as $field) :

                $name = $field['name'] ?? '';
                $type = $field['type'] ?? 'text';

                // フィールド名がない項目は処理しない
                if ($name === '') {
                    continue;
                }

                // ファイル項目は後で別処理を追加する
                if ($type === 'file') {
                    continue;
                }

                // 入力された値を取得
                $value =
                    $submitted_data[$name] ?? '';
            ?>


                <?php
                /*----------------------------------------
                チェックボックスなどの複数値
                ----------------------------------------*/
                if (is_array($value)) :
                ?>

                <?php foreach ($value as $item) : ?>

                    <input
                        type="hidden"
                        name="im_mail_form_data[<?php echo esc_attr($name); ?>][]"
                        value="<?php echo esc_attr($item); ?>"
                    >

                <?php endforeach; ?>


                <?php
                /*----------------------------------------
                通常の入力値
                ----------------------------------------*/
                elseif (is_scalar($value)) :
                ?>

                    <input
                        type="hidden"
                        name="im_mail_form_data[<?php echo esc_attr($name); ?>]"
                        value="<?php echo esc_attr((string) $value); ?>"
                    >

                <?php endif; ?>

            <?php endforeach; ?>

            <?php
            /*----------------------------------------
            一時保存した添付ファイル情報を引き継ぐ
            ----------------------------------------*/
            foreach ($confirm_files as $name => $file) :

                $file_name = isset($file['name'])
                    ? sanitize_file_name($file['name'])
                    : '';

                $file_token = isset($file['token'])
                    ? sanitize_key($file['token'])
                    : '';

                if (
                    $name === '' ||
                    $file_name === '' ||
                    $file_token === ''
                ) {
                    continue;
                }
            ?>

                <input
                    type="hidden"
                    name="im_mail_form_confirm_files[<?php echo esc_attr($name); ?>][name]"
                    value="<?php echo esc_attr($file_name); ?>"
                >

                <input
                    type="hidden"
                    name="im_mail_form_confirm_files[<?php echo esc_attr($name); ?>][token]"
                    value="<?php echo esc_attr($file_token); ?>"
                >

            <?php endforeach; ?>

            <input
                type="hidden"
                name="website"
                value=""
            >

            <input
                type="hidden"
                name="im_mail_form_timestamp"
                value="<?php echo esc_attr($form_timestamp); ?>"
            >

            <div class="im-mail-form-confirm__actions">

                <button
                    type="submit"
                    name="im_mail_form_action"
                    value="back"
                    class="im-mail-form-confirm__back"
                >
                    <?php
                    echo esc_html(
                        $back_button_label
                    );
                    ?>
                </button>

                <button
                    type="submit"
                    name="im_mail_form_action"
                    value="submit"
                    class="im-mail-form-confirm__submit"
                >
                    <?php
                    echo esc_html(
                        $submit_button_label
                    );
                    ?>
                </button>

            </div>

    </form>

    <?php return ob_get_clean(); ?>

<?php endif; ?>


<form
    class="im-mail-form"
    id="im-mail-form-<?php echo esc_attr($form_id); ?>"
    method="post"
    action="<?php echo esc_url(
        get_permalink()
    ); ?>"
    enctype="multipart/form-data"
    novalidate
>

    <?php
    wp_nonce_field(
        'im_mail_form_submit_' . $post_id,
        'im_mail_form_nonce'
    );
    ?>

    <?php if ($mail_error) : ?>

        <div
            class="im-mail-form__mail-error"
            role="alert"
        >
            <p>
                <?php
                esc_html_e(
                    'Failed to send the email. Please wait a moment and try again.',
                    'im-mail-form'
                );
                ?>
            </p>
        </div>

    <?php endif; ?>

    <?php if (!empty($errors)) : ?>

        <div
            class="im-mail-form__error-summary"
            role="alert"
        >
            <p>
                <?php
                esc_html_e(
                    'There are errors in your submission. Please review each field.',
                    'im-mail-form'
                );
                ?>
            </p>
        </div>

    <?php endif; ?>

    <input
        type="hidden"
        name="im_mail_form_post_id"
        value="<?php echo esc_attr($post_id); ?>"
    >

    <input
        type="hidden"
        name="im_mail_form_action"
        value="<?php echo esc_attr(
            $use_confirm === '1'
                ? 'confirm'
                : 'submit'
        ); ?>"
    >

<?php foreach ($fields as $field) : ?>

    <?php
    /*----------------------------------------
    フォーム項目の設定値を取得
    ----------------------------------------*/
    $label = $field['label'] ?? '';
    $name = $field['name'] ?? '';
    $type = $field['type'] ?? 'text';

    // HTMLブロックは入力欄を生成せず、保存済みHTMLをそのまま出力する
    if ($type === 'html') {
        ?>
        <div class="im-mail-form__html-block">
            <?php echo wp_kses_post($field['html_content'] ?? ''); ?>
        </div>
        <?php
        continue;
    }

    $description = $field['description'] ?? '';
    $placeholder = $field['placeholder'] ?? '';
    $required = ($field['required'] ?? '0') === '1';
    $min_length = $field['min_length'] ?? '';
    $max_length = $field['max_length'] ?? '';

    $max_file_size = isset(
        $field['max_file_size']
    ) && $field['max_file_size'] !== ''
        ? absint($field['max_file_size'])
        : '';

    $allowed_file_types = isset(
        $field['allowed_file_types']
    ) && is_array(
        $field['allowed_file_types']
    )
        ? $field['allowed_file_types']
        : [];

    $options = $field['options'] ?? '';
    $hidden_value = $field['hidden_value'] ?? '';

    // フィールド名がない項目は出力しない
    if ($name === '') {
        continue;
    }


    /*----------------------------------------
    入力エラーの有無を判定
    ----------------------------------------*/
    $has_error = isset(
        $errors[$name]
    );


    /*----------------------------------------
    ファイル形式の設定を取得
    ----------------------------------------*/
    $file_type_settings = [
        'jpeg' => [
            'label' => 'JPG / JPEG',
            'accept' => '.jpg,.jpeg',
        ],
        'png' => [
            'label' => 'PNG',
            'accept' => '.png',
        ],
        'webp' => [
            'label' => 'WebP',
            'accept' => '.webp',
        ],
        'pdf' => [
            'label' => 'PDF',
            'accept' => '.pdf',
        ],
    ];

    $accepts = [];
    $file_type_labels = [];

    foreach (
        $allowed_file_types as $file_type
    ) {

        if (
            !isset(
                $file_type_settings[$file_type]
            )
        ) {
            continue;
        }

        $accepts[] =
            $file_type_settings[$file_type]['accept'];

        $file_type_labels[] =
            $file_type_settings[$file_type]['label'];

    }

    $accept = implode(
        ',',
        $accepts
    );

    $file_type_label = implode(
        '、',
        $file_type_labels
    );


    /*----------------------------------------
    ファイル設定の案内文を取得
    ----------------------------------------*/
    $file_setting_note = '';

    if (
        $file_type_label !== ''
    ) {

        if ($max_file_size !== '') {
            $file_setting_note = sprintf(
                /* translators: 1: Supported file formats, 2: Maximum file size in megabytes. */
                __(
                    'Supported formats: %1$s (maximum %2$s MB)',
                    'im-mail-form'
                ),
                $file_type_label,
                $max_file_size
            );

        } else {
            $file_setting_note = sprintf(
                /* translators: %s: Supported file formats. */
                __(
                    'Supported formats: %s',
                    'im-mail-form'
                ),
                $file_type_label
            );
        }
    }

    /*----------------------------------------
    送信後に復元する入力値を取得
    ----------------------------------------*/
    $submitted_value =
        $submitted_data[$name] ?? '';

    $submitted_values =
        is_array($submitted_value)
            ? $submitted_value
            : [];

    $confirmed_file =
        isset($confirm_files[$name]) &&
        is_array($confirm_files[$name])
            ? $confirm_files[$name]
            : [];

    $confirmed_file_name = isset(
        $confirmed_file['name']
    )
        ? sanitize_file_name(
            $confirmed_file['name']
        )
        : '';

    $confirmed_file_token = isset(
        $confirmed_file['token']
    )
        ? sanitize_key(
            $confirmed_file['token']
        )
        : '';

    ?>


    <?php
    /*----------------------------------------
    hidden項目
    ----------------------------------------*/
    if ($type === 'hidden') :
    ?>

        <input
            type="hidden"
            name="im_mail_form_data[<?php echo esc_attr($name); ?>]"
            value="<?php echo esc_attr($hidden_value); ?>"
        >

        <?php continue; ?>

    <?php endif; ?>


    <div
        class="im-mail-form__field<?php
        echo $has_error
            ? ' im-mail-form__field--error'
            : '';
        ?>"
    >

        <?php
        /*----------------------------------------
        項目ラベル
        ----------------------------------------*/
        ?>
        <label
            class="im-mail-form__label"
            for="im-mail-form-<?php echo esc_attr($name); ?>"
        >
            <?php echo esc_html($label); ?>

            <?php if (
                $required &&
                $required_label !== ''
            ) : ?>

                <span class="im-mail-form__required">
                    <?php echo esc_html($required_label); ?>
                </span>

            <?php endif; ?>
        </label>


        <div class="im-mail-form__control">

            <?php
            /*----------------------------------------
            テキストエリア
            ----------------------------------------*/
            if ($type === 'textarea') :
            ?>

                <textarea
                    id="im-mail-form-<?php echo esc_attr($name); ?>"
                    name="im_mail_form_data[<?php echo esc_attr($name); ?>]"
                    class="im-mail-form__textarea"
                    <?php if ($has_error) : ?>
                        aria-invalid="true"
                        aria-describedby="im-mail-form-<?php echo esc_attr($name); ?>-error"
                    <?php endif; ?>
                    <?php if ($placeholder !== '') : ?>
                        placeholder="<?php echo esc_attr($placeholder); ?>"
                    <?php endif; ?>
                    <?php if ($min_length !== '') : ?>
                        minlength="<?php echo esc_attr($min_length); ?>"
                    <?php endif; ?>
                    <?php if ($max_length !== '') : ?>
                        maxlength="<?php echo esc_attr($max_length); ?>"
                    <?php endif; ?>
                ><?php echo esc_textarea($submitted_value); ?></textarea>


            <?php
            /*----------------------------------------
            セレクトボックス
            ----------------------------------------*/
            elseif ($type === 'select') :
            ?>

                <select
                    id="im-mail-form-<?php echo esc_attr($name); ?>"
                    name="im_mail_form_data[<?php echo esc_attr($name); ?>]"
                    class="im-mail-form__select"
                    <?php if ($has_error) : ?>
                        aria-invalid="true"
                        aria-describedby="im-mail-form-<?php echo esc_attr($name); ?>-error"
                    <?php endif; ?>
                >

                    <option
                        value=""
                        <?php selected($submitted_value, ''); ?>
                    >
                        <?php
                        echo esc_html(
                            $placeholder !== ''
                                ? $placeholder
                                : __(
                                    'Please select',
                                    'im-mail-form'
                                )
                        );
                        ?>
                    </option>

                    <?php
                    $option_values = preg_split(
                        '/\r\n|\r|\n/',
                        $options
                    );
                    ?>

                    <?php foreach ($option_values as $option) : ?>

                    <?php
                    $option = trim($option);

                    if ($option === '') {
                        continue;
                    }

                    $parts = array_map(
                        'trim',
                        explode(
                            '|',
                            $option,
                            2
                        )
                    );

                    $option_value = $parts[0];

                    $option_label = $parts[1]
                        ?? $parts[0];
                    ?>

                    <option
                        value="<?php echo esc_attr($option_value); ?>"
                        <?php selected($submitted_value, $option_value); ?>
                    >
                        <?php echo esc_html($option_label); ?>
                    </option>

                    <?php endforeach; ?>

                </select>


            <?php
            /*----------------------------------------
            ラジオボタン・チェックボックス
            ----------------------------------------*/
            elseif (
                $type === 'radio' ||
                $type === 'checkbox'
            ) :
            ?>

                <div
                    class="im-mail-form__choices"
                    role="group"
                    <?php if ($has_error) : ?>
                        aria-invalid="true"
                        aria-describedby="im-mail-form-<?php echo esc_attr($name); ?>-error"
                    <?php endif; ?>
                >

                    <?php
                    $option_values = preg_split(
                        '/\r\n|\r|\n/',
                        $options
                    );
                    ?>

                    <?php foreach ($option_values as $index => $option) : ?>

                        <?php
                        $option = trim($option);

                        if ($option === '') {
                            continue;
                        }

                        $parts = array_map(
                            'trim',
                            explode(
                                '|',
                                $option,
                                2
                            )
                        );

                        $option_value = $parts[0];

                        $option_label = $parts[1]
                            ?? $parts[0];

                        $choice_id =
                            'im-mail-form-'
                            . $name
                            . '-'
                            . $index;
                        ?>

                        <label
                            class="im-mail-form__choice"
                            for="<?php echo esc_attr($choice_id); ?>"
                        >

                            <input
                                type="<?php echo esc_attr($type); ?>"
                                id="<?php echo esc_attr($choice_id); ?>"
                                name="<?php
                                echo esc_attr(
                                    $type === 'checkbox'
                                        ? 'im_mail_form_data[' . $name . '][]'
                                        : 'im_mail_form_data[' . $name . ']'
                                );
                                ?>"
                                value="<?php echo esc_attr($option_value); ?>"

                                <?php if ($type === 'checkbox') : ?>

                                    <?php
                                    checked(
                                        in_array(
                                            $option_value,
                                            $submitted_values,
                                            true
                                        )
                                    );
                                    ?>

                                <?php else : ?>

                                    <?php
                                    checked(
                                        $submitted_value,
                                        $option_value
                                    );
                                    ?>

                                <?php endif; ?>
                            >

                            <span>
                                <?php echo esc_html($option_label); ?>
                            </span>

                        </label>

                    <?php endforeach; ?>

                </div>


            <?php
            /*----------------------------------------
            通常のinput項目
            ----------------------------------------*/
            else :
            ?>

                <input
                    type="<?php echo esc_attr($type); ?>"
                    id="im-mail-form-<?php echo esc_attr($name); ?>"
                    name="<?php
                    echo esc_attr(
                        $type === 'file'
                            ? 'im_mail_form_files[' . $name . ']'
                            : 'im_mail_form_data[' . $name . ']'
                    );
                    ?>"
                    class="im-mail-form__input"

                    <?php if ($has_error) : ?>
                        aria-invalid="true"
                        aria-describedby="im-mail-form-<?php echo esc_attr($name); ?>-error"
                    <?php endif; ?>

                    <?php if ($type === 'file') : ?>
                        data-contact-form-file-input
                    <?php endif; ?>

                    <?php if (
                        $type === 'file' &&
                        $confirmed_file_name !== '' &&
                        $confirmed_file_token !== ''
                    ) : ?>
                        hidden
                    <?php endif; ?>

                    <?php if (
                        $type === 'file' &&
                        $accept !== ''
                    ) : ?>
                        accept="<?php echo esc_attr($accept); ?>"
                    <?php endif; ?>

                    <?php if ($type !== 'file') : ?>
                        value="<?php echo esc_attr($submitted_value); ?>"
                    <?php endif; ?>

                    <?php if ($placeholder !== '') : ?>
                        placeholder="<?php echo esc_attr($placeholder); ?>"
                    <?php endif; ?>

                    <?php if (
                        $type === 'text' &&
                        $max_length !== ''
                    ) : ?>
                        maxlength="<?php echo esc_attr($max_length); ?>"
                    <?php endif; ?>
                >

                <?php if (
                    $type === 'file' &&
                    $confirmed_file_name !== '' &&
                    $confirmed_file_token !== ''
                ) : ?>

                    <input
                        type="hidden"
                        name="im_mail_form_confirm_files[<?php echo esc_attr($name); ?>][name]"
                        value="<?php echo esc_attr($confirmed_file_name); ?>"
                    >

                    <input
                        type="hidden"
                        name="im_mail_form_confirm_files[<?php echo esc_attr($name); ?>][token]"
                        value="<?php echo esc_attr($confirmed_file_token); ?>"
                    >

                    <input
                        type="hidden"
                        name="im_mail_form_remove_confirm_files[<?php echo esc_attr($name); ?>]"
                        value="0"
                        data-confirmed-file-remove-value
                    >

                    <div
                        class="im-mail-form__selected-file"
                        data-confirmed-file
                    >
                        <span>
                            <?php
                            esc_html_e(
                                'Selected:',
                                'im-mail-form'
                            );
                            ?>
                            <?php echo esc_html($confirmed_file_name); ?>
                        </span>

                        <button
                            type="button"
                            class="im-mail-form__selected-file-remove"
                            data-confirmed-file-remove
                        >
                            <?php
                            esc_html_e(
                                'Remove',
                                'im-mail-form'
                            );
                            ?>
                        </button>
                    </div>

                <?php endif; ?>

            <?php endif; ?>

        </div>


        <?php
        /*----------------------------------------
        補足説明
        ----------------------------------------*/
        if ($description !== '') :
        ?>

            <p class="im-mail-form__description">
                <?php echo nl2br(esc_html($description)); ?>
            </p>

        <?php endif; ?>


        <?php
        /*----------------------------------------
        入力エラー
        ----------------------------------------*/
        if (isset($errors[$name])) :
        ?>

            <p
                class="im-mail-form__error"
                id="im-mail-form-<?php echo esc_attr($name); ?>-error"
                role="alert"
            >
                <?php echo esc_html($errors[$name]); ?>
            </p>

        <?php endif; ?>

    </div>

<?php endforeach; ?>

    <div
        class="im-mail-form__honeypot"
        aria-hidden="true"
        hidden
    >
        <label for="im-mail-form-website">
            Website
        </label>

        <input
            type="text"
            id="im-mail-form-website"
            name="website"
            value=""
            tabindex="-1"
            autocomplete="off"
        >
    </div>

    <input
        type="hidden"
        name="im_mail_form_timestamp"
        value="<?php echo esc_attr(time()); ?>"
    >

    <div class="im-mail-form__actions">

        <button
            type="submit"
            class="im-mail-form__submit"
        >
            <?php if ($use_confirm === '1') : ?>

                <?php
                echo esc_html(
                    $confirm_button_label
                );
                ?>

            <?php else : ?>

                <?php
                echo esc_html(
                    $submit_button_label
                );
                ?>

            <?php endif; ?>
        </button>

    </div>

</form>

<?php
return ob_get_clean();

}

add_shortcode(
    'im_mail_form',
    'immf_shortcode'
);