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

/**
 * @return void
 */
function algo_forms_admin_menu()
{
    add_menu_page(
        __('Algo Forms', 'algo-forms'),
        __('Algo Forms', 'algo-forms'),
        ALGO_FORMS_CAP,
        'algo-forms',
        'algo_forms_dashboard_page',
        'none',
        30
    );

    add_submenu_page(
        'algo-forms',
        __('Dashboard', 'algo-forms'),
        __('Dashboard', 'algo-forms'),
        ALGO_FORMS_CAP,
        'algo-forms',
        'algo_forms_dashboard_page'
    );

    add_submenu_page(
        'algo-forms',
        __('All Forms', 'algo-forms'),
        __('All Forms', 'algo-forms'),
        ALGO_FORMS_CAP,
        'algo-forms-list',
        'algo_forms_list_page'
    );

    add_submenu_page(
        'algo-forms',
        __('Add New Form', 'algo-forms'),
        __('Add New', 'algo-forms'),
        ALGO_FORMS_CAP,
        'algo-forms-edit',
        'algo_forms_edit_page'
    );

    add_submenu_page(
        'algo-forms',
        __('Submissions', 'algo-forms'),
        __('Submissions', 'algo-forms'),
        ALGO_FORMS_CAP,
        'algo-forms-submissions',
        'algo_forms_submissions_page'
    );

    add_submenu_page(
        'algo-forms',
        __('SMTP Setup', 'algo-forms'),
        __('SMTP Setup', 'algo-forms'),
        ALGO_FORMS_CAP,
        'algo-forms-smtp',
        'algo_forms_render_smtp_settings_page'
    );

    add_submenu_page(
        'algo-forms',
        __('Email & notifications', 'algo-forms'),
        __('Email & notifications', 'algo-forms'),
        ALGO_FORMS_CAP,
        'algo-forms-email',
        'algo_forms_render_email_settings_page'
    );

    add_submenu_page(
        'algo-forms',
        __('Delivery log', 'algo-forms'),
        __('Delivery log', 'algo-forms'),
        ALGO_FORMS_CAP,
        'algo-forms-delivery-log',
        'algo_forms_render_delivery_log_page'
    );

    add_submenu_page(
        'algo-forms',
        __('Pro settings', 'algo-forms'),
        __('Pro', 'algo-forms'),
        ALGO_FORMS_CAP,
        'algo-forms-pro',
        'algo_forms_render_pro_settings_page'
    );
}
add_action('admin_menu', 'algo_forms_admin_menu');

/**
 * Save form edits before any admin HTML is printed (avoids headers-already-sent).
 *
 * @return void
 */
function algo_forms_handle_edit_save()
{
    if (!is_admin() || !current_user_can(ALGO_FORMS_CAP)) {
        return;
    }

    $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
    if ($page !== 'algo-forms-edit') {
        return;
    }

    if (
        ($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' ||
        !isset($_POST['_wpnonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'algo_forms_edit')
    ) {
        return;
    }

    global $wpdb;
    $table = $wpdb->prefix . 'algo_forms';
    $form_id = isset($_POST['form_id']) ? (int) $_POST['form_id'] : 0;
    $form_name = sanitize_title(wp_unslash($_POST['form_name'] ?? ''));
    $form_title = sanitize_text_field(wp_unslash($_POST['form_title'] ?? ''));
    $fields = array();
    $required_map = isset($_POST['field_required']) && is_array($_POST['field_required'])
        ? wp_unslash($_POST['field_required'])
        : array();

    if (isset($_POST['field_label']) && is_array($_POST['field_label'])) {
        foreach ($_POST['field_label'] as $index => $label) {
            $label = sanitize_text_field(wp_unslash($label));
            if ($label === '') {
                continue;
            }
            $existing_key = isset($_POST['field_key'][$index]) ? sanitize_key((string) wp_unslash($_POST['field_key'][$index])) : '';
            $field_type = isset($_POST['field_type'][$index]) ? sanitize_key((string) wp_unslash($_POST['field_type'][$index])) : 'text';
            $options_raw = isset($_POST['field_options'][$index]) ? (string) wp_unslash($_POST['field_options'][$index]) : '';
            $row = array(
                'key' => $existing_key,
                'label' => $label,
                'type' => $field_type !== '' ? $field_type : 'text',
                'required' => !empty($required_map[$index]),
            );
            if ($row['type'] === 'select' && $options_raw !== '') {
                $row['options'] = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n|,/', $options_raw) ?: array())));
            }
            $fields[] = $row;
        }
    }

    $fields = algo_forms_normalize_fields($fields);
    $messages = array(
        'submit_label' => sanitize_text_field(wp_unslash($_POST['msg_submit_label'] ?? '')),
        'sending_label' => sanitize_text_field(wp_unslash($_POST['msg_sending_label'] ?? '')),
        'success_message' => sanitize_text_field(wp_unslash($_POST['msg_success_message'] ?? '')),
        'error_generic' => sanitize_text_field(wp_unslash($_POST['msg_error_generic'] ?? '')),
        'required_message' => sanitize_text_field(wp_unslash($_POST['msg_required_message'] ?? '')),
        'invalid_email_message' => sanitize_text_field(wp_unslash($_POST['msg_invalid_email_message'] ?? '')),
        'show_title' => !empty($_POST['show_title']) ? '1' : '0',
    );

    $notify_mode = isset($_POST['notify_mode']) ? sanitize_key(wp_unslash($_POST['notify_mode'])) : 'global';
    $notify_post = isset($_POST['notify_emails']) && is_array($_POST['notify_emails'])
        ? wp_unslash($_POST['notify_emails'])
        : array();
    $notify_recipients = algo_forms_sanitize_recipient_entries_from_post(
        $notify_post['emails'] ?? array(),
        $notify_post['enabled'] ?? array()
    );

    $data = array(
        'form_name' => $form_name,
        'form_title' => $form_title,
        'fields' => wp_json_encode($fields),
        'messages' => wp_json_encode($messages),
        'notify_emails' => algo_forms_encode_form_notify_config($notify_mode, $notify_recipients),
        'email_subject' => sanitize_text_field(wp_unslash($_POST['email_subject'] ?? '')),
    );

    $redirect_args = array('page' => 'algo-forms-edit');

    if ($form_name === '' || $form_title === '') {
        set_transient(
            'algo_forms_edit_error_' . get_current_user_id(),
            __('Form name and title are required.', 'algo-forms'),
            60
        );
        if ($form_id) {
            $redirect_args['id'] = $form_id;
        }
        $redirect_args['error'] = '1';
        wp_safe_redirect(add_query_arg($redirect_args, admin_url('admin.php')));
        exit;
    }

    if ($form_id) {
        $result = $wpdb->update($table, $data, array('id' => $form_id), array('%s', '%s', '%s', '%s', '%s', '%s'), array('%d'));
        if ($result === false) {
            set_transient(
                'algo_forms_edit_error_' . get_current_user_id(),
                __('Failed to save form.', 'algo-forms') . ' ' . $wpdb->last_error,
                60
            );
            $redirect_args['id'] = $form_id;
            $redirect_args['error'] = '1';
            wp_safe_redirect(add_query_arg($redirect_args, admin_url('admin.php')));
            exit;
        }
        $redirect_args['id'] = $form_id;
        $redirect_args['message'] = '1';
        wp_safe_redirect(add_query_arg($redirect_args, admin_url('admin.php')));
        exit;
    }

    $result = $wpdb->insert($table, $data, array('%s', '%s', '%s', '%s', '%s', '%s'));
    if ($result === false) {
        set_transient(
            'algo_forms_edit_error_' . get_current_user_id(),
            __('Failed to create form.', 'algo-forms') . ' ' . $wpdb->last_error,
            60
        );
        $redirect_args['error'] = '1';
        wp_safe_redirect(add_query_arg($redirect_args, admin_url('admin.php')));
        exit;
    }

    $redirect_args['id'] = (int) $wpdb->insert_id;
    $redirect_args['message'] = '1';
    wp_safe_redirect(add_query_arg($redirect_args, admin_url('admin.php')));
    exit;
}
add_action('admin_init', 'algo_forms_handle_edit_save');

/**
 * Stream CSV downloads before any admin HTML is printed.
 *
 * @return void
 */
function algo_forms_handle_submission_download()
{
    if (!is_admin() || !current_user_can(ALGO_FORMS_CAP)) {
        return;
    }

    $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
    if ($page !== 'algo-forms-submissions') {
        return;
    }

    if (
        !isset($_GET['action'], $_GET['form_id']) ||
        $_GET['action'] !== 'download' ||
        !check_admin_referer('algo_forms_download_' . (int) $_GET['form_id'])
    ) {
        return;
    }

    global $wpdb;
    $subs = $wpdb->prefix . 'algo_form_submissions';
    $forms = $wpdb->prefix . 'algo_forms';
    $form_id = (int) $_GET['form_id'];
    $form = $wpdb->get_row($wpdb->prepare("SELECT form_title FROM {$forms} WHERE id = %d", $form_id));
    $rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$subs} WHERE form_id = %d ORDER BY submission_date DESC", $form_id));

    if (!$form) {
        return;
    }

    nocache_headers();
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . sanitize_file_name($form->form_title) . '-submissions.csv"');
    $out = fopen('php://output', 'w');
    $headers = array('ID', 'Date');
    $first = !empty($rows[0]) ? json_decode($rows[0]->form_data, true) : array();
    if (is_array($first)) {
        foreach (array_keys($first) as $key) {
            $headers[] = (string) $key;
        }
    }
    fputcsv($out, $headers);
    foreach ($rows as $row) {
        $data = json_decode($row->form_data, true);
        $line = array($row->id, $row->submission_date);
        if (is_array($data)) {
            foreach ($data as $value) {
                $line[] = $value;
            }
        }
        fputcsv($out, $line);
    }
    fclose($out);
    exit;
}
add_action('admin_init', 'algo_forms_handle_submission_download');

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

    global $wpdb;
    $table = $wpdb->prefix . 'algo_forms';

    if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'delete' && check_admin_referer('algo_forms_delete_' . (int) $_GET['id'])) {
        $wpdb->delete($table, array('id' => (int) $_GET['id']), array('%d'));
        echo '<div class="notice notice-success"><p>' . esc_html__('Form deleted.', 'algo-forms') . '</p></div>';
    }

    $forms = $wpdb->get_results("SELECT * FROM {$table} ORDER BY created_at DESC");
    $global_recipients = algo_forms_get_company_recipients();

    algo_forms_admin_shell_start(
        __('All Forms', 'algo-forms'),
        __('Use shortcode [algo_form name="your-form-name"] on any page or post.', 'algo-forms'),
        'sky'
    );
    ?>
        <p style="margin:0 0 1rem;">
            <a href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-edit')); ?>" class="button button-primary">
                <?php esc_html_e('Add New Form', 'algo-forms'); ?>
            </a>
        </p>

        <div class="af-status-card is-info" style="margin-bottom:1rem;">
            <span class="af-status-icon"><?php echo algo_forms_admin_icon('bell'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
            <div>
                <strong><?php esc_html_e('Company notifications go to', 'algo-forms'); ?></strong>
                <p>
                    <?php if ($global_recipients) : ?>
                        <?php echo esc_html(implode(', ', $global_recipients)); ?>
                    <?php else : ?>
                        <?php
                        printf(
                            /* translators: %s: admin email */
                            esc_html__('not set (fallback: %s)', 'algo-forms'),
                            esc_html((string) get_option('admin_email'))
                        );
                        ?>
                    <?php endif; ?>
                </p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-email')); ?>"><?php esc_html_e('Manage recipients', 'algo-forms'); ?></a>
            </div>
        </div>

        <?php if (!empty($_GET['message'])) : ?>
            <div class="notice notice-success is-dismissible"><p><?php esc_html_e('Form saved.', 'algo-forms'); ?></p></div>
        <?php endif; ?>

        <div class="af-panel" style="padding:0; overflow:hidden;">
        <table class="wp-list-table widefat fixed striped" style="border:0; box-shadow:none; margin:0;">
            <thead>
                <tr>
                    <th><?php esc_html_e('ID', 'algo-forms'); ?></th>
                    <th><?php esc_html_e('Form Name', 'algo-forms'); ?></th>
                    <th><?php esc_html_e('Title', 'algo-forms'); ?></th>
                    <th><?php esc_html_e('Shortcode', 'algo-forms'); ?></th>
                    <th><?php esc_html_e('Created', 'algo-forms'); ?></th>
                    <th><?php esc_html_e('Actions', 'algo-forms'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if ($forms) : ?>
                    <?php foreach ($forms as $form) : ?>
                        <tr>
                            <td><?php echo esc_html((string) $form->id); ?></td>
                            <td><?php echo esc_html($form->form_name); ?></td>
                            <td><?php echo esc_html($form->form_title); ?></td>
                            <td><code>[algo_form name="<?php echo esc_attr($form->form_name); ?>"]</code></td>
                            <td><?php echo esc_html($form->created_at); ?></td>
                            <td>
                                <a class="button button-small" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-edit&id=' . (int) $form->id)); ?>"><?php esc_html_e('Edit', 'algo-forms'); ?></a>
                                <a class="button button-small" href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=algo-forms-list&action=delete&id=' . (int) $form->id), 'algo_forms_delete_' . (int) $form->id)); ?>"
                                    onclick="return confirm('<?php echo esc_js(__('Delete this form?', 'algo-forms')); ?>');"><?php esc_html_e('Delete', 'algo-forms'); ?></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr><td colspan="6"><?php esc_html_e('No forms yet.', 'algo-forms'); ?></td></tr>
                <?php endif; ?>
            </tbody>
        </table>
        </div>
    <?php
    algo_forms_admin_shell_end();
}

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

    global $wpdb;
    $table = $wpdb->prefix . 'algo_forms';
    $form_id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
    $form = $form_id ? $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $form_id)) : null;
    $error_message = '';

    if (!empty($_GET['error'])) {
        $error_key = 'algo_forms_edit_error_' . get_current_user_id();
        $stored_error = get_transient($error_key);
        if (is_string($stored_error) && $stored_error !== '') {
            $error_message = $stored_error;
            delete_transient($error_key);
        } else {
            $error_message = __('Failed to save form.', 'algo-forms');
        }
    }

    $fields = $form ? algo_forms_normalize_fields(json_decode($form->fields, true) ?: array()) : array();
    $messages = $form ? algo_forms_get_form_messages($form) : algo_forms_default_messages();
    $notify_config = $form
        ? algo_forms_decode_form_notify_config($form->notify_emails ?? '')
        : array('mode' => 'global', 'recipients' => array());
    $notify_mode = $notify_config['mode'] ?? 'global';
    $form_recipients = $notify_config['recipients'] ?? array();
    $global_recipients = algo_forms_get_company_recipients();
    $global_entries = algo_forms_get_company_recipient_entries();
    algo_forms_recipients_manager_assets();
    algo_forms_admin_shell_start(
        $form_id ? __('Edit Form', 'algo-forms') : __('Add New Form', 'algo-forms'),
        __('Configure fields, messages, and who gets notified for this form.', 'algo-forms'),
        'sky'
    );
    ?>
        <?php if (!empty($_GET['message'])) : ?>
            <div class="notice notice-success is-dismissible"><p><?php esc_html_e('Form saved.', 'algo-forms'); ?></p></div>
        <?php endif; ?>
        <?php if ($error_message !== '') : ?>
            <div class="notice notice-error"><p><?php echo esc_html($error_message); ?></p></div>
        <?php endif; ?>

        <form method="post" class="af-panel">
            <?php wp_nonce_field('algo_forms_edit'); ?>
            <?php if ($form_id) : ?>
                <input type="hidden" name="form_id" value="<?php echo esc_attr((string) $form_id); ?>">
            <?php endif; ?>

            <table class="form-table" role="presentation">
                <tr>
                    <th><label for="form_name"><?php esc_html_e('Form Name', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="text" class="regular-text" name="form_name" id="form_name" required
                            value="<?php echo $form ? esc_attr($form->form_name) : ''; ?>">
                        <p class="description"><?php esc_html_e('Used in shortcode: [algo_form name="form-name"]', 'algo-forms'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><label for="form_title"><?php esc_html_e('Form Title', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="text" class="regular-text" name="form_title" id="form_title" required
                            value="<?php echo $form ? esc_attr($form->form_title) : ''; ?>">
                        <?php
                        $show_title = $form ? algo_forms_form_shows_title($form) : true;
                        ?>
                        <p style="margin:0.65rem 0 0;">
                            <label for="show_title">
                                <input type="checkbox" name="show_title" id="show_title" value="1" <?php checked($show_title); ?>>
                                <?php esc_html_e('Show form title on the front end', 'algo-forms'); ?>
                            </label>
                        </p>
                        <p class="description">
                            <?php esc_html_e('When checked, the Form Title appears above the fields wherever this form is embedded.', 'algo-forms'); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Company notifications', 'algo-forms'); ?></th>
                    <td>
                        <div class="algo-notify-mode">
                            <label>
                                <input type="radio" name="notify_mode" value="global" <?php checked($notify_mode, 'global'); ?>>
                                <strong><?php esc_html_e('Use global recipients', 'algo-forms'); ?></strong>
                                <span class="description" style="display:inline; margin-left:4px;">
                                    <?php
                                    if ($global_recipients) {
                                        printf(
                                            /* translators: %s: comma-separated emails */
                                            esc_html__('(%s)', 'algo-forms'),
                                            esc_html(implode(', ', $global_recipients))
                                        );
                                    } else {
                                        esc_html_e('(configure under Algo Forms → Email & notifications)', 'algo-forms');
                                    }
                                    ?>
                                </span>
                            </label>
                            <label>
                                <input type="radio" name="notify_mode" value="custom" <?php checked($notify_mode, 'custom'); ?>>
                                <strong><?php esc_html_e('Custom recipients for this form only', 'algo-forms'); ?></strong>
                                <span class="description" style="display:inline; margin-left:4px;">
                                    <?php esc_html_e('(ignores the global list — use for plugin requests, sales, etc.)', 'algo-forms'); ?>
                                </span>
                            </label>
                        </div>

                        <?php if ($global_entries && $notify_mode === 'global') : ?>
                            <p class="description" style="margin-top:0;">
                                <?php esc_html_e('Paused global addresses (Receive unchecked) will not get mail for this form either.', 'algo-forms'); ?>
                            </p>
                        <?php endif; ?>

                        <div class="algo-notify-custom-wrap" <?php echo $notify_mode === 'custom' ? '' : 'hidden'; ?>>
                            <p><strong><?php esc_html_e('Recipients for this form', 'algo-forms'); ?></strong></p>
                            <?php
                            algo_forms_render_recipients_manager(
                                $form_recipients,
                                'notify_emails',
                                'algo-form-recipients-list',
                                array(
                                    'empty_note' => __('Add at least one email when using custom recipients. Until then, mail falls back to the WordPress admin email.', 'algo-forms'),
                                    'add_placeholder' => 'plugins@algorisys.com',
                                    'hint' => __('Only these people get notifications for this form. Uncheck Receive to pause someone without removing them. Save the form to keep changes.', 'algo-forms'),
                                )
                            );
                            ?>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th><label for="email_subject"><?php esc_html_e('Email subject', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="text" class="large-text" name="email_subject" id="email_subject"
                            value="<?php echo $form ? esc_attr($form->email_subject ?? '') : ''; ?>"
                            placeholder="{form_title} — {site_name}">
                    </td>
                </tr>
            </table>

            <h2><?php esc_html_e('Fields', 'algo-forms'); ?></h2>
            <div id="algo-form-fields">
                <?php foreach ($fields as $index => $field) :
                    $opts = isset($field['options']) && is_array($field['options']) ? implode("\n", $field['options']) : '';
                    ?>
                    <div class="algo-admin-field-row">
                        <span class="algo-admin-field-order">
                            <button type="button" class="button button-small algo-move-up">&#8593;</button>
                            <button type="button" class="button button-small algo-move-down">&#8595;</button>
                        </span>
                        <input type="hidden" name="field_key[]" value="<?php echo esc_attr(algo_forms_field_key($field, $index)); ?>">
                        <input type="text" name="field_label[]" value="<?php echo esc_attr($field['label']); ?>" placeholder="<?php esc_attr_e('Label', 'algo-forms'); ?>" required>
                        <select name="field_type[]">
                            <?php foreach (array('text' => 'Text', 'email' => 'Email', 'tel' => 'Phone', 'select' => 'Select', 'textarea' => 'Textarea') as $val => $label) : ?>
                                <option value="<?php echo esc_attr($val); ?>" <?php selected($field['type'], $val); ?>><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <textarea name="field_options[]" rows="2" placeholder="<?php esc_attr_e('Select options (one per line)', 'algo-forms'); ?>"><?php echo esc_textarea($opts); ?></textarea>
                        <label><input type="checkbox" name="field_required[<?php echo (int) $index; ?>]" value="1" <?php checked(!empty($field['required'])); ?>> <?php esc_html_e('Required', 'algo-forms'); ?></label>
                        <button type="button" class="button algo-remove-field"><?php esc_html_e('Remove', 'algo-forms'); ?></button>
                    </div>
                <?php endforeach; ?>
            </div>
            <p><button type="button" class="button" id="algo-add-field"><?php esc_html_e('Add Field', 'algo-forms'); ?></button></p>

            <h2><?php esc_html_e('Messages', 'algo-forms'); ?></h2>
            <table class="form-table" role="presentation">
                <tr>
                    <th><label for="msg_submit_label"><?php esc_html_e('Submit button', 'algo-forms'); ?></label></th>
                    <td><input type="text" class="regular-text" name="msg_submit_label" id="msg_submit_label" value="<?php echo esc_attr($messages['submit_label']); ?>"></td>
                </tr>
                <tr>
                    <th><label for="msg_sending_label"><?php esc_html_e('Sending label', 'algo-forms'); ?></label></th>
                    <td><input type="text" class="regular-text" name="msg_sending_label" id="msg_sending_label" value="<?php echo esc_attr($messages['sending_label']); ?>"></td>
                </tr>
                <tr>
                    <th><label for="msg_success_message"><?php esc_html_e('Success message', 'algo-forms'); ?></label></th>
                    <td><input type="text" class="large-text" name="msg_success_message" id="msg_success_message" value="<?php echo esc_attr($messages['success_message']); ?>"></td>
                </tr>
                <tr>
                    <th><label for="msg_error_generic"><?php esc_html_e('Generic error', 'algo-forms'); ?></label></th>
                    <td><input type="text" class="large-text" name="msg_error_generic" id="msg_error_generic" value="<?php echo esc_attr($messages['error_generic']); ?>"></td>
                </tr>
                <tr>
                    <th><label for="msg_required_message"><?php esc_html_e('Required field message', 'algo-forms'); ?></label></th>
                    <td>
                        <input type="text" class="large-text" name="msg_required_message" id="msg_required_message" value="<?php echo esc_attr($messages['required_message']); ?>">
                        <p class="description"><?php esc_html_e('Use %s for the field label.', 'algo-forms'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><label for="msg_invalid_email_message"><?php esc_html_e('Invalid email message', 'algo-forms'); ?></label></th>
                    <td><input type="text" class="large-text" name="msg_invalid_email_message" id="msg_invalid_email_message" value="<?php echo esc_attr($messages['invalid_email_message']); ?>"></td>
                </tr>
            </table>

            <p class="submit">
                <button type="submit" class="button button-primary"><?php echo $form_id ? esc_html__('Update Form', 'algo-forms') : esc_html__('Create Form', 'algo-forms'); ?></button>
                <a class="button" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-list')); ?>"><?php esc_html_e('Back to All Forms', 'algo-forms'); ?></a>
            </p>
        </form>
    <?php
    algo_forms_admin_shell_end();
    ?>
    <style>
        .algo-admin-field-row { display:flex; flex-wrap:wrap; gap:8px; align-items:flex-start; margin:0 0 10px; padding:10px 12px; background:#f7fafc; border:1px solid #e4ebf4; border-radius:12px; }
        .algo-admin-field-order { display:inline-flex; flex-direction:column; gap:2px; }
        .algo-admin-field-row input[type="text"] { min-width:160px; }
        .algo-admin-field-row textarea { min-width:180px; }
        .algo-admin-field-row label { display:inline-flex; align-items:center; gap:4px; margin:0; }
    </style>
    <script>
    jQuery(function($){
        function reindex(){
            $('#algo-form-fields .algo-admin-field-row').each(function(i){
                $(this).find('input[type="checkbox"][name^="field_required"]').attr('name','field_required['+i+']');
            });
            var $rows = $('#algo-form-fields .algo-admin-field-row');
            $rows.each(function(i){
                $(this).find('.algo-move-up').prop('disabled', i===0);
                $(this).find('.algo-move-down').prop('disabled', i===$rows.length-1);
            });
        }
        function rowTpl(i){
            return '<div class="algo-admin-field-row">'+
                '<span class="algo-admin-field-order"><button type="button" class="button button-small algo-move-up">&#8593;</button><button type="button" class="button button-small algo-move-down">&#8595;</button></span>'+
                '<input type="hidden" name="field_key[]" value="">'+
                '<input type="text" name="field_label[]" placeholder="Label" required>'+
                '<select name="field_type[]"><option value="text">Text</option><option value="email">Email</option><option value="tel">Phone</option><option value="select">Select</option><option value="textarea">Textarea</option></select>'+
                '<textarea name="field_options[]" rows="2" placeholder="Select options (one per line)"></textarea>'+
                '<label><input type="checkbox" name="field_required['+i+']" value="1"> Required</label>'+
                '<button type="button" class="button algo-remove-field">Remove</button></div>';
        }
        $('#algo-add-field').on('click', function(){
            $('#algo-form-fields').append(rowTpl($('#algo-form-fields .algo-admin-field-row').length));
            reindex();
        });
        $(document).on('click','.algo-remove-field', function(){ $(this).closest('.algo-admin-field-row').remove(); reindex(); });
        $(document).on('click','.algo-move-up', function(){ var $r=$(this).closest('.algo-admin-field-row'); var $p=$r.prev('.algo-admin-field-row'); if($p.length){ $r.insertBefore($p); reindex(); }});
        $(document).on('click','.algo-move-down', function(){ var $r=$(this).closest('.algo-admin-field-row'); var $n=$r.next('.algo-admin-field-row'); if($n.length){ $r.insertAfter($n); reindex(); }});
        reindex();
    });
    </script>
    <?php
}

/**
 * @param object $submission
 * @param string $search
 * @return bool
 */
function algo_forms_submission_matches_search($submission, $search)
{
    if ($search === '') {
        return true;
    }
    $hay = strtolower((string) $submission->id . ' ' . $submission->submission_date . ' ' . $submission->form_data);
    return strpos($hay, strtolower($search)) !== false;
}

/**
 * @return void
 */
function algo_forms_handle_submission_pro_actions()
{
    if (!is_admin() || !current_user_can(ALGO_FORMS_CAP) || !algo_forms_pro_feature('submission_inbox')) {
        return;
    }

    $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
    if ($page !== 'algo-forms-submissions') {
        return;
    }

    global $wpdb;
    $subs = $wpdb->prefix . 'algo_form_submissions';
    $forms = $wpdb->prefix . 'algo_forms';

    // Save notes.
    if (
        isset($_POST['algo_forms_save_notes']) &&
        isset($_POST['_wpnonce']) &&
        wp_verify_nonce($_POST['_wpnonce'], 'algo_forms_submission_notes')
    ) {
        $id = isset($_POST['submission_id']) ? (int) $_POST['submission_id'] : 0;
        $notes = isset($_POST['admin_notes']) ? sanitize_textarea_field(wp_unslash($_POST['admin_notes'])) : '';
        if ($id) {
            algo_forms_maybe_upgrade_submissions_pro_columns();
            $wpdb->update($subs, array('admin_notes' => $notes), array('id' => $id), array('%s'), array('%d'));
        }
        wp_safe_redirect(add_query_arg(array('page' => 'algo-forms-submissions', 'view' => $id, 'notes_saved' => '1'), admin_url('admin.php')));
        exit;
    }

    // Toggle read / unread / resend.
    if (!isset($_GET['pro_action'], $_GET['id'])) {
        return;
    }
    $id = (int) $_GET['id'];
    $action = sanitize_key(wp_unslash($_GET['pro_action']));
    if (!$id || !in_array($action, array('mark_read', 'mark_unread', 'resend'), true)) {
        return;
    }
    if (!check_admin_referer('algo_forms_pro_sub_' . $action . '_' . $id)) {
        return;
    }

    algo_forms_maybe_upgrade_submissions_pro_columns();
    $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$subs} WHERE id = %d", $id));
    if (!$row) {
        return;
    }

    if ($action === 'mark_read') {
        $wpdb->update($subs, array('status' => 'read'), array('id' => $id), array('%s'), array('%d'));
    } elseif ($action === 'mark_unread') {
        $wpdb->update($subs, array('status' => 'unread'), array('id' => $id), array('%s'), array('%d'));
    } elseif ($action === 'resend' && algo_forms_pro_feature('resend')) {
        $form = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$forms} WHERE id = %d", (int) $row->form_id));
        $data = json_decode($row->form_data, true);
        if ($form && is_array($data)) {
            $fields = algo_forms_normalize_fields(json_decode($form->fields, true) ?: array());
            algo_forms_send_notification($form, $data, $fields, $id);
            set_transient('algo_forms_resend_' . get_current_user_id(), 1, 60);
        }
    }

    $redirect = array('page' => 'algo-forms-submissions', 'view' => $id);
    if ($action === 'resend') {
        $redirect['resent'] = '1';
    }
    wp_safe_redirect(add_query_arg($redirect, admin_url('admin.php')));
    exit;
}
add_action('admin_init', 'algo_forms_handle_submission_pro_actions');

/**
 * Render a single submission detail (Pro inbox).
 *
 * @param object $submission Submission row joined with form fields.
 * @return void
 */
function algo_forms_render_submission_detail($submission)
{
    $data = json_decode($submission->form_data, true);
    if (!is_array($data)) {
        $data = array();
    }
    $status = isset($submission->status) ? (string) $submission->status : 'unread';
    $notes = isset($submission->admin_notes) ? (string) $submission->admin_notes : '';
    $id = (int) $submission->id;

    echo '<div class="af-panel">';
    echo '<div class="af-panel-head">';
    echo '<h2>' . esc_html(sprintf(
        /* translators: 1: form title, 2: submission id */
        __('Submission #%2$d — %1$s', 'algo-forms'),
        $submission->form_title ?: __('Unknown Form', 'algo-forms'),
        $id
    )) . '</h2>';
    echo '<a class="button" href="' . esc_url(admin_url('admin.php?page=algo-forms-submissions')) . '">' . esc_html__('← Back to list', 'algo-forms') . '</a>';
    echo '</div>';

    if (!empty($_GET['notes_saved'])) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Notes saved.', 'algo-forms') . '</p></div>';
    }
    if (!empty($_GET['resent'])) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Notification resent (check Delivery log for results).', 'algo-forms') . '</p></div>';
    }

    echo '<p><strong>' . esc_html__('Date:', 'algo-forms') . '</strong> ' . esc_html((string) $submission->submission_date);
    echo ' · <strong>' . esc_html__('Status:', 'algo-forms') . '</strong> ';
    echo esc_html($status === 'read' ? __('Read', 'algo-forms') : __('Unread', 'algo-forms'));
    echo '</p>';

    echo '<div class="af-detail-actions" style="display:flex;flex-wrap:wrap;gap:0.5rem;margin:0 0 1rem;">';
    if ($status === 'read') {
        echo '<a class="button" href="' . esc_url(wp_nonce_url(admin_url('admin.php?page=algo-forms-submissions&view=' . $id . '&pro_action=mark_unread&id=' . $id), 'algo_forms_pro_sub_mark_unread_' . $id)) . '">' . esc_html__('Mark unread', 'algo-forms') . '</a>';
    } else {
        echo '<a class="button" href="' . esc_url(wp_nonce_url(admin_url('admin.php?page=algo-forms-submissions&view=' . $id . '&pro_action=mark_read&id=' . $id), 'algo_forms_pro_sub_mark_read_' . $id)) . '">' . esc_html__('Mark read', 'algo-forms') . '</a>';
    }
    if (algo_forms_pro_feature('resend')) {
        echo '<a class="button button-primary" href="' . esc_url(wp_nonce_url(admin_url('admin.php?page=algo-forms-submissions&view=' . $id . '&pro_action=resend&id=' . $id), 'algo_forms_pro_sub_resend_' . $id)) . '" onclick="return confirm(\'' . esc_js(__('Resend company notification for this submission?', 'algo-forms')) . '\');">' . esc_html__('Resend notification', 'algo-forms') . '</a>';
    }
    echo '<a class="button" href="' . esc_url(wp_nonce_url(admin_url('admin.php?page=algo-forms-submissions&action=delete&id=' . $id), 'algo_forms_del_sub_' . $id)) . '" onclick="return confirm(\'' . esc_js(__('Delete?', 'algo-forms')) . '\');">' . esc_html__('Delete', 'algo-forms') . '</a>';
    echo '</div>';

    echo '<table class="wp-list-table widefat striped"><tbody>';
    foreach ($data as $k => $v) {
        echo '<tr><th style="width:28%;">' . esc_html((string) $k) . '</th><td>' . nl2br(esc_html((string) $v)) . '</td></tr>';
    }
    echo '</tbody></table>';

    if (algo_forms_pro_feature('notes')) {
        echo '<form method="post" style="margin-top:1.25rem;">';
        wp_nonce_field('algo_forms_submission_notes');
        echo '<input type="hidden" name="submission_id" value="' . esc_attr((string) $id) . '">';
        echo '<h3>' . esc_html__('Admin notes', 'algo-forms') . '</h3>';
        echo '<textarea class="large-text" rows="4" name="admin_notes">' . esc_textarea($notes) . '</textarea>';
        echo '<p class="submit"><button type="submit" name="algo_forms_save_notes" value="1" class="button button-primary">' . esc_html__('Save notes', 'algo-forms') . '</button></p>';
        echo '</form>';
    }

    echo '</div>';
}

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

    global $wpdb;
    $subs = $wpdb->prefix . 'algo_form_submissions';
    $forms = $wpdb->prefix . 'algo_forms';
    $inbox = algo_forms_pro_feature('submission_inbox');

    if ($inbox) {
        algo_forms_maybe_upgrade_submissions_pro_columns();
    }

    if (
        isset($_POST['algo_forms_bulk_delete']) &&
        isset($_POST['_wpnonce']) &&
        wp_verify_nonce($_POST['_wpnonce'], 'algo_forms_bulk_delete')
    ) {
        $ids = isset($_POST['submission_ids']) && is_array($_POST['submission_ids'])
            ? array_map('intval', $_POST['submission_ids'])
            : array();
        $ids = array_values(array_filter($ids));
        if ($ids) {
            $placeholders = implode(',', array_fill(0, count($ids), '%d'));
            $wpdb->query($wpdb->prepare("DELETE FROM {$subs} WHERE id IN ({$placeholders})", $ids));
            echo '<div class="notice notice-success"><p>' . esc_html__('Selected submissions deleted.', 'algo-forms') . '</p></div>';
        }
    }

    if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'delete' && check_admin_referer('algo_forms_del_sub_' . (int) $_GET['id'])) {
        $wpdb->delete($subs, array('id' => (int) $_GET['id']), array('%d'));
        echo '<div class="notice notice-success"><p>' . esc_html__('Submission deleted.', 'algo-forms') . '</p></div>';
    }

    // Pro detail view.
    if ($inbox && !empty($_GET['view'])) {
        $view_id = (int) $_GET['view'];
        $detail = $wpdb->get_row($wpdb->prepare(
            "SELECT s.*, f.form_title, f.form_name
             FROM {$subs} s
             LEFT JOIN {$forms} f ON s.form_id = f.id
             WHERE s.id = %d",
            $view_id
        ));
        algo_forms_admin_shell_start(
            __('Submission', 'algo-forms'),
            __('Pro inbox — notes, read state, and resend.', 'algo-forms'),
            'peach'
        );
        if ($detail) {
            // Auto-mark read when opening.
            if (empty($detail->status) || $detail->status === 'unread') {
                $wpdb->update($subs, array('status' => 'read'), array('id' => $view_id), array('%s'), array('%d'));
                $detail->status = 'read';
            }
            algo_forms_render_submission_detail($detail);
        } else {
            echo '<div class="af-empty af-panel"><p>' . esc_html__('Submission not found.', 'algo-forms') . '</p></div>';
        }
        algo_forms_admin_shell_end();
        return;
    }

    $search = isset($_GET['s']) ? sanitize_text_field(wp_unslash($_GET['s'])) : '';
    $all = $wpdb->get_results("
        SELECT s.*, f.form_title, f.form_name
        FROM {$subs} s
        LEFT JOIN {$forms} f ON s.form_id = f.id
        ORDER BY f.form_title ASC, s.submission_date DESC
    ");

    $grouped = array();
    foreach ($all as $submission) {
        if (!algo_forms_submission_matches_search($submission, $search)) {
            continue;
        }
        $title = $submission->form_title ?: __('Unknown Form', 'algo-forms');
        if (!isset($grouped[$title])) {
            $grouped[$title] = array(
                'form_id' => (int) $submission->form_id,
                'items' => array(),
            );
        }
        $grouped[$title]['items'][] = $submission;
    }
    algo_forms_admin_shell_start(
        __('Submissions', 'algo-forms'),
        $inbox
            ? __('Pro inbox — open an entry for notes and resend. CSV export stays available for everyone.', 'algo-forms')
            : __('Review inbox entries, export CSV, or clean up old messages.', 'algo-forms'),
        'peach'
    );
    ?>
        <?php if (!$inbox) : ?>
            <div class="af-status-card is-info" style="margin-bottom:1rem;">
                <span class="af-status-icon"><?php echo algo_forms_admin_icon('inbox'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <div>
                    <strong><?php esc_html_e('Want a Pro inbox?', 'algo-forms'); ?> <?php echo algo_forms_pro_badge_html(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></strong>
                    <p><?php esc_html_e('Activate Pro for detail view, admin notes, read/unread, and resend notification.', 'algo-forms'); ?></p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-pro')); ?>"><?php esc_html_e('Open Pro settings', 'algo-forms'); ?></a>
                </div>
            </div>
        <?php endif; ?>

        <form method="get" class="af-panel" style="display:flex; gap:0.6rem; align-items:center; flex-wrap:wrap;">
            <input type="hidden" name="page" value="algo-forms-submissions">
            <input type="search" name="s" class="regular-text" value="<?php echo esc_attr($search); ?>" placeholder="<?php esc_attr_e('Search…', 'algo-forms'); ?>">
            <button class="button button-primary"><?php esc_html_e('Search', 'algo-forms'); ?></button>
        </form>

        <?php if (!$grouped) : ?>
            <div class="af-empty af-panel"><p><?php esc_html_e('No submissions found.', 'algo-forms'); ?></p></div>
        <?php else : ?>
            <?php foreach ($grouped as $title => $group) : ?>
                <div class="af-panel">
                <div class="af-panel-head">
                    <h2><?php echo esc_html($title); ?> (<?php echo (int) count($group['items']); ?>)</h2>
                    <a class="button" href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=algo-forms-submissions&action=download&form_id=' . (int) $group['form_id']), 'algo_forms_download_' . (int) $group['form_id'])); ?>">
                        <?php esc_html_e('Download CSV', 'algo-forms'); ?>
                    </a>
                </div>
                <form method="post">
                    <?php wp_nonce_field('algo_forms_bulk_delete'); ?>
                    <input type="hidden" name="algo_forms_bulk_delete" value="1">
                    <p><button type="submit" class="button" onclick="return confirm('<?php echo esc_js(__('Delete selected?', 'algo-forms')); ?>');"><?php esc_html_e('Delete Selected', 'algo-forms'); ?></button></p>
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th style="width:36px;"></th>
                                <th style="width:70px;"><?php esc_html_e('ID', 'algo-forms'); ?></th>
                                <?php if ($inbox) : ?>
                                    <th style="width:80px;"><?php esc_html_e('Status', 'algo-forms'); ?></th>
                                <?php endif; ?>
                                <th style="width:160px;"><?php esc_html_e('Page', 'algo-forms'); ?></th>
                                <th><?php esc_html_e('Data', 'algo-forms'); ?></th>
                                <th style="width:150px;"><?php esc_html_e('Date', 'algo-forms'); ?></th>
                                <th style="width:120px;"><?php esc_html_e('Actions', 'algo-forms'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($group['items'] as $submission) :
                                $data = json_decode($submission->form_data, true);
                                if (!is_array($data)) {
                                    $data = array();
                                }
                                $page = isset($data['Page']) ? (string) $data['Page'] : '—';
                                unset($data['Page']);
                                $status = isset($submission->status) ? (string) $submission->status : 'unread';
                                $row_class = ($inbox && $status !== 'read') ? 'af-row-unread' : '';
                                ?>
                                <tr class="<?php echo esc_attr($row_class); ?>">
                                    <td><input type="checkbox" name="submission_ids[]" value="<?php echo esc_attr((string) $submission->id); ?>"></td>
                                    <td><?php echo esc_html((string) $submission->id); ?></td>
                                    <?php if ($inbox) : ?>
                                        <td><?php echo esc_html($status === 'read' ? __('Read', 'algo-forms') : __('Unread', 'algo-forms')); ?></td>
                                    <?php endif; ?>
                                    <td><?php echo esc_html($page); ?></td>
                                    <td>
                                        <?php foreach ($data as $k => $v) : ?>
                                            <div><strong><?php echo esc_html((string) $k); ?>:</strong> <?php echo esc_html((string) $v); ?></div>
                                        <?php endforeach; ?>
                                    </td>
                                    <td><?php echo esc_html($submission->submission_date); ?></td>
                                    <td>
                                        <?php if ($inbox) : ?>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-submissions&view=' . (int) $submission->id)); ?>"><?php esc_html_e('Open', 'algo-forms'); ?></a>
                                            |
                                        <?php endif; ?>
                                        <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=algo-forms-submissions&action=delete&id=' . (int) $submission->id), 'algo_forms_del_sub_' . (int) $submission->id)); ?>"
                                            onclick="return confirm('<?php echo esc_js(__('Delete?', 'algo-forms')); ?>');"><?php esc_html_e('Delete', 'algo-forms'); ?></a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </form>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    <?php
    algo_forms_admin_shell_end();
}
