<?php

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

/*----------------------------------------
差し込みタグ一覧を取得
----------------------------------------*/
function immf_merge_tags($post_id) {

    $fields = get_post_meta(
        $post_id,
        'immf_fields',
        true
    );

    $tags = [
        '{inquiry_number}' => __(
            'Inquiry number',
            'im-mail-form'
        ),
        '{form_title}'     => __(
            'Form title',
            'im-mail-form'
        ),
    ];

    if (!is_array($fields)) {
        return $tags;
    }

    foreach ($fields as $field) {

        if (empty($field['name'])) {
            continue;
        }

        $tags[
            '{' . $field['name'] . '}'
        ] = $field['label'] ?: $field['name'];

    }

    $tags['{all_fields}'] = __(
        'All fields (labels and values)',
        'im-mail-form'
    );

    return $tags;

}


/*----------------------------------------
差し込みタグボタンを表示
----------------------------------------*/
function immf_merge_tag_buttons(
    $post_id,
    $target_id
) {

    $tags = immf_merge_tags($post_id);

    ?>
    <div class="im-mail-form-merge-tags">

        <?php foreach ($tags as $tag => $label) : ?>

            <button
                type="button"
                class="button button-small"
                data-merge-tag="<?php echo esc_attr($tag); ?>"
                data-merge-tag-target="<?php echo esc_attr($target_id); ?>"
            >
                <?php echo esc_html($label); ?>
            </button>

        <?php endforeach; ?>

    </div>
    <?php

}


/*----------------------------------------
メール設定の入力エラー項目を取得
----------------------------------------*/
function immf_invalid_mail_fields($post_id) {

    static $invalid_fields_by_post = [];

    if (
        isset(
            $invalid_fields_by_post[$post_id]
        )
    ) {
        return $invalid_fields_by_post[$post_id];
    }

    $transient_key =
        'immf_invalid_mail_fields_'
        . get_current_user_id()
        . '_'
        . $post_id;

    $invalid_fields = get_transient(
        $transient_key
    );

    if (!is_array($invalid_fields)) {
        $invalid_fields = [];
    }

    delete_transient(
        $transient_key
    );

    $invalid_fields_by_post[$post_id] =
        $invalid_fields;

    return $invalid_fields;
}


/*----------------------------------------
自動返信先に指定できるメール項目一覧を取得
----------------------------------------*/
function immf_reply_to_field_options($post_id) {

    $fields = get_post_meta(
        $post_id,
        'immf_fields',
        true
    );

    if (!is_array($fields)) {
        return [];
    }

    $email_fields = [];

    foreach ($fields as $field) {

        if (empty($field['name'])) {
            continue;
        }

        $field_type = $field['type'] ?? '';
        $field_validation = $field['validation'] ?? '';

        if (
            $field_type !== 'email' &&
            $field_validation !== 'email'
        ) {
            continue;
        }

        $email_fields[] = [
            'name'  => $field['name'],
            'label' => $field['label'] ?: $field['name'],
        ];

    }

    return $email_fields;

}


/*----------------------------------------
メールフォーム：自動返信メール設定メタボックス登録
----------------------------------------*/
function immf_add_contact_form_reply_mail_meta_box() {

    add_meta_box(
        'im_mail_form_reply_mail',
        __(
            'Auto-reply Email Settings',
            'im-mail-form'
        ),
        'immf_reply_mail_meta_box_callback',
        'im_mail_form',
        'normal',
        'default'
    );

}

add_action(
    'add_meta_boxes',
    'immf_add_contact_form_reply_mail_meta_box'
);


/*----------------------------------------
メールフォーム：管理者向け確認メール設定メタボックス登録
----------------------------------------*/
function immf_add_contact_form_admin_mail_meta_box() {

    add_meta_box(
        'im_mail_form_admin_mail',
        __(
            'Admin Email Settings',
            'im-mail-form'
        ),
        'immf_admin_mail_meta_box_callback',
        'im_mail_form',
        'normal',
        'default'
    );

}

add_action(
    'add_meta_boxes',
    'immf_add_contact_form_admin_mail_meta_box'
);


