<?php

defined('ABSPATH') || exit;

if (isset($_SERVER['REQUEST_METHOD']) && 'POST' == $_SERVER['REQUEST_METHOD']) {
    if (isset($_POST['action'])) {
        // Verificar nonce para segurança
        if (! isset($_POST['_wpnonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'save_settings_nonce')) {
            wp_die(esc_html(__('You do not have permission to do this.', 'lkn-wp-crowdfunding-extension')));
        }

        // Processar ações diferentes com base no botão clicado
        if (isset($_POST['action']) && sanitize_text_field(wp_unslash($_POST['action'])) === __('Save Settings', 'lkn-wp-crowdfunding-extension')) {
            $email_is_username = isset($_POST['email_username']) ? 1 : 0;
            $email_por_validacao = isset($_POST['email_validacao']) ? 1 : 0;
            $nonce_register = isset($_POST['nonce_register']) ? 1 : 0;
            $redirect_uri_pos_cadastro_id = isset($_POST['url_red_pos_cadastro']) ? intval($_POST['url_red_pos_cadastro']) : 0;
            $redirect_uri_envio_email_id = isset($_POST['url_red_envio_email']) ? intval($_POST['url_red_envio_email']) : 0;
            $redirect_uri_falha_email_id = isset($_POST['url_red_falha_email']) ? intval($_POST['url_red_falha_email']) : 0;

            $selected_template_id = isset($_POST['lkn_crowdfunding_custom_template_id']) ? intval($_POST['lkn_crowdfunding_custom_template_id']) : '';

            // Atualizar opções
            update_option('lkn_wpcf_email_is_username', $email_is_username);
            update_option('lkn_wpcf_registro_por_validacao', $email_por_validacao);
            update_option('wpcf_redurl', $redirect_uri_pos_cadastro_id ? get_permalink($redirect_uri_pos_cadastro_id) : '');
            update_option('lkn_wpcf_redurl_envio_email', $redirect_uri_envio_email_id ? get_permalink($redirect_uri_envio_email_id) : '');
            update_option('lkn_wpcf_redurl_falha_email', $redirect_uri_falha_email_id ? get_permalink($redirect_uri_falha_email_id) : '');
            update_option('lkn_crowdfunding_custom_template_id', $selected_template_id);

            add_settings_error('plugin_options', 'saved', __('Settings saved successfully.', 'lkn-wp-crowdfunding-extension'), 'updated');
        } elseif (isset($_POST['action']) && sanitize_text_field(wp_unslash($_POST['action'])) === __('Clear Email Options', 'lkn-wp-crowdfunding-extension')) {
            // Deletar todas as opções com os prefixos especificados
            global $wpdb;
            $prefixes = array('lkn_send_email_verification_', 'lkn_custom_email_verification_');
            $current_time = time();
            $one_day_ago = $current_time - 86400;

            foreach ($prefixes as $prefix) {
                $options = $wpdb->get_results($wpdb->prepare(
                    "SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE %s",
                    $prefix . '%'
                ));

                foreach ($options as $option) {
                    $option_data = maybe_unserialize($option->option_value);
                    if (isset($option_data['timestamp']) && $option_data['timestamp'] < $one_day_ago) {
                        delete_option($option->option_name);
                    }
                }
            }

            add_settings_error('plugin_options', 'cleared', __('All email verification options have been cleared!', 'lkn-wp-crowdfunding-extension'), 'updated');
        } elseif (isset($_POST['action']) && sanitize_text_field(wp_unslash($_POST['action'])) === __('Reset Settings', 'lkn-wp-crowdfunding-extension')) {
            // Resetar todas as configurações
            delete_option('lkn_wpcf_email_is_username');
            delete_option('lkn_wpcf_registro_por_validacao');
            // delete_option('wpcf_redurl');
            delete_option('lkn_crowdfunding_custom_template_id');
            delete_option('lkn_wpcf_redurl_envio_email');
            delete_option('lkn_wpcf_redurl_falha_email');

            add_settings_error('plugin_options', 'reset', __('All settings have been reset!', 'lkn-wp-crowdfunding-extension'), 'updated');
        } else {
            wp_die(esc_html(__('Invalid options.', 'lkn-wp-crowdfunding-extension')));
        }
    }
}


$settings_errors = get_settings_errors('plugin_options');

// Recuperar valores atuais
$saved_redirect_uri = get_option('wpcf_redurl');
$redirect_pos_cadastro = $saved_redirect_uri ? $saved_redirect_uri : '';

// Valor salvo na opção específica para redirecionamento de envio de email
$saved_redirect_uri_envio_email = get_option('lkn_wpcf_redurl_envio_email');
$saved_redirect_page_id_envio_email  = $saved_redirect_uri_envio_email ? $saved_redirect_uri_envio_email : '';

// Valor salvo na opção específica para redirecionamento de falha de envio de email
$saved_redirect_uri_falha_email = get_option('lkn_wpcf_redurl_falha_email');
$redirect_falha_email = $saved_redirect_uri_falha_email ? $saved_redirect_uri_falha_email : '';

$emailIsUsername = get_option('lkn_wpcf_email_is_username');
$is_checked = $emailIsUsername ? true : false;

$registroPorValidacao = get_option('lkn_wpcf_registro_por_validacao');
$is_checked_validacao = $registroPorValidacao ? true : false;

$pages = wpcf_function()->get_pages();
$page_array = array();
if (count($pages) > 0) {
    foreach ($pages as $page) {
        $page_array[$page->ID] = array(
            'title' => $page->post_title,
            'url' => get_permalink($page->ID)
        );
    }
}
$pages = $page_array;

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0">
    <title>
        <?php esc_html_e('Plugin Settings', 'lkn-wp-crowdfunding-extension'); ?>
    </title>
</head>

<body>
    <h2><?php esc_html_e('Plugin Settings', 'lkn-wp-crowdfunding-extension'); ?>
    </h2>
    <hr>
    <?php if ($settings_errors): ?>
        <?php foreach ($settings_errors as $error): ?>
            <div class="updated">
                <p><?php echo esc_html($error['message']); ?>
                </p>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
    <h2><b>Shortcode:</b></h2>
    <h3 style="color: #555;">
        <?php esc_html_e('Simplified Registration:', 'lkn-wp-crowdfunding-extension'); ?>
        <b style="font-weight: bold;">[lkn_wpcf_simple_registration]</b>
    </h3>
    <hr>

    <form action="" method="POST">
        <?php wp_nonce_field('save_settings_nonce'); ?>

        <div class="form-group">
            <input <?php checked($is_checked); ?> type="checkbox" name="email_username" id="email_username" />
            <label for="email_username"><?php esc_html_e('Hide Username Field', 'lkn-wp-crowdfunding-extension'); ?></label>
            <div class="lkn-tooltip">
                <span class="lkn-tooltip-icon">i</span>
                <span class="lkn-tooltiptext">
                    <?php esc_html_e('Checking this option will hide the username field during registration, and the username will be generated automatically.', 'lkn-wp-crowdfunding-extension'); ?>
                </span>
            </div>
        </div>

        <div class="form-group">
            <input <?php checked($is_checked_validacao); ?> type="checkbox" name="email_validacao" id="email_validacao" />
            <label for="email_validacao"><?php esc_html_e('Enable Email Validation Registration', 'lkn-wp-crowdfunding-extension'); ?></label>
            <div class="lkn-tooltip">
                <span class="lkn-tooltip-icon">i</span>
                <span class="lkn-tooltiptext">
                    <?php esc_html_e('Checking this option will require email validation before user registration is completed.', 'lkn-wp-crowdfunding-extension'); ?>
                </span>
            </div>
        </div>

        <div class="form-group lkn-group-template">
            <?php
            $templates = get_posts([
                'post_type'   => 'page',
                'post_status' => 'publish',
                'numberposts' => -1,
            ]);
            $selected = get_option('lkn_crowdfunding_custom_template_id', ''); ?>
            <label for="lkn_crowdfunding_custom_template_id"><?php esc_html_e('Select the campaign details page', 'lkn-wp-crowdfunding-extension'); ?></label>
            <select name="lkn_crowdfunding_custom_template_id" id="lkn_crowdfunding_custom_template_id">
                <option value=""><?php esc_html_e('Default', 'lkn-wp-crowdfunding-extension'); ?></option>
                <?php foreach ($templates as $template) : ?>
                    <option value="<?php echo esc_attr($template->ID); ?>" <?php selected($template->ID, $selected); ?>>
                        <?php echo esc_html($template->post_title); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="lkn-form-group">
            <label for="url_red_pos_cadastro"><?php esc_html_e('Enter Default Redirect URL After Registration', 'lkn-wp-crowdfunding-extension'); ?></label>
            <select name="url_red_pos_cadastro" id="url_red_pos_cadastro">
                <option <?php selected($saved_redirect_uri, ''); ?> value=""><?php esc_html_e('None', 'lkn-wp-crowdfunding-extension'); ?></option>
                <?php foreach ($pages as $page_id => $page) : ?>
                    <option value="<?php echo esc_attr($page_id); ?>" <?php selected($saved_redirect_uri, $page['url']); ?>>
                        <?php echo esc_html($page['title']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="lkn-form-group">
            <label for="url_red_envio_email"><?php esc_html_e('Enter Default Redirect URL After Email Sent', 'lkn-wp-crowdfunding-extension'); ?></label>
            <select name="url_red_envio_email" id="url_red_envio_email">
                <option value="" <?php selected($saved_redirect_uri_envio_email, ''); ?>><?php esc_html_e('None', 'lkn-wp-crowdfunding-extension'); ?></option>
                <?php foreach ($pages as $page_id => $page) : ?>
                    <option value="<?php echo esc_attr($page_id); ?>" <?php selected($saved_redirect_uri_envio_email, $page['url']); ?>>
                        <?php echo esc_html($page['title']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="lkn-form-group">
            <label for="url_red_falha_email"><?php esc_html_e('Enter Default Redirect URL After Email Sending Failure', 'lkn-wp-crowdfunding-extension'); ?></label>
            <select name="url_red_falha_email" id="url_red_falha_email">
                <option value="" <?php selected($saved_redirect_uri_falha_email, ''); ?>><?php esc_html_e('None', 'lkn-wp-crowdfunding-extension'); ?></option>
                <?php foreach ($pages as $page_id => $page) : ?>
                    <option value="<?php echo esc_attr($page_id); ?>" <?php selected($saved_redirect_uri_falha_email, $page['url']); ?>>
                        <?php echo esc_html($page['title']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div style="width: 100%; margin: 8px 0px 40px 0px;">
            <input type="submit" name="action" value="<?php esc_attr_e('Clear Email Options', 'lkn-wp-crowdfunding-extension'); ?>" class="option">
        </div>

        <div class="lkn-button-group">
            <input type="submit" name="action" value="<?php esc_attr_e('Save Settings', 'lkn-wp-crowdfunding-extension'); ?>" class="save">
            <input type="submit" name="action" value="<?php esc_attr_e('Reset Settings', 'lkn-wp-crowdfunding-extension'); ?>" class="reset">
        </div>

        <hr>
    </form>
</body>

</html>

<?php wpcf_function()->generator(array()); ?>