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

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

    $recipient_post = isset($_POST['algo_forms_recipients']) && is_array($_POST['algo_forms_recipients'])
        ? wp_unslash($_POST['algo_forms_recipients'])
        : array();
    $emails_input = $recipient_post['emails'] ?? array();
    $enabled_input = $recipient_post['enabled'] ?? array();
    $recipients = algo_forms_sanitize_recipient_entries_from_post($emails_input, $enabled_input);

    $opts = algo_forms_get_options();
    $opts['send_notifications'] = !empty($_POST['algo_forms_send_notifications']) ? 1 : 0;
    $opts['send_visitor_copy'] = !empty($_POST['algo_forms_send_visitor_copy']) ? 1 : 0;
    $opts['recipients'] = $recipients;
    $opts['subject_template'] = sanitize_text_field(wp_unslash($_POST['algo_forms_subject_template'] ?? ''));
    $opts['visitor_subject_template'] = sanitize_text_field(wp_unslash($_POST['algo_forms_visitor_subject_template'] ?? ''));
    $opts['visitor_intro'] = sanitize_textarea_field(wp_unslash($_POST['algo_forms_visitor_intro'] ?? ''));
    $opts['from_name'] = sanitize_text_field(wp_unslash($_POST['algo_forms_from_name'] ?? ''));
    $opts['from_email'] = sanitize_email(wp_unslash($_POST['algo_forms_from_email'] ?? ''));

    update_option(ALGO_FORMS_OPTIONS_KEY, $opts, false);

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

/**
 * Company-notification test emails.
 *
 * @return void
 */
function algo_forms_handle_company_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;
    }

    $mode = isset($_POST['algo_forms_test_mode']) ? sanitize_key(wp_unslash($_POST['algo_forms_test_mode'])) : 'single';
    if ($mode !== 'company') {
        return;
    }

    $opts = algo_forms_get_options();
    $headers = algo_forms_notification_headers($opts, '');
    $recipients = algo_forms_get_company_recipients();

    if (!$recipients) {
        set_transient(
            'algo_forms_mail_test_' . get_current_user_id(),
            array('ok' => false, 'detail' => __('Add and enable at least one company recipient first.', 'algo-forms')),
            60
        );
    } else {
        $failed = array();
        $ok_count = 0;
        $body = sprintf(
            "This is a company-notification test from Algo Forms.\n\nConfigured recipients:\n- %s\n\nSite: %s\nTime: %s\n",
            implode("\n- ", $recipients),
            home_url('/'),
            wp_date('Y-m-d H:i:s')
        );
        foreach ($recipients as $to) {
            list($sent, $detail) = algo_forms_wp_mail_send(
                $to,
                '[Algo Forms] Company notification test',
                $body,
                $headers,
                'company recipient test → ' . $to
            );
            if ($sent) {
                $ok_count++;
            } else {
                $failed[] = $to . ($detail !== '' ? ' (' . $detail . ')' : '');
            }
        }
        set_transient(
            'algo_forms_mail_test_' . get_current_user_id(),
            array(
                'ok' => $ok_count > 0 && !$failed,
                'detail' => $failed
                    ? sprintf(
                        /* translators: 1: sent count, 2: failure details */
                        __('Sent to %1$d recipient(s). Failed: %2$s', 'algo-forms'),
                        $ok_count,
                        implode('; ', $failed)
                    )
                    : sprintf(
                        /* translators: %d: recipient count */
                        __('Test sent to %d company recipient(s).', 'algo-forms'),
                        $ok_count
                    ),
            ),
            60
        );
    }

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

/**
 * @return void
 */
function algo_forms_render_email_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();
    $company_entries = algo_forms_get_company_recipient_entries();
    $company_recipients = algo_forms_enabled_recipient_emails($company_entries);
    $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());
    }
    $last_log = get_option('algo_forms_last_mail_log', array());
    if (!is_array($last_log)) {
        $last_log = array();
    }
    $transport = algo_forms_mail_transport_status();

    algo_forms_recipients_manager_assets();
    algo_forms_admin_shell_start(
        __('Email & notifications', 'algo-forms'),
        __('Choose who gets form submissions and how visitor thank-you emails look.', 'algo-forms'),
        'peach'
    );
    ?>
        <?php if (!empty($_GET['updated'])) : ?>
            <div class="notice notice-success is-dismissible"><p><?php esc_html_e('Settings saved.', 'algo-forms'); ?></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('smtp'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
            <div>
                <strong><?php echo esc_html($transport['label']); ?></strong>
                <p><?php echo esc_html($transport['detail']); ?></p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-smtp')); ?>">
                    <?php esc_html_e('Open SMTP Setup →', 'algo-forms'); ?>
                </a>
            </div>
        </div>

        <?php if ($last_log) : ?>
            <div class="af-panel" style="margin-bottom:1.25rem;">
                <div class="af-panel-head">
                    <h2><?php esc_html_e('Last company notification attempt', 'algo-forms'); ?></h2>
                    <?php if (!empty($last_log['time'])) : ?>
                        <span class="description"><?php echo esc_html((string) $last_log['time']); ?></span>
                    <?php endif; ?>
                </div>
                <?php if (!empty($last_log['recipients']) && is_array($last_log['recipients'])) : ?>
                    <p><strong><?php esc_html_e('Recipients:', 'algo-forms'); ?></strong> <?php echo esc_html(implode(', ', $last_log['recipients'])); ?></p>
                <?php endif; ?>
                <?php if (!empty($last_log['subject'])) : ?>
                    <p><strong><?php esc_html_e('Subject:', 'algo-forms'); ?></strong> <?php echo esc_html((string) $last_log['subject']); ?></p>
                <?php endif; ?>
                <?php if (!empty($last_log['detail'])) : ?>
                    <p><strong><?php esc_html_e('Result:', 'algo-forms'); ?></strong> <?php echo esc_html((string) $last_log['detail']); ?></p>
                <?php endif; ?>
                <?php if (!empty($last_log['visitor'])) : ?>
                    <p><strong><?php esc_html_e('Visitor copy:', 'algo-forms'); ?></strong> <?php echo esc_html((string) $last_log['visitor']); ?></p>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=algo-forms-email')); ?>">
            <?php wp_nonce_field('algo_forms_email_settings'); ?>

            <div class="af-panel algo-company-recipients-card">
                <div class="af-panel-head">
                    <h2><?php esc_html_e('Global notification recipients', 'algo-forms'); ?></h2>
                </div>
                <p class="description" style="margin-top:0;">
                    <?php esc_html_e('Default people who receive form submissions. Uncheck Receive to pause an address without removing it. Forms set to “Custom recipients only” ignore this list.', 'algo-forms'); ?>
                </p>

                <p>
                    <label>
                        <input type="checkbox" name="algo_forms_send_notifications" value="1" <?php checked(!empty($o['send_notifications'])); ?>>
                        <strong><?php esc_html_e('Send company notifications on form submit', 'algo-forms'); ?></strong>
                    </label>
                </p>

                <?php
                algo_forms_render_recipients_manager(
                    $company_entries,
                    'algo_forms_recipients',
                    'algo-company-recipients-list',
                    array(
                        'empty_note' => sprintf(
                            /* translators: %s: WordPress admin email */
                            __('No company emails added yet. Until you add one, notifications fall back to the WordPress admin email: %s', 'algo-forms'),
                            $admin_email
                        ),
                        'add_placeholder' => 'info@algorisys.com',
                    )
                );
                ?>

                <?php if ($company_recipients) : ?>
                    <p class="algo-recipients-summary description">
                        <strong><?php esc_html_e('Currently receiving (enabled):', 'algo-forms'); ?></strong>
                        <?php echo esc_html(implode(', ', $company_recipients)); ?>
                    </p>
                <?php elseif ($company_entries) : ?>
                    <p class="algo-recipients-summary description">
                        <?php esc_html_e('All listed emails are paused (Receive unchecked). Enable at least one, or forms will fall back to the WordPress admin email.', 'algo-forms'); ?>
                    </p>
                <?php endif; ?>
            </div>

            <div class="af-panel">
                <div class="af-panel-head">
                    <h2><?php esc_html_e('Visitor acknowledgement', 'algo-forms'); ?></h2>
                </div>
                <table class="form-table" role="presentation">
                    <tr>
                        <th><?php esc_html_e('Visitor copy', 'algo-forms'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="algo_forms_send_visitor_copy" value="1" <?php checked(!empty($o['send_visitor_copy'])); ?>>
                                <?php esc_html_e('Send thank-you email to the visitor’s email field', 'algo-forms'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="algo_forms_visitor_subject_template"><?php esc_html_e('Visitor subject', 'algo-forms'); ?></label></th>
                        <td><input type="text" class="large-text" id="algo_forms_visitor_subject_template" name="algo_forms_visitor_subject_template" value="<?php echo esc_attr($o['visitor_subject_template']); ?>"></td>
                    </tr>
                    <tr>
                        <th><label for="algo_forms_visitor_intro"><?php esc_html_e('Visitor intro', 'algo-forms'); ?></label></th>
                        <td><textarea class="large-text" rows="3" id="algo_forms_visitor_intro" name="algo_forms_visitor_intro"><?php echo esc_textarea($o['visitor_intro']); ?></textarea></td>
                    </tr>
                </table>
            </div>

            <div class="af-panel">
                <div class="af-panel-head">
                    <h2><?php esc_html_e('Message templates & sender', 'algo-forms'); ?></h2>
                </div>
                <table class="form-table" role="presentation">
                    <tr>
                        <th><label for="algo_forms_subject_template"><?php esc_html_e('Company email subject', 'algo-forms'); ?></label></th>
                        <td>
                            <input type="text" class="large-text" id="algo_forms_subject_template" name="algo_forms_subject_template" value="<?php echo esc_attr($o['subject_template']); ?>">
                            <p class="description"><?php esc_html_e('Placeholders: {form_title}, {form_name}, {site_name}', 'algo-forms'); ?></p>
                        </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('Should match an address allowed by your SMTP account. Configure delivery under SMTP Setup.', 'algo-forms'); ?>
                            </p>
                        </td>
                    </tr>
                </table>

                <p class="submit">
                    <button type="submit" name="algo_forms_email_save" class="button button-primary" value="1"><?php esc_html_e('Save changes', 'algo-forms'); ?></button>
                </p>
            </div>
        </form>

        <div class="af-panel">
            <div class="af-panel-head">
                <h2><?php esc_html_e('Test company notifications', 'algo-forms'); ?></h2>
            </div>
            <p class="description" style="margin-top:0;">
                <?php esc_html_e('Sends a test to every enabled company recipient. For raw SMTP delivery tests, use SMTP Setup.', 'algo-forms'); ?>
            </p>
            <form method="post">
                <?php wp_nonce_field('algo_forms_test_mail'); ?>
                <input type="hidden" name="algo_forms_test_mode" value="company">
                <p>
                    <button type="submit" name="algo_forms_send_test" class="button button-primary" <?php disabled(empty($company_recipients)); ?>>
                        <?php esc_html_e('Test company notifications (enabled emails)', 'algo-forms'); ?>
                    </button>
                </p>
                <?php if ($company_recipients) : ?>
                    <p class="description"><?php echo esc_html(implode(', ', $company_recipients)); ?></p>
                <?php else : ?>
                    <p class="description"><?php esc_html_e('Save and enable at least one company recipient above first.', 'algo-forms'); ?></p>
                <?php endif; ?>
            </form>
        </div>
    <?php
    algo_forms_admin_shell_end();
}