/*----------------------------------------
メールフォーム：送信完了画面設定メタボックス登録
----------------------------------------*/
function immf_add_contact_form_complete_meta_box() {

    add_meta_box(
        'im_mail_form_complete',
        __(
            'Completion Screen Settings',
            'im-mail-form'
        ),
        'immf_complete_meta_box_callback',
        'im_mail_form',
        'normal',
        'default'
    );

}

add_action(
    'add_meta_boxes',
    'immf_add_contact_form_complete_meta_box'
);


/*----------------------------------------
メールフォーム：自動返信メール設定表示
----------------------------------------*/
function immf_reply_mail_meta_box_callback($post) {

    $invalid_fields =
        immf_invalid_mail_fields(
            $post->ID
        );

    $use_reply = get_post_meta(
        $post->ID,
        'immf_use_reply',
        true
    );

    $use_reply_input_key =
        'immf_use_reply_input_'
        . get_current_user_id()
        . '_'
        . $post->ID;

    $use_reply_input = get_transient(
        $use_reply_input_key
    );

    if ($use_reply_input !== false) {

        $use_reply = $use_reply_input;

        delete_transient(
            $use_reply_input_key
        );
    }

    $reply_from_name = get_post_meta(
        $post->ID,
        'immf_reply_from_name',
        true
    );

    $reply_from = get_post_meta(
        $post->ID,
        'immf_reply_from',
        true
    );

    $reply_bcc = get_post_meta(
        $post->ID,
        'immf_reply_bcc',
        true
    );

    $reply_subject = get_post_meta(
        $post->ID,
        'immf_reply_subject',
        true
    );

    $reply_body = get_post_meta(
        $post->ID,
        'immf_reply_body',
        true
    );

    $reply_to_field = get_post_meta(
        $post->ID,
        'immf_reply_to_field',
        true
    );

    $email_fields = immf_reply_to_field_options(
        $post->ID
    );

    /*
    * 保存値がない場合は、既存フォームとの互換性のため
    * 先頭のメール項目を選択状態にします。
    */
    if (
        $reply_to_field === '' &&
        !empty($email_fields)
    ) {
        $reply_to_field = $email_fields[0]['name'];
    }

    ?>

   <table
        class="form-table"
        role="presentation"
        data-invalid-mail-fields="<?php
        echo esc_attr(
            implode(
                ' ',
                $invalid_fields
            )
        );
        ?>"
    >
        <tbody>

            <tr>
                <th scope="row">
                    <?php esc_html_e(
                        'Auto-reply',
                        'im-mail-form'
                    ); ?>
                </th>
                <td>
                    <label>
                        <input
                            type="checkbox"
                            name="im_mail_form_use_reply"
                            value="1"
                            data-reply-toggle
                            <?php checked($use_reply, '1'); ?>
                        >
                        <?php esc_html_e(
                            'Send an auto-reply email',
                            'im-mail-form'
                        ); ?>
                    </label>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-reply-to-field">
                        <?php esc_html_e(
                            'Auto-reply recipient field',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                            data-reply-required-mark
                            <?php echo $use_reply === '1' ? '' : 'hidden'; ?>
                        >*</span>
                    </label>
                </th>
                <td>
                    <select
                        id="im-mail-form-reply-to-field"
                        name="im_mail_form_reply_to_field"
                        class="regular-text"
                        data-reply-to-field-select
                        <?php disabled(empty($email_fields)); ?>
                    >

                        <?php foreach ($email_fields as $email_field) : ?>

                            <option
                                value="<?php echo esc_attr($email_field['name']); ?>"
                                <?php selected($reply_to_field, $email_field['name']); ?>
                            >
                                <?php echo esc_html(
                                    $email_field['label']
                                    . ' ('
                                    . $email_field['name']
                                    . ')'
                                ); ?>
                            </option>

                        <?php endforeach; ?>

                    </select>

                    <p class="description">
                        <?php esc_html_e(
                            'Select the email field that receives the auto-reply.',
                            'im-mail-form'
                        ); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-reply-from-name">
                        <?php esc_html_e(
                            'Sender name',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                            data-reply-required-mark
                            <?php echo $use_reply === '1' ? '' : 'hidden'; ?>
                        >*</span>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        id="im-mail-form-reply-from-name"
                        name="im_mail_form_reply_from_name"
                        value="<?php echo esc_attr($reply_from_name); ?>"
                        class="regular-text"
                    >
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-reply-from">
                        <?php esc_html_e(
                            'From address',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                            data-reply-required-mark
                            <?php echo $use_reply === '1' ? '' : 'hidden'; ?>
                        >*</span>
                    </label>
                </th>
                <td>
                    <input
                        type="email"
                        id="im-mail-form-reply-from"
                        name="im_mail_form_reply_from"
                        value="<?php echo esc_attr($reply_from); ?>"
                        class="regular-text"
                    >

                    <p class="description">
                        <?php esc_html_e(
                            'An email address on the same domain as the site is recommended.',
                            'im-mail-form'
                        ); ?><br>
                        <?php esc_html_e(
                            'If you use another domain, configure an authenticated SMTP service.',
                            'im-mail-form'
                        ); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-reply-bcc">
                        BCC
                    </label>
                </th>

                <td>
                    <input
                        type="text"
                        id="im-mail-form-reply-bcc"
                        name="im_mail_form_reply_bcc"
                        value="<?php echo esc_attr($reply_bcc); ?>"
                        class="regular-text"
                    >

                    <p class="description">
                        <?php esc_html_e(
                            'A copy of the auto-reply email is sent to these addresses.',
                            'im-mail-form'
                        ); ?><br>
                        <?php esc_html_e(
                            'Separate multiple addresses with commas.',
                            'im-mail-form'
                        ); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-reply-subject">
                        <?php esc_html_e(
                            'Subject',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                            data-reply-required-mark
                            <?php echo $use_reply === '1' ? '' : 'hidden'; ?>
                        >*</span>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        id="im-mail-form-reply-subject"
                        name="im_mail_form_reply_subject"
                        value="<?php echo esc_attr($reply_subject); ?>"
                        class="large-text"
                    >
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-reply-body">
                        <?php esc_html_e(
                            'Email body',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                            data-reply-required-mark
                            <?php echo $use_reply === '1' ? '' : 'hidden'; ?>
                        >*</span>
                    </label>
                </th>
                <td>
                    <textarea
                        id="im-mail-form-reply-body"
                        name="im_mail_form_reply_body"
                        rows="12"
                        class="large-text"
                    ><?php echo esc_textarea($reply_body); ?></textarea>
                    <?php
                    immf_merge_tag_buttons(
                        $post->ID,
                        'im-mail-form-reply-body'
                    );
                    ?>
                    <ul class="description">
                        <li>
                            <?php esc_html_e(
                                '* Individual merge tags output only the submitted value.',
                                'im-mail-form'
                            ); ?>
                        </li>
                        <li>
                            <?php esc_html_e(
                                '* The “All fields (labels and values)” tag outputs every field label and submitted value.',
                                'im-mail-form'
                            ); ?>
                        </li>
                    </ul>
                </td>
            </tr>

        </tbody>
    </table>

    <?php
}


/*----------------------------------------
メールフォーム：管理者向けメール設定表示
----------------------------------------*/
function immf_admin_mail_meta_box_callback($post) {

    $invalid_fields =
        immf_invalid_mail_fields(
            $post->ID
        );

    $use_admin_mail = get_post_meta(
        $post->ID,
        'immf_use_admin_mail',
        true
    );

    $admin_to = get_post_meta(
        $post->ID,
        'immf_admin_to',
        true
    );

    $admin_from_name = get_post_meta(
        $post->ID,
        'immf_admin_from_name',
        true
    );

    $admin_from = get_post_meta(
        $post->ID,
        'immf_admin_from',
        true
    );

    $admin_cc = get_post_meta(
        $post->ID,
        'immf_admin_cc',
        true
    );

    $admin_bcc = get_post_meta(
        $post->ID,
        'immf_admin_bcc',
        true
    );

    $admin_subject = get_post_meta(
        $post->ID,
        'immf_admin_subject',
        true
    );

    $admin_body = get_post_meta(
        $post->ID,
        'immf_admin_body',
        true
    );

    ?>

    <table
        class="form-table"
        role="presentation"
        data-invalid-mail-fields="<?php
        echo esc_attr(
            implode(
                ' ',
                $invalid_fields
            )
        );
        ?>"
    >
        <tbody>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-admin-to">
                        <?php esc_html_e(
                            'To (admin address)',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                        >*</span>
                    </label>
                </th>
                <td>
                    <input
                        type="email"
                        id="im-mail-form-admin-to"
                        name="im_mail_form_admin_to"
                        value="<?php echo esc_attr($admin_to); ?>"
                        class="regular-text"
                        required
                    >
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-admin-from-name">
                        <?php esc_html_e(
                            'Sender name',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                        >*</span>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        id="im-mail-form-admin-from-name"
                        name="im_mail_form_admin_from_name"
                        value="<?php echo esc_attr($admin_from_name); ?>"
                        class="regular-text"
                        required
                    >
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-admin-from">
                        <?php esc_html_e(
                            'From address',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                        >*</span>
                    </label>
                </th>
                <td>
                    <input
                        type="email"
                        id="im-mail-form-admin-from"
                        name="im_mail_form_admin_from"
                        value="<?php echo esc_attr($admin_from); ?>"
                        class="regular-text"
                        required
                    >

                    <p class="description">
                        <?php esc_html_e(
                            'An email address on the same domain as the site is recommended.',
                            'im-mail-form'
                        ); ?><br>
                        <?php esc_html_e(
                            'If you use another domain, configure an authenticated SMTP service.',
                            'im-mail-form'
                        ); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-admin-cc">
                        CC
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        id="im-mail-form-admin-cc"
                        name="im_mail_form_admin_cc"
                        value="<?php echo esc_attr($admin_cc); ?>"
                        class="regular-text"
                    >

                    <p class="description">
                        <?php esc_html_e(
                            'Separate multiple addresses with commas.',
                            'im-mail-form'
                        ); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-admin-bcc">
                        BCC
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        id="im-mail-form-admin-bcc"
                        name="im_mail_form_admin_bcc"
                        value="<?php echo esc_attr($admin_bcc); ?>"
                        class="regular-text"
                    >

                    <p class="description">
                        <?php esc_html_e(
                            'Separate multiple addresses with commas.',
                            'im-mail-form'
                        ); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-admin-subject">
                        <?php esc_html_e(
                            'Subject',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                        >*</span>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        id="im-mail-form-admin-subject"
                        name="im_mail_form_admin_subject"
                        value="<?php echo esc_attr($admin_subject); ?>"
                        class="large-text"
                        required
                    >
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-admin-body">
                        <?php esc_html_e(
                            'Email body',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                        >*</span>
                    </label>
                </th>
                <td>
                    <textarea
                        id="im-mail-form-admin-body"
                        name="im_mail_form_admin_body"
                        rows="12"
                        class="large-text"
                        required
                    ><?php echo esc_textarea($admin_body); ?></textarea>
                    <?php
                    immf_merge_tag_buttons(
                        $post->ID,
                        'im-mail-form-admin-body'
                    );
                    ?>
                    <ul class="description">
                        <li>
                            <?php esc_html_e(
                                '* Individual merge tags output only the submitted value.',
                                'im-mail-form'
                            ); ?>
                        </li>
                        <li>
                            <?php esc_html_e(
                                '* The “All fields (labels and values)” tag outputs every field label and submitted value.',
                                'im-mail-form'
                            ); ?>
                        </li>
                    </ul>
                </td>
            </tr>

        </tbody>
    </table>

    <?php
}

/*----------------------------------------
メールフォーム：送信完了画面設定表示
----------------------------------------*/
function immf_complete_meta_box_callback($post) {

    $invalid_fields =
        immf_invalid_mail_fields(
            $post->ID
        );

    $redirect_enabled = get_post_meta(
        $post->ID,
        'immf_redirect_enabled',
        true
    );

    $redirect_url = get_post_meta(
        $post->ID,
        'immf_redirect_url',
        true
    );

    $complete_message = get_post_meta(
        $post->ID,
        'immf_complete_message',
        true
    );

    if ($complete_message === '') {

        $default_templates =
            immf_default_templates();

        $complete_message =
            $default_templates['complete_message'];

    }

    /*----------------------------------------
    バリデーションエラー時の入力内容を復元
    ----------------------------------------*/
    $complete_settings_key =
        'immf_complete_settings_'
        . get_current_user_id()
        . '_'
        . $post->ID;

    $complete_settings = get_transient(
        $complete_settings_key
    );

    if (is_array($complete_settings)) {

        $redirect_enabled =
            $complete_settings['redirect_enabled'] ?? '0';

        $redirect_url =
            $complete_settings['redirect_url'] ?? '';

        $complete_message =
            $complete_settings['complete_message'] ?? '';

        delete_transient(
            $complete_settings_key
        );
    }
    ?>

    <table
        class="form-table"
        role="presentation"
        data-invalid-mail-fields="<?php
        echo esc_attr(
            implode(
                ' ',
                $invalid_fields
            )
        );
        ?>"
    >
        <tbody>

            <tr>
                <th scope="row">
                    <?php esc_html_e(
                        'Redirect',
                        'im-mail-form'
                    ); ?>
                </th>
                <td>
                    <label>
                        <input
                            type="checkbox"
                            name="im_mail_form_redirect_enabled"
                            value="1"
                            data-redirect-toggle
                            <?php checked($redirect_enabled, '1'); ?>
                        >
                        <?php esc_html_e(
                            'Redirect to a specified URL after submission',
                            'im-mail-form'
                        ); ?>
                    </label>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-redirect-url">
                        <?php esc_html_e(
                            'Redirect URL',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                            data-redirect-required-mark
                            <?php echo $redirect_enabled === '1' ? '' : 'hidden'; ?>
                        >*</span>
                    </label>
                </th>
                <td>
                    <input
                        type="url"
                        id="im-mail-form-redirect-url"
                        name="im_mail_form_redirect_url"
                        value="<?php echo esc_attr($redirect_url); ?>"
                        class="large-text"
                        <?php disabled($redirect_enabled, '1', false); ?>
                    >

                    <p class="description">
                        <?php esc_html_e(
                            'Used only when redirect is enabled.',
                            'im-mail-form'
                        ); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="im-mail-form-complete-message">
                        <?php esc_html_e(
                            'Completion message',
                            'im-mail-form'
                        ); ?>
                        <span
                            class="im-mail-form-admin__required"
                            aria-label="<?php esc_attr_e(
                                'Required',
                                'im-mail-form'
                            ); ?>"
                            data-complete-message-required-mark
                            <?php echo $redirect_enabled === '1' ? 'hidden' : ''; ?>
                        >*</span>
                    </label>
                </th>
                <td>
                    <textarea
                        id="im-mail-form-complete-message"
                        name="im_mail_form_complete_message"
                        rows="10"
                        class="large-text"
                    ><?php echo esc_textarea($complete_message); ?></textarea>
                    <?php
                    immf_merge_tag_buttons(
                        $post->ID,
                        'im-mail-form-complete-message'
                    );
                    ?>
                    <ul class="description">
                        <li>
                            <?php esc_html_e(
                                '* Individual merge tags output only the submitted value.',
                                'im-mail-form'
                            ); ?>
                        </li>
                        <li>
                            <?php esc_html_e(
                                '* The “All fields (labels and values)” tag outputs every field label and submitted value.',
                                'im-mail-form'
                            ); ?>
                        </li>
                        <li>
                            <?php esc_html_e(
                                '* HTML is allowed.',
                                'im-mail-form'
                            ); ?>
                        </li>
                        <li>
                            <?php esc_html_e(
                                '* This message is not displayed when redirect is enabled.',
                                'im-mail-form'
                            ); ?>
                        </li>
                    </ul>
                </td>
            </tr>

        </tbody>
    </table>

    <?php
}