<?php
/**
 * Pro settings (activate Pro + spam options).
 *
 * @package AlgoForms
 */

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

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

    $opts = algo_forms_get_options();
    $action = isset($_POST['algo_forms_pro_action']) ? sanitize_key(wp_unslash($_POST['algo_forms_pro_action'])) : 'save';
    $license = function_exists('algo_forms_license') ? algo_forms_license() : null;

    if ($action === 'activate') {
        $key = sanitize_text_field(wp_unslash($_POST['algo_forms_pro_license_key'] ?? ''));
        $result = null;
        if ($license) {
            $result = ($key !== '') ? $license->activate_license($key) : $license->activate_local();
        }
        if (is_wp_error($result)) {
            set_transient(
                'algo_forms_pro_error_' . get_current_user_id(),
                $result->get_error_message(),
                2 * MINUTE_IN_SECONDS
            );
            wp_safe_redirect(add_query_arg(array('page' => 'algo-forms-pro', 'license_error' => '1'), admin_url('admin.php')));
            exit;
        }
        $state = $license ? $license->get() : array();
        $opts['pro_active'] = 1;
        $opts['pro_license_key'] = (string) ($state['license_key'] ?? '');
    } elseif ($action === 'deactivate') {
        // Constant ALGO_FORMS_PRO still wins if defined.
        if ($license) {
            $license->deactivate();
        }
        $opts['pro_active'] = 0;
        $opts['pro_license_key'] = '';
    } else {
        $opts['spam_honeypot'] = !empty($_POST['algo_forms_spam_honeypot']) ? 1 : 0;
        $opts['spam_min_seconds'] = max(0, (int) ($_POST['algo_forms_spam_min_seconds'] ?? 2));
        $opts['spam_rate_limit'] = max(0, (int) ($_POST['algo_forms_spam_rate_limit'] ?? 8));
        $opts['spam_rate_window'] = max(60, (int) ($_POST['algo_forms_spam_rate_window'] ?? HOUR_IN_SECONDS));
    }

    update_option(ALGO_FORMS_OPTIONS_KEY, $opts, false);

    if ($action === 'activate' && algo_forms_is_pro()) {
        algo_forms_install_mail_log_table();
        algo_forms_maybe_upgrade_submissions_pro_columns();
    }

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

/**
 * Ensure Pro tables/columns exist once Pro is active (idempotent).
 *
 * @return void
 */
function algo_forms_ensure_pro_schema()
{
    if (!is_admin() || !algo_forms_is_pro()) {
        return;
    }
    static $done = false;
    if ($done) {
        return;
    }
    $done = true;
    if (function_exists('algo_forms_install_mail_log_table')) {
        algo_forms_install_mail_log_table();
    }
    if (function_exists('algo_forms_maybe_upgrade_submissions_pro_columns')) {
        algo_forms_maybe_upgrade_submissions_pro_columns();
    }
}
add_action('admin_init', 'algo_forms_ensure_pro_schema', 5);

/**
 * @return void
 */
function algo_forms_render_pro_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'));
    }

    $opts = algo_forms_get_options();
    $is_pro = algo_forms_is_pro();
    $locked_by_const = defined('ALGO_FORMS_PRO') && ALGO_FORMS_PRO;
    $license = function_exists('algo_forms_license') ? algo_forms_license() : null;
    $lic_data = $license ? $license->get() : array();
    $allow_local = $license ? $license->allow_local_unlock() : false;
    $status_line = $license ? $license->status_label() : '';

    algo_forms_admin_shell_start(
        __('Pro settings', 'algo-forms'),
        __('Unlock spam protection, delivery log, and the submission inbox — without changing Free form behaviour.', 'algo-forms'),
        'lavender'
    );
    ?>
        <?php if (!empty($_GET['updated'])) : ?>
            <div class="notice notice-success is-dismissible"><p><?php esc_html_e('Pro settings saved.', 'algo-forms'); ?></p></div>
        <?php endif; ?>
        <?php
        $lic_error = get_transient('algo_forms_pro_error_' . get_current_user_id());
        if (is_string($lic_error) && $lic_error !== '') {
            delete_transient('algo_forms_pro_error_' . get_current_user_id());
            ?>
            <div class="notice notice-error is-dismissible"><p><?php echo esc_html($lic_error); ?></p></div>
            <?php
        }
        ?>

        <div class="af-status-card <?php echo $is_pro ? 'is-ok' : 'is-warn'; ?>" style="margin-bottom:1.25rem;">
            <span class="af-status-icon"><?php echo algo_forms_admin_icon($is_pro ? 'check' : 'warning'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
            <div>
                <strong>
                    <?php echo $is_pro ? esc_html__('Algo Forms Pro is active', 'algo-forms') : esc_html__('Running Free plan', 'algo-forms'); ?>
                </strong>
                <p>
                    <?php
                    if ($locked_by_const) {
                        esc_html_e('Enabled via ALGO_FORMS_PRO in wp-config.php.', 'algo-forms');
                    } elseif ($status_line !== '') {
                        echo esc_html($status_line);
                    } elseif ($is_pro) {
                        esc_html_e('Pro features are unlocked on this site.', 'algo-forms');
                    } else {
                        esc_html_e('Enter a license key from algorisys.com to unlock Pro. Existing forms, SMTP, and submissions keep working either way.', 'algo-forms');
                    }
                    ?>
                </p>
            </div>
        </div>

        <div class="af-panel">
            <div class="af-panel-head">
                <h2><?php esc_html_e('License / activation', 'algo-forms'); ?></h2>
            </div>
            <form method="post">
                <?php wp_nonce_field('algo_forms_pro_settings'); ?>
                <table class="form-table" role="presentation">
                    <tr>
                        <th><label for="algo_forms_pro_license_key"><?php esc_html_e('License key', 'algo-forms'); ?></label></th>
                        <td>
                            <?php if (!empty($lic_data['license_key']) && ($lic_data['mode'] ?? '') === 'license') : ?>
                                <p><code><?php echo esc_html((string) $lic_data['license_key']); ?></code></p>
                            <?php endif; ?>
                            <input type="text" class="regular-text" id="algo_forms_pro_license_key" name="algo_forms_pro_license_key"
                                value=""
                                placeholder="AFPRO-XXXX-XXXX-XXXX-XXXX" <?php disabled($locked_by_const || ($is_pro && !$allow_local && ($lic_data['mode'] ?? '') === 'license')); ?>>
                            <p class="description">
                                <?php
                                if ($allow_local) {
                                    esc_html_e('On this development / Algorisys site you can activate without a key. Customer sites must use a key issued under Plugin Licenses / Plugin Sales.', 'algo-forms');
                                } else {
                                    esc_html_e('Buy Algo Forms Pro on algorisys.com, then paste the AFPRO key here. You can also define ALGO_FORMS_PRO as true in wp-config.php.', 'algo-forms');
                                }
                                ?>
                            </p>
                        </td>
                    </tr>
                </table>
                <p class="submit">
                    <?php if ($locked_by_const) : ?>
                        <span class="description"><?php esc_html_e('Managed by ALGO_FORMS_PRO constant.', 'algo-forms'); ?></span>
                    <?php elseif ($is_pro) : ?>
                        <button type="submit" name="algo_forms_pro_action" value="deactivate" class="button">
                            <?php esc_html_e('Deactivate Pro', 'algo-forms'); ?>
                        </button>
                        <input type="hidden" name="algo_forms_pro_save" value="1">
                    <?php else : ?>
                        <button type="submit" name="algo_forms_pro_action" value="activate" class="button button-primary">
                            <?php echo $allow_local ? esc_html__('Activate Pro on this site', 'algo-forms') : esc_html__('Activate license', 'algo-forms'); ?>
                        </button>
                        <input type="hidden" name="algo_forms_pro_save" value="1">
                    <?php endif; ?>
                </p>
            </form>
        </div>

        <div class="af-panel">
            <div class="af-panel-head">
                <h2>
                    <?php esc_html_e('Spam protection', 'algo-forms'); ?>
                    <?php echo algo_forms_pro_badge_html(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                </h2>
            </div>
            <?php if (!$is_pro) : ?>
                <p class="description"><?php esc_html_e('Activate Pro to configure and enforce these rules on front-end forms.', 'algo-forms'); ?></p>
            <?php endif; ?>
            <form method="post">
                <?php wp_nonce_field('algo_forms_pro_settings'); ?>
                <input type="hidden" name="algo_forms_pro_action" value="save">
                <table class="form-table" role="presentation">
                    <tr>
                        <th><?php esc_html_e('Honeypot', 'algo-forms'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="algo_forms_spam_honeypot" value="1"
                                    <?php checked(!isset($opts['spam_honeypot']) || !empty($opts['spam_honeypot'])); ?>
                                    <?php disabled(!$is_pro); ?>>
                                <?php esc_html_e('Block bots that fill the hidden website field', 'algo-forms'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="algo_forms_spam_min_seconds"><?php esc_html_e('Minimum seconds before submit', 'algo-forms'); ?></label></th>
                        <td>
                            <input type="number" class="small-text" id="algo_forms_spam_min_seconds" name="algo_forms_spam_min_seconds"
                                value="<?php echo esc_attr((string) ((int) ($opts['spam_min_seconds'] ?? 2))); ?>" min="0" max="60"
                                <?php disabled(!$is_pro); ?>>
                            <p class="description"><?php esc_html_e('0 disables the timing check. Default 2.', 'algo-forms'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="algo_forms_spam_rate_limit"><?php esc_html_e('Max submissions per IP / window', 'algo-forms'); ?></label></th>
                        <td>
                            <input type="number" class="small-text" id="algo_forms_spam_rate_limit" name="algo_forms_spam_rate_limit"
                                value="<?php echo esc_attr((string) ((int) ($opts['spam_rate_limit'] ?? 8))); ?>" min="0" max="200"
                                <?php disabled(!$is_pro); ?>>
                            <span><?php esc_html_e('per', 'algo-forms'); ?></span>
                            <input type="number" class="small-text" name="algo_forms_spam_rate_window"
                                value="<?php echo esc_attr((string) ((int) ($opts['spam_rate_window'] ?? HOUR_IN_SECONDS))); ?>" min="60" step="60"
                                <?php disabled(!$is_pro); ?>>
                            <span><?php esc_html_e('seconds', 'algo-forms'); ?></span>
                            <p class="description"><?php esc_html_e('0 disables rate limiting. Default 8 per hour.', 'algo-forms'); ?></p>
                        </td>
                    </tr>
                </table>
                <p class="submit">
                    <button type="submit" name="algo_forms_pro_save" value="1" class="button button-primary" <?php disabled(!$is_pro); ?>>
                        <?php esc_html_e('Save spam settings', 'algo-forms'); ?>
                    </button>
                </p>
            </form>
        </div>

        <div class="af-panel">
            <div class="af-panel-head"><h2><?php esc_html_e('What stays Free', 'algo-forms'); ?></h2></div>
            <ul class="af-pro-list">
                <li><?php esc_html_e('Unlimited forms, shortcodes, and field editor', 'algo-forms'); ?></li>
                <li><?php esc_html_e('Built-in SMTP Setup', 'algo-forms'); ?></li>
                <li><?php esc_html_e('Email & notifications (recipients, visitor copy)', 'algo-forms'); ?></li>
                <li><?php esc_html_e('Submissions list, search, CSV export, delete', 'algo-forms'); ?></li>
                <li><?php esc_html_e('Pip dashboard overview', 'algo-forms'); ?></li>
            </ul>
        </div>
    <?php
    algo_forms_admin_shell_end();
}
