<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * @return void
 */
function algo_forms_save_smtp_settings()
{
    if (!isset($_POST['algo_forms_smtp_save']) || !isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'algo_forms_smtp_settings')) {
        return;
    }
    if (!current_user_can(ALGO_FORMS_CAP)) {
        return;
    }

    $opts = algo_forms_get_options();
    $opts = algo_forms_sanitize_smtp_options_from_post($opts);
    // From name/email live with delivery identity; keep editable here too.
    if (isset($_POST['algo_forms_from_name'])) {
        $opts['from_name'] = sanitize_text_field(wp_unslash($_POST['algo_forms_from_name']));
    }
    if (isset($_POST['algo_forms_from_email'])) {
        $opts['from_email'] = sanitize_email(wp_unslash($_POST['algo_forms_from_email']));
    }
    if (isset($_POST['algo_forms_reply_to_email'])) {
        $opts['reply_to_email'] = sanitize_email(wp_unslash($_POST['algo_forms_reply_to_email']));
    }
    update_option(ALGO_FORMS_OPTIONS_KEY, $opts, false);

    wp_safe_redirect(add_query_arg(array('page' => 'algo-forms-smtp', 'updated' => '1'), admin_url('admin.php')));
    exit;
}
add_action('admin_init', 'algo_forms_save_smtp_settings');

/**
 * Manual “Import from WP Mail SMTP” action.
 *
 * @return void
 */
function algo_forms_handle_import_wpms_smtp()
{
    if (!isset($_POST['algo_forms_import_wpms']) || !isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'algo_forms_import_wpms')) {
        return;
    }
    if (!current_user_can(ALGO_FORMS_CAP)) {
        return;
    }

    $result = algo_forms_import_wp_mail_smtp_settings(true);
    set_transient(
        'algo_forms_wpms_import_' . get_current_user_id(),
        $result,
        60
    );

    wp_safe_redirect(add_query_arg(array('page' => 'algo-forms-smtp', 'wpms_import' => '1'), admin_url('admin.php')));
    exit;
}
add_action('admin_init', 'algo_forms_handle_import_wpms_smtp');

/**
 * Delivery tests (single address).
 *
 * @return void
 */
function algo_forms_handle_smtp_test_email()
{
    if (!isset($_POST['algo_forms_send_test']) || !isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'algo_forms_test_mail')) {
        return;
    }
    if (!current_user_can(ALGO_FORMS_CAP)) {
        return;
    }

    // Company recipient tests stay on Email & notifications.
    $mode = isset($_POST['algo_forms_test_mode']) ? sanitize_key(wp_unslash($_POST['algo_forms_test_mode'])) : 'single';
    if ($mode !== 'single') {
        return;
    }

    $opts = algo_forms_get_options();
    $headers = algo_forms_notification_headers($opts, '');
    $to = sanitize_email(wp_unslash($_POST['algo_forms_test_to'] ?? ''));

    if (!$to || !is_email($to)) {
        set_transient(
            'algo_forms_mail_test_' . get_current_user_id(),
            array('ok' => false, 'detail' => __('Enter a valid email address.', 'algo-forms')),
            60
        );
    } else {
        $body = sprintf(
            "This is a test message from Algo Forms SMTP Setup.\n\nSite: %s\nTime: %s\n",
            home_url('/'),
            wp_date('Y-m-d H:i:s')
        );
        list($sent, $detail) = algo_forms_wp_mail_send($to, '[Algo Forms] Test email', $body, $headers, 'admin smtp test');
        set_transient(
            'algo_forms_mail_test_' . get_current_user_id(),
            array(
                'ok' => $sent,
                'detail' => $sent ? '' : ($detail !== '' ? $detail : __('wp_mail() returned false. Check SMTP settings, or your host mail configuration.', 'algo-forms')),
            ),
            60
        );
    }

    wp_safe_redirect(add_query_arg(array('page' => 'algo-forms-smtp', 'mail_test' => '1'), admin_url('admin.php')));
    exit;
}
add_action('admin_init', 'algo_forms_handle_smtp_test_email');

