<?php

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

/*----------------------------------------
テンプレート設定を登録
----------------------------------------*/
function immf_register_template_settings() {

    register_setting(
        'immf_template_settings',
        immf_template_option_name(),
        [
            'type'              => 'array',
            'sanitize_callback' =>
                'immf_sanitize_template_settings',
            'default'           =>
                immf_default_templates(),
        ]
    );

    register_setting(
        'immf_template_settings',
        'immf_delete_data_on_uninstall',
        [
            'type'              => 'boolean',
            'sanitize_callback' =>
                'rest_sanitize_boolean',
            'default'           => false,
        ]
    );
}

add_action(
    'admin_init',
    'immf_register_template_settings'
);


/*----------------------------------------
テンプレート設定をサニタイズ
----------------------------------------*/
function immf_sanitize_template_settings(
    $input
) {

    if (!is_array($input)) {
        return immf_default_templates();
    }

    $input = array_merge(
        immf_get_templates(),
        $input
    );

    $templates = [
        'admin_to' => sanitize_email(
            $input['admin_to'] ?? ''
        ),

        'admin_from_name' => sanitize_text_field(
            $input['admin_from_name'] ?? ''
        ),

        'admin_from' => sanitize_email(
            $input['admin_from'] ?? ''
        ),

        'admin_cc' =>
            immf_sanitize_email_list(
                $input['admin_cc'] ?? ''
            ),

        'admin_bcc' =>
            immf_sanitize_email_list(
                $input['admin_bcc'] ?? ''
            ),

        'admin_subject' => sanitize_text_field(
            $input['admin_subject'] ?? ''
        ),

        'admin_body' => sanitize_textarea_field(
            $input['admin_body'] ?? ''
        ),

        'reply_from_name' => sanitize_text_field(
            $input['reply_from_name'] ?? ''
        ),

        'reply_from' => sanitize_email(
            $input['reply_from'] ?? ''
        ),

        'reply_bcc' =>
            immf_sanitize_email_list(
                $input['reply_bcc'] ?? ''
            ),

        'reply_subject' => sanitize_text_field(
            $input['reply_subject'] ?? ''
        ),

        'reply_body' => sanitize_textarea_field(
            $input['reply_body'] ?? ''
        ),

        'complete_message' => wp_kses_post(
            $input['complete_message'] ?? ''
        ),
    ];

    $errors = [];

    $required_fields = [
        'admin_from_name'  => __(
            'Admin email sender name',
            'im-mail-form'
        ),
        'admin_subject'    => __(
            'Admin email subject',
            'im-mail-form'
        ),
        'admin_body'       => __(
            'Admin email body',
            'im-mail-form'
        ),
        'reply_from_name'  => __(
            'Auto-reply email sender name',
            'im-mail-form'
        ),
        'reply_subject'    => __(
            'Auto-reply email subject',
            'im-mail-form'
        ),
        'reply_body'       => __(
            'Auto-reply email body',
            'im-mail-form'
        ),
        'complete_message' => __(
            'Completion message',
            'im-mail-form'
        ),
    ];

    foreach (
        $required_fields
        as $field_name => $field_label
    ) {

        if ($templates[$field_name] === '') {
            $errors[] = sprintf(
                /* translators: %s: Field label. */
                __(
                    'Please enter %s.',
                    'im-mail-form'
                ),
                $field_label
            );
        }
    }

    $email_fields = [
        'admin_to'   => __(
            'Admin email recipient address',
            'im-mail-form'
        ),
        'admin_from' => __(
            'Admin email sender address',
            'im-mail-form'
        ),
        'reply_from' => __(
            'Auto-reply email sender address',
            'im-mail-form'
        ),
    ];

    foreach (
        $email_fields
        as $field_name => $field_label
    ) {

        if (
            $templates[$field_name] === '' ||
            !is_email(
                $templates[$field_name]
            )
        ) {
            $errors[] = sprintf(
                /* translators: %s: Template setting field label. */
                __(
                    'Please enter a valid email address for %s.',
                    'im-mail-form'
                ),
                $field_label
            );
        }
    }

    $email_list_fields = [
        'admin_cc'  => __(
            'Admin email Cc',
            'im-mail-form'
        ),
        'admin_bcc' => __(
            'Admin email Bcc',
            'im-mail-form'
        ),
        'reply_bcc' => __(
            'Auto-reply email Bcc',
            'im-mail-form'
        ),
    ];

    foreach (
        $email_list_fields
        as $field_name => $field_label
    ) {

        if (
            immf_has_invalid_email_list(
                $input[$field_name] ?? ''
            )
        ) {
            $errors[] = sprintf(
                /* translators: %s: Template setting field label. */
                __(
                    '%s contains an invalid email address.',
                    'im-mail-form'
                ),
                $field_label
            );
        }
    }

    if (!empty($errors)) {

        foreach (
            $errors
            as $error_number => $error
        ) {

            add_settings_error(
                'immf_templates',
                'immf_template_error_'
                    . $error_number,
                $error,
                'error'
            );
        }

        return immf_get_templates();
    }

    return $templates;
}


/*----------------------------------------
新規フォームへテンプレートを反映
----------------------------------------*/
function immf_apply_templates_to_new_form(
    $post_id,
    $post,
    $update
) {

    if (
        $update ||
        !$post instanceof WP_Post ||
        $post->post_type !== 'im_mail_form'
    ) {
        return;
    }

    $templates = immf_get_templates();

    $initial_settings = [
        'immf_use_reply' =>
            '0',

        'immf_reply_from_name' =>
            $templates['reply_from_name'],

        'immf_reply_from' =>
            $templates['reply_from'],

        'immf_reply_bcc' =>
            $templates['reply_bcc'],

        'immf_reply_subject' =>
            $templates['reply_subject'],

        'immf_reply_body' =>
            $templates['reply_body'],

        'immf_admin_to' =>
            $templates['admin_to'],

        'immf_admin_from_name' =>
            $templates['admin_from_name'],

        'immf_admin_from' =>
            $templates['admin_from'],

        'immf_admin_cc' =>
            $templates['admin_cc'],

        'immf_admin_bcc' =>
            $templates['admin_bcc'],

        'immf_admin_subject' =>
            $templates['admin_subject'],

        'immf_admin_body' =>
            $templates['admin_body'],

        'immf_redirect_enabled' =>
            '0',

        'immf_complete_message' =>
            $templates['complete_message'],
    ];

    foreach (
        $initial_settings
        as $meta_key => $meta_value
    ) {

        add_post_meta(
            $post_id,
            $meta_key,
            $meta_value,
            true
        );
    }

}

add_action(
    'wp_after_insert_post',
    'immf_apply_templates_to_new_form',
    10,
    3
);


/*----------------------------------------
テンプレート設定サブメニューを登録
----------------------------------------*/
function immf_add_template_settings_page() {

    add_submenu_page(
        'edit.php?post_type=im_mail_form',
        __(
            'Template Settings',
            'im-mail-form'
        ),
        __(
            'Template Settings',
            'im-mail-form'
        ),
        'manage_options',
        'im-mail-form-template-settings',
        'immf_render_template_settings_page'
    );

}

add_action(
    'admin_menu',
    'immf_add_template_settings_page'
);


/*----------------------------------------
テンプレート設定画面を表示
----------------------------------------*/
function immf_render_template_settings_page() {

    $templates = immf_get_templates();

    $template_option_name =
        immf_template_option_name();

    $delete_data_on_uninstall = (bool) get_option(
        'immf_delete_data_on_uninstall',
        false
    );

    ?>

    <div class="wrap">

        <?php immf_render_admin_header(); ?>

        <h1>
            <?php
            esc_html_e(
                'Template Settings',
                'im-mail-form'
            );
            ?>
        </h1>

        <p>
            <?php
            esc_html_e(
                'Set the default values applied to newly created mail forms.',
                'im-mail-form'
            );
            ?>
        </p>

        <?php settings_errors(); ?>

        <form
            action="options.php"
            method="post"
            class="im-mail-form-template-settings"
        >

            <?php
            settings_fields(
                'immf_template_settings'
            );
            ?>

            <section
                class="im-mail-form-template-settings__section"
            >
                <div class="im-mail-form-setting-header">
                <h2>
                    <?php
                    esc_html_e(
                        'Auto-Reply Email',
                        'im-mail-form'
                    );
                    ?>
                </h2>
                </div>

                <table
                    class="form-table"
                    role="presentation"
                >
                    <tbody>

                        <tr>
                            <th scope="row">
                                <label for="im-mail-form-template-reply-from-name">
                                    <?php
                                    esc_html_e(
                                        'Sender Name',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    id="im-mail-form-template-reply-from-name"
                                    name="<?php echo esc_attr($template_option_name); ?>[reply_from_name]"
                                    value="<?php echo esc_attr($templates['reply_from_name']); ?>"
                                    class="regular-text"
                                    required
                                >
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="im-mail-form-template-reply-from">
                                    <?php
                                    esc_html_e(
                                        'From (Sender Address)',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="email"
                                    id="im-mail-form-template-reply-from"
                                    name="<?php echo esc_attr($template_option_name); ?>[reply_from]"
                                    value="<?php echo esc_attr($templates['reply_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-template-reply-bcc">
                                    <?php
                                    esc_html_e(
                                        'Bcc',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    id="im-mail-form-template-reply-bcc"
                                    name="<?php echo esc_attr($template_option_name); ?>[reply_bcc]"
                                    value="<?php echo esc_attr($templates['reply_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-template-reply-subject">
                                    <?php
                                    esc_html_e(
                                        'Subject',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    id="im-mail-form-template-reply-subject"
                                    name="<?php echo esc_attr($template_option_name); ?>[reply_subject]"
                                    value="<?php echo esc_attr($templates['reply_subject']); ?>"
                                    class="large-text"
                                    required
                                >
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="im-mail-form-template-reply-body">
                                    <?php
                                    esc_html_e(
                                        'Email Body',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <textarea
                                    id="im-mail-form-template-reply-body"
                                    name="<?php echo esc_attr($template_option_name); ?>[reply_body]"
                                    rows="12"
                                    class="large-text"
                                    required
                                ><?php echo esc_textarea($templates['reply_body']); ?></textarea>

                                <ul class="description">
                                    <li>
                                        <?php
                                        esc_html_e(
                                            '* You can use {form_title}, {inquiry_number}, and {all_fields}.',
                                            'im-mail-form'
                                        );
                                        ?>
                                    </li>
                                    <li>
                                        <?php
                                        esc_html_e(
                                            '* {all_fields} outputs the label and submitted value of every field.',
                                            'im-mail-form'
                                        );
                                        ?>
                                    </li>
                                </ul>
                            </td>
                        </tr>

                    </tbody>
                </table>
            </section>

            <section
                class="im-mail-form-template-settings__section"
            >
                <div class="im-mail-form-setting-header">
                <h2>
                    <?php
                    esc_html_e(
                        'Admin Email',
                        'im-mail-form'
                    );
                    ?>
                </h2>
                </div>

                <table
                    class="form-table"
                    role="presentation"
                >
                    <tbody>

                        <tr>
                            <th scope="row">
                                <label for="im-mail-form-template-admin-to">
                                    <?php
                                    esc_html_e(
                                        'To (Recipient Address)',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="email"
                                    id="im-mail-form-template-admin-to"
                                    name="<?php echo esc_attr($template_option_name); ?>[admin_to]"
                                    value="<?php echo esc_attr($templates['admin_to']); ?>"
                                    class="regular-text"
                                    required
                                >
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="im-mail-form-template-admin-from-name">
                                    <?php
                                    esc_html_e(
                                        'Sender Name',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    id="im-mail-form-template-admin-from-name"
                                    name="<?php echo esc_attr($template_option_name); ?>[admin_from_name]"
                                    value="<?php echo esc_attr($templates['admin_from_name']); ?>"
                                    class="regular-text"
                                    required
                                >
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="im-mail-form-template-admin-from">
                                    <?php
                                    esc_html_e(
                                        'From (Sender Address)',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="email"
                                    id="im-mail-form-template-admin-from"
                                    name="<?php echo esc_attr($template_option_name); ?>[admin_from]"
                                    value="<?php echo esc_attr($templates['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-template-admin-cc">
                                    <?php
                                    esc_html_e(
                                        'Cc',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    id="im-mail-form-template-admin-cc"
                                    name="<?php echo esc_attr($template_option_name); ?>[admin_cc]"
                                    value="<?php echo esc_attr($templates['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-template-admin-bcc">
                                    <?php
                                    esc_html_e(
                                        'Bcc',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    id="im-mail-form-template-admin-bcc"
                                    name="<?php echo esc_attr($template_option_name); ?>[admin_bcc]"
                                    value="<?php echo esc_attr($templates['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-template-admin-subject">
                                    <?php
                                    esc_html_e(
                                        'Subject',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    id="im-mail-form-template-admin-subject"
                                    name="<?php echo esc_attr($template_option_name); ?>[admin_subject]"
                                    value="<?php echo esc_attr($templates['admin_subject']); ?>"
                                    class="large-text"
                                    required
                                >
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="im-mail-form-template-admin-body">
                                    <?php
                                    esc_html_e(
                                        'Email Body',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <textarea
                                    id="im-mail-form-template-admin-body"
                                    name="<?php echo esc_attr($template_option_name); ?>[admin_body]"
                                    rows="12"
                                    class="large-text"
                                    required
                                ><?php echo esc_textarea($templates['admin_body']); ?></textarea>

                                <ul class="description">
                                    <li>
                                        <?php
                                        esc_html_e(
                                            '* You can use {form_title}, {inquiry_number}, and {all_fields}.',
                                            'im-mail-form'
                                        );
                                        ?>
                                    </li>
                                    <li>
                                        <?php
                                        esc_html_e(
                                            '* {all_fields} outputs the label and submitted value of every field.',
                                            'im-mail-form'
                                        );
                                        ?>
                                    </li>
                                </ul>
                            </td>
                        </tr>

                    </tbody>
                </table>
            </section>

            <section
                class="im-mail-form-template-settings__section"
            >
                <div class="im-mail-form-setting-header">
                <h2>
                    <?php
                    esc_html_e(
                        'Completion Screen',
                        'im-mail-form'
                    );
                    ?>
                </h2>
                </div>

                <table
                    class="form-table"
                    role="presentation"
                >
                    <tbody>

                        <tr>
                            <th scope="row">
                                <label for="im-mail-form-template-complete-message">
                                    <?php
                                    esc_html_e(
                                        'Completion Message',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>
                            </th>
                            <td>
                                <textarea
                                    id="im-mail-form-template-complete-message"
                                    name="<?php echo esc_attr($template_option_name); ?>[complete_message]"
                                    rows="10"
                                    class="large-text"
                                    required
                                ><?php echo esc_textarea($templates['complete_message']); ?></textarea>

                                <ul class="description">
                                    <li>
                                        <?php
                                        esc_html_e(
                                            '* You can use {form_title}, {inquiry_number}, and {all_fields}.',
                                            'im-mail-form'
                                        );
                                        ?>
                                    </li>
                                    <li>
                                        <?php
                                        esc_html_e(
                                            '* {all_fields} outputs the label and submitted value of every field.',
                                            'im-mail-form'
                                        );
                                        ?>
                                    </li>
                                    <li>
                                        <?php
                                        esc_html_e(
                                            '* HTML is supported.',
                                            'im-mail-form'
                                        );
                                        ?>
                                    </li>
                                </ul>
                            </td>
                        </tr>

                    </tbody>
                </table>
            </section>

            <section
                class="im-mail-form-template-settings__section"
            >
                <div class="im-mail-form-setting-header">
                <h2>
                    <?php
                    esc_html_e(
                        'Data Removal',
                        'im-mail-form'
                    );
                    ?>
                </h2>
                </div>
                <table
                    class="form-table"
                    role="presentation"
                >
                    <tbody>

                        <tr>
                            <th scope="row">
                                <?php
                                esc_html_e(
                                    'When Uninstalling the Plugin',
                                    'im-mail-form'
                                );
                                ?>
                            </th>
                            <td>
                                <input
                                    type="hidden"
                                    name="immf_delete_data_on_uninstall"
                                    value="0"
                                >

                                <label>
                                    <input
                                        type="checkbox"
                                        name="immf_delete_data_on_uninstall"
                                        value="1"
                                        <?php checked(
                                            $delete_data_on_uninstall
                                        ); ?>
                                    >
                                    <?php
                                    esc_html_e(
                                        'Delete all created forms and settings',
                                        'im-mail-form'
                                    );
                                    ?>
                                </label>

                                <p class="description">
                                    <?php
                                    esc_html_e(
                                        'When enabled, all forms and settings are permanently deleted when the plugin is uninstalled. Deactivating the plugin does not delete them.',
                                        'im-mail-form'
                                    );
                                    ?>
                                </p>
                            </td>
                        </tr>

                    </tbody>
                </table>
            </section>

            <?php
            submit_button(
                __(
                    'Save Templates',
                    'im-mail-form'
                )
            );
            ?>

        </form>

    </div>

    <?php
}