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

/**
 * @return void
 */
function algo_forms_handle_submission()
{
    global $wpdb;

    $form_id = isset($_POST['form_id']) ? (int) $_POST['form_id'] : 0;
    if (!$form_id) {
        wp_send_json_error(__('Form ID is required.', 'algo-forms'));
    }

    $nonce = isset($_POST['nonce']) ? wp_unslash($_POST['nonce']) : '';
    $nonce_ok = is_string($nonce) && wp_verify_nonce($nonce, 'algo_forms_nonce');
    if (!$nonce_ok) {
        $fallback = isset($_POST['af_form_token']) ? wp_unslash($_POST['af_form_token']) : '';
        $token_ok = algo_forms_verify_form_token($form_id, is_string($fallback) ? $fallback : '');
        if (!$token_ok && !algo_forms_is_same_origin_submission()) {
            wp_send_json_error(__('Invalid security token.', 'algo-forms'));
        }
    }

    $form = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}algo_forms WHERE id = %d",
        $form_id
    ));
    if (!$form) {
        wp_send_json_error(__('Form not found.', 'algo-forms'));
    }

    $spam_error = function_exists('algo_forms_check_spam') ? algo_forms_check_spam($form_id) : '';
    if ($spam_error !== '') {
        wp_send_json_error($spam_error);
    }

    $fields = algo_forms_normalize_fields(json_decode($form->fields, true) ?: array());
    if (empty($fields)) {
        wp_send_json_error(__('Form has no fields.', 'algo-forms'));
    }

    $messages = algo_forms_get_form_messages($form);
    $required_tpl = $messages['required_message'] ?? '%s is required.';
    $invalid_email_tpl = $messages['invalid_email_message'] ?? 'Please enter a valid email for %s.';
    $success_message = $messages['success_message'] ?? __('Thank you. Your message has been sent.', 'algo-forms');

    $form_data = array();
    foreach ($fields as $index => $field) {
        $field_key = algo_forms_field_key($field, $index);
        $field_label = (string) ($field['label'] ?? $field_key);
        $raw = isset($_POST[$field_key]) ? wp_unslash($_POST[$field_key]) : '';
        $value = (($field['type'] ?? '') === 'textarea')
            ? sanitize_textarea_field(is_string($raw) ? $raw : '')
            : sanitize_text_field(is_string($raw) ? $raw : '');

        if (!empty($field['required']) && $value === '') {
            wp_send_json_error(sprintf($required_tpl, $field_label));
        }

        if (($field['type'] ?? '') === 'email' && $value !== '' && !is_email($value)) {
            wp_send_json_error(sprintf($invalid_email_tpl, $field_label));
        }

        $form_data[$field['label'] !== '' ? $field['label'] : $field_key] = $value;
    }

    $page_url = isset($_POST['page_url']) ? wp_unslash($_POST['page_url']) : '';
    $page_url = is_string($page_url) ? $page_url : '';
    $page_title = isset($_POST['page_title']) ? sanitize_text_field(wp_unslash($_POST['page_title'])) : '';
    $plugin_name = isset($_POST['plugin_name']) ? sanitize_text_field(wp_unslash($_POST['plugin_name'])) : '';
    if ($page_url === '' && !empty($_SERVER['HTTP_REFERER'])) {
        $page_url = wp_unslash($_SERVER['HTTP_REFERER']);
        $page_url = is_string($page_url) ? $page_url : '';
    }

    $page_display = '';
    $parsed = $page_url !== '' ? wp_parse_url($page_url) : false;
    $path = ($parsed && isset($parsed['path'])) ? trim((string) $parsed['path'], '/') : '';
    $home_path = trim((string) wp_parse_url(home_url('/'), PHP_URL_PATH), '/');
    $is_home = ($path === '' || $path === $home_path) || (rtrim($page_url, '/') === rtrim(home_url('/'), '/'));
    $is_site_name = $page_title !== '' && strcasecmp(trim($page_title), get_bloginfo('name')) === 0;
    if ($is_home || $is_site_name) {
        $page_display = __('Home', 'algo-forms');
    } elseif ($page_title !== '') {
        $page_display = $page_title;
    } elseif ($path !== '') {
        $page_display = $path;
    }
    $form_data['Page'] = $page_display !== '' ? $page_display : '-';

    if ($plugin_name !== '') {
        // Put Plugin first so email/admin views lead with the product context.
        $form_data = array_merge(array('Plugin' => $plugin_name), $form_data);
    }

    // Prefer Free core insert; add Pro inbox columns only when schema already has them.
    $insert = array(
        'form_id' => $form_id,
        'form_data' => wp_json_encode($form_data),
        'submission_date' => current_time('mysql'),
    );
    $formats = array('%d', '%s', '%s');

    if (function_exists('algo_forms_submissions_have_pro_columns') && algo_forms_submissions_have_pro_columns()) {
        $insert['status'] = 'unread';
        $insert['admin_notes'] = '';
        $insert['ip_hash'] = function_exists('algo_forms_client_ip_hash') ? algo_forms_client_ip_hash() : '';
        $formats = array('%d', '%s', '%s', '%s', '%s', '%s');
    } elseif (function_exists('algo_forms_is_pro') && algo_forms_is_pro() && function_exists('algo_forms_maybe_upgrade_submissions_pro_columns')) {
        // Pro sites may still be mid-upgrade — ensure columns, then include them.
        algo_forms_maybe_upgrade_submissions_pro_columns();
        if (algo_forms_submissions_have_pro_columns()) {
            $insert['status'] = 'unread';
            $insert['admin_notes'] = '';
            $insert['ip_hash'] = function_exists('algo_forms_client_ip_hash') ? algo_forms_client_ip_hash() : '';
            $formats = array('%d', '%s', '%s', '%s', '%s', '%s');
        }
    }

    $result = $wpdb->insert($wpdb->prefix . 'algo_form_submissions', $insert, $formats);

    if ($result === false && count($insert) > 3) {
        // Fallback: Free core columns only.
        $result = $wpdb->insert(
            $wpdb->prefix . 'algo_form_submissions',
            array(
                'form_id' => $form_id,
                'form_data' => wp_json_encode($form_data),
                'submission_date' => current_time('mysql'),
            ),
            array('%d', '%s', '%s')
        );
    }

    if ($result === false) {
        error_log('algo-forms: DB insert failed: ' . $wpdb->last_error);
        wp_send_json_error(__('Failed to save submission.', 'algo-forms'));
    }

    $submission_id = (int) $wpdb->insert_id;
    if (function_exists('algo_forms_spam_rate_limit_hit')) {
        algo_forms_spam_rate_limit_hit();
    }
    algo_forms_send_notification($form, $form_data, $fields, $submission_id);
    wp_send_json_success($success_message);
}
add_action('wp_ajax_algo_forms_submission', 'algo_forms_handle_submission');
add_action('wp_ajax_nopriv_algo_forms_submission', 'algo_forms_handle_submission');