/**
 * @return void
 */
function algo_forms_render_smtp_settings_page()
{
    if (!current_user_can(ALGO_FORMS_CAP)) {
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'algo-forms'));
    }

    $o = algo_forms_get_options();
    $admin_email = (string) get_option('admin_email');
    $test_result = get_transient('algo_forms_mail_test_' . get_current_user_id());
    if ($test_result !== false) {
        delete_transient('algo_forms_mail_test_' . get_current_user_id());
    }
    $transport = algo_forms_mail_transport_status();
    $has_smtp_pass = algo_forms_smtp_resolve_password($o) !== '';
    $pass_from_const = (defined('ALGO_FORMS_SMTP_PASS') && ALGO_FORMS_SMTP_PASS !== '')
        || (defined('WPMS_ON') && WPMS_ON && defined('WPMS_SMTP_PASS') && WPMS_SMTP_PASS !== '');
    $wpms_preview = algo_forms_read_wp_mail_smtp_settings();
    $import_result = get_transient('algo_forms_wpms_import_' . get_current_user_id());
    if ($import_result !== false) {
        delete_transient('algo_forms_wpms_import_' . get_current_user_id());
    }

    algo_forms_admin_shell_start(
        __('SMTP Setup', 'algo-forms'),
        __('Configure built-in delivery so Algo Forms can send mail without another SMTP plugin.', 'algo-forms'),
        'mint'
    );
    ?>
        <?php if (!empty($_GET['updated'])) : ?>
            <div class="notice notice-success is-dismissible"><p><?php esc_html_e('SMTP settings saved.', 'algo-forms'); ?></p></div>
        <?php endif; ?>

        <?php if (!empty($_GET['wpms_import']) && is_array($import_result)) : ?>
            <div class="notice <?php echo !empty($import_result['ok']) ? 'notice-success' : 'notice-warning'; ?> is-dismissible">
                <p><?php echo esc_html((string) ($import_result['message'] ?? '')); ?></p>
            </div>
        <?php endif; ?>

        <?php if (!empty($_GET['mail_test']) && is_array($test_result)) : ?>
            <?php if (!empty($test_result['ok'])) : ?>
                <div class="notice notice-success is-dismissible">
                    <p>
                        <?php esc_html_e('Test email sent.', 'algo-forms'); ?>
                        <?php echo !empty($test_result['detail']) ? ' ' . esc_html((string) $test_result['detail']) : ''; ?>
                    </p>
                </div>
            <?php else : ?>
                <div class="notice notice-error is-dismissible">
                    <p><strong><?php esc_html_e('Test email failed.', 'algo-forms'); ?></strong>
                    <?php echo !empty($test_result['detail']) ? ' ' . esc_html((string) $test_result['detail']) : ''; ?></p>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <div class="af-status-card <?php echo !empty($transport['ready']) ? 'is-ok' : 'is-warn'; ?>" style="margin-bottom:1.25rem;">
            <span class="af-status-icon"><?php echo algo_forms_admin_icon(!empty($transport['ready']) ? 'check' : 'warning'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
            <div>
                <strong><?php echo esc_html($transport['label']); ?></strong>
                <p><?php echo esc_html($transport['detail']); ?></p>
                <?php if (!empty($transport['conflict'])) : ?>
                    <p><?php esc_html_e('Another SMTP plugin is also active. Disable it (or turn off Algo Forms SMTP) to avoid conflicting mail settings.', 'algo-forms'); ?></p>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($wpms_preview) : ?>
            <div class="af-panel" style="margin-bottom:1.25rem;">
                <div class="af-panel-head">
                    <h2><?php esc_html_e('Import from WP Mail SMTP', 'algo-forms'); ?></h2>
                </div>
                <p class="description" style="margin-top:0;">
                    <?php
                    printf(
                        /* translators: 1: host, 2: user */
                        esc_html__('WP Mail SMTP settings detected (%1$s / %2$s). Algo Forms imports these automatically when its SMTP fields are empty.', 'algo-forms'),
                        esc_html($wpms_preview['smtp_host']),
                        esc_html($wpms_preview['smtp_user'] !== '' ? $wpms_preview['smtp_user'] : __('no user', 'algo-forms'))
                    );
                    ?>
                </p>
                <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=algo-forms-smtp')); ?>">
                    <?php wp_nonce_field('algo_forms_import_wpms'); ?>
                    <button type="submit" name="algo_forms_import_wpms" class="button" value="1">
                        <?php esc_html_e('Re-import SMTP from WP Mail SMTP now', 'algo-forms'); ?>
                    </button>
                </form>
            </div>
        <?php endif; ?>

        <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=algo-forms-smtp')); ?>" class="af-panel">
            <?php wp_nonce_field('algo_forms_smtp_settings'); ?>
            <div class="af-panel-head">
                <h2><?php esc_html_e('SMTP credentials', 'algo-forms'); ?></h2>
            </div>

            <p>
                <label>
                    <input type="checkbox" name="algo_forms_smtp_enabled" value="1" <?php checked(!empty($o['smtp_enabled'])); ?>>
                    <strong><?php esc_html_e('Send mail through Algo Forms SMTP', 'algo-forms'); ?></strong>
                </label>
            </p>

            <table class="form-table" role="presentation">
                <tr>
                    <th><label for="algo_forms_smtp_host"><?php esc_html_e('SMTP host', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="text" class="regular-text" id="algo_forms_smtp_host" name="algo_forms_smtp_host"
                            value="<?php echo esc_attr((string) ($o['smtp_host'] ?? '')); ?>"
                            placeholder="smtp.example.com" autocomplete="off">
                    </td>
                </tr>
                <tr>
                    <th><label for="algo_forms_smtp_port"><?php esc_html_e('Port', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="number" class="small-text" id="algo_forms_smtp_port" name="algo_forms_smtp_port"
                            value="<?php echo esc_attr((string) ((int) ($o['smtp_port'] ?? 587))); ?>" min="1" max="65535">
                        <p class="description"><?php esc_html_e('Common: 587 (TLS), 465 (SSL), 25 (none).', 'algo-forms'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><label for="algo_forms_smtp_encryption"><?php esc_html_e('Encryption', 'algo-forms'); ?></label></th>
                    <td>
                        <select id="algo_forms_smtp_encryption" name="algo_forms_smtp_encryption">
                            <?php
                            $enc = (string) ($o['smtp_encryption'] ?? 'tls');
                            foreach (array(
                                'tls' => __('TLS (STARTTLS)', 'algo-forms'),
                                'ssl' => __('SSL', 'algo-forms'),
                                'none' => __('None', 'algo-forms'),
                            ) as $val => $label) :
                                ?>
                                <option value="<?php echo esc_attr($val); ?>" <?php selected($enc, $val); ?>><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Authentication', 'algo-forms'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="algo_forms_smtp_auth" value="1" <?php checked(!isset($o['smtp_auth']) || !empty($o['smtp_auth'])); ?>>
                            <?php esc_html_e('SMTP server requires username and password', 'algo-forms'); ?>
                        </label>
                    </td>
                </tr>
                <tr>
                    <th><label for="algo_forms_smtp_user"><?php esc_html_e('Username', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="text" class="regular-text" id="algo_forms_smtp_user" name="algo_forms_smtp_user"
                            value="<?php echo esc_attr((string) ($o['smtp_user'] ?? '')); ?>"
                            autocomplete="off">
                        <p class="description"><?php esc_html_e('Often the full mailbox address, e.g. noreply@yourdomain.com', 'algo-forms'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><label for="algo_forms_smtp_pass"><?php esc_html_e('Password', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="password" class="regular-text" id="algo_forms_smtp_pass" name="algo_forms_smtp_pass"
                            value="" placeholder="<?php echo $has_smtp_pass ? esc_attr__('•••••••• (saved — leave blank to keep)', 'algo-forms') : ''; ?>"
                            autocomplete="new-password" <?php disabled($pass_from_const); ?>>
                        <?php if ($pass_from_const) : ?>
                            <p class="description">
                                <?php esc_html_e('Password is loaded from wp-config.php (ALGO_FORMS_SMTP_PASS or WPMS_SMTP_PASS). That is the most secure option — the field above is locked.', 'algo-forms'); ?>
                            </p>
                        <?php elseif ($has_smtp_pass) : ?>
                            <p class="description">
                                <?php esc_html_e('A password is already saved. Enter a new one only if you want to change it. For better security you can move it to wp-config.php:', 'algo-forms'); ?>
                                <code>define('ALGO_FORMS_SMTP_PASS', 'your-password');</code>
                            </p>
                        <?php else : ?>
                            <p class="description">
                                <?php esc_html_e('Or define in wp-config.php: define(\'ALGO_FORMS_SMTP_PASS\', \'your-password\');', 'algo-forms'); ?>
                            </p>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th><label for="algo_forms_from_name"><?php esc_html_e('From name', 'algo-forms'); ?></label></th>
                    <td><input type="text" class="regular-text" id="algo_forms_from_name" name="algo_forms_from_name" value="<?php echo esc_attr($o['from_name']); ?>"></td>
                </tr>
                <tr>
                    <th><label for="algo_forms_from_email"><?php esc_html_e('From email', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="email" class="regular-text" id="algo_forms_from_email" name="algo_forms_from_email" value="<?php echo esc_attr($o['from_email']); ?>">
                        <p class="description">
                            <?php esc_html_e('Must match an address allowed by your SMTP account (Yahoo username). Do not put info@ here if you send via Yahoo.', 'algo-forms'); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th><label for="algo_forms_reply_to_email"><?php esc_html_e('Reply-To email', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="email" class="regular-text" id="algo_forms_reply_to_email" name="algo_forms_reply_to_email" value="<?php echo esc_attr((string) ($o['reply_to_email'] ?? '')); ?>" placeholder="info@algorisys.com">
                        <p class="description">
                            <?php esc_html_e('Where Reply goes (forms + license emails). Yahoo SMTP will ignore this and reject mail if it differs from the Yahoo account — leave blank while using Yahoo. To make Reply go to info@algorisys.com, send via Hostinger SMTP as info@ instead.', 'algo-forms'); ?>
                        </p>
                    </td>
                </tr>
            </table>

            <p class="submit">
                <button type="submit" name="algo_forms_smtp_save" class="button button-primary" value="1">
                    <?php esc_html_e('Save SMTP settings', 'algo-forms'); ?>
                </button>
                <a class="button" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-email')); ?>">
                    <?php esc_html_e('Email & notifications →', 'algo-forms'); ?>
                </a>
            </p>
        </form>

        <div class="af-panel">
            <div class="af-panel-head">
                <h2><?php esc_html_e('Send test email', 'algo-forms'); ?></h2>
            </div>
            <p class="description" style="margin-top:0;">
                <?php esc_html_e('Save SMTP settings first, then send a test. Check spam if needed.', 'algo-forms'); ?>
            </p>
            <form method="post">
                <?php wp_nonce_field('algo_forms_test_mail'); ?>
                <input type="hidden" name="algo_forms_test_mode" value="single">
                <p>
                    <label for="algo_forms_test_to"><?php esc_html_e('Send a test to', 'algo-forms'); ?></label><br>
                    <input type="email" class="regular-text" id="algo_forms_test_to" name="algo_forms_test_to" required value="<?php echo esc_attr($admin_email); ?>">
                </p>
                <p><button type="submit" name="algo_forms_send_test" class="button button-primary"><?php esc_html_e('Send test email', 'algo-forms'); ?></button></p>
            </form>
        </div>
    <?php
    algo_forms_admin_shell_end();
}
