<?php
/**
 * Kantan Analytics - Form Plugin Integrations
 * Auto-detects active form plugins and tracks submissions as conversions.
 * Zero configuration — just activate and go.
 */

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

/**
 * Enqueue the front-end form session-field injector (no inline <script>). The
 * script self-guards: with no Kantan session/visitor id in storage it no-ops,
 * so loading it on every front-end request is harmless.
 */
function kantan_enqueue_form_fields() {
    wp_enqueue_script(
        'kantan-form-fields',
        KANTAN_ANALYTICS_PLUGIN_URL . 'assets/js/form-fields.js',
        array(),
        KANTAN_ANALYTICS_VERSION,
        true
    );
}
add_action('wp_enqueue_scripts', 'kantan_enqueue_form_fields');

/**
 * Record a form conversion in the database
 */
function kantan_record_form_conversion($session_id, $visitor_id, $form_plugin, $form_title, $page_url = '') {
    global $wpdb;

    if (empty($session_id)) return;

    $table = $wpdb->prefix . 'kantan_conversions';

    $wpdb->insert($table, array(
        'property_id'      => kantan_get_property_id(),
        'session_id'       => sanitize_text_field($session_id),
        'visitor_id'       => sanitize_text_field($visitor_id),
        'conversion_type'  => 'form_submit',
        'conversion_label' => sanitize_text_field($form_title),
        'conversion_value' => sanitize_text_field($form_plugin),
        'page_url'         => esc_url_raw($page_url ?: wp_get_referer()),
    ));

    do_action('kantan_conversion_tracked', $session_id, 'form_submit', array(
        'form_plugin' => $form_plugin,
        'form_title'  => $form_title,
        'visitor_id'  => $visitor_id,
    ));
}

/**
 * Register all form plugin hooks after all plugins are loaded
 */
function kantan_register_form_integrations() {

    // Contact Form 7
    if (defined('WPCF7_VERSION')) {
        add_action('wpcf7_mail_sent', function($contact_form) {
            $submission = WPCF7_Submission::get_instance();
            if (!$submission) return;

            $data = $submission->get_posted_data();
            $session_id = $data['kantan_session_id'] ?? '';
            $visitor_id = $data['kantan_visitor_id'] ?? '';

            kantan_record_form_conversion($session_id, $visitor_id, 'Contact Form 7', $contact_form->title());
        });
    }

    // WPForms
    if (defined('WPFORMS_VERSION')) {
        add_action('wpforms_process_complete', function($fields, $entry, $form_data, $entry_id) {
            $session_id = sanitize_text_field(wp_unslash($_POST['kantan_session_id'] ?? ''));
            $visitor_id = sanitize_text_field(wp_unslash($_POST['kantan_visitor_id'] ?? ''));
            $form_title = $form_data['settings']['form_title'] ?? 'WPForms';

            kantan_record_form_conversion($session_id, $visitor_id, 'WPForms', $form_title);
        }, 10, 4);
    }

    // Gravity Forms
    if (class_exists('GFForms')) {
        add_action('gform_after_submission', function($entry, $form) {
            $session_id = sanitize_text_field(wp_unslash($_POST['kantan_session_id'] ?? ''));
            $visitor_id = sanitize_text_field(wp_unslash($_POST['kantan_visitor_id'] ?? ''));
            $form_title = $form['title'] ?? 'Gravity Form';

            kantan_record_form_conversion($session_id, $visitor_id, 'Gravity Forms', $form_title);
        }, 10, 2);
    }

    // Formidable Forms
    if (class_exists('FrmAppHelper')) {
        add_action('frm_after_create_entry', function($entry_id, $form_id) {
            $session_id = sanitize_text_field(wp_unslash($_POST['kantan_session_id'] ?? ''));
            $visitor_id = sanitize_text_field(wp_unslash($_POST['kantan_visitor_id'] ?? ''));

            $form_title = 'Formidable Form';
            if (class_exists('FrmForm')) {
                $form = FrmForm::getOne($form_id);
                if ($form) {
                    $form_title = $form->name;
                }
            }

            kantan_record_form_conversion($session_id, $visitor_id, 'Formidable Forms', $form_title);
        }, 10, 2);
    }

    // Ninja Forms
    if (function_exists('Ninja_Forms')) {
        add_action('ninja_forms_after_submission', function($form_data) {
            $session_id = '';
            $visitor_id = '';

            // Ninja Forms passes fields differently
            if (isset($form_data['fields'])) {
                foreach ($form_data['fields'] as $field) {
                    if (isset($field['key'])) {
                        if ($field['key'] === 'kantan_session_id') {
                            $session_id = $field['value'] ?? '';
                        } elseif ($field['key'] === 'kantan_visitor_id') {
                            $visitor_id = $field['value'] ?? '';
                        }
                    }
                }
            }

            if (empty($session_id)) {
                $session_id = sanitize_text_field(wp_unslash($_POST['kantan_session_id'] ?? ''));
            }
            if (empty($visitor_id)) {
                $visitor_id = sanitize_text_field(wp_unslash($_POST['kantan_visitor_id'] ?? ''));
            }

            $form_title = $form_data['settings']['title'] ?? 'Ninja Form';

            kantan_record_form_conversion($session_id, $visitor_id, 'Ninja Forms', $form_title);
        });
    }

    // Elementor Pro Forms
    if (defined('ELEMENTOR_PRO_VERSION')) {
        add_action('elementor_pro/forms/new_record', function($record, $ajax_handler) {
            $raw_fields = $record->get('fields');
            $form_name = $record->get_form_settings('form_name') ?: 'Elementor Form';

            $session_id = sanitize_text_field(wp_unslash($_POST['kantan_session_id'] ?? ''));
            $visitor_id = sanitize_text_field(wp_unslash($_POST['kantan_visitor_id'] ?? ''));

            if (empty($session_id) && isset($raw_fields['kantan_session_id'])) {
                $session_id = $raw_fields['kantan_session_id']['value'] ?? '';
            }
            if (empty($visitor_id) && isset($raw_fields['kantan_visitor_id'])) {
                $visitor_id = $raw_fields['kantan_visitor_id']['value'] ?? '';
            }

            kantan_record_form_conversion($session_id, $visitor_id, 'Elementor Forms', $form_name);
        }, 10, 2);
    }

    // Fluent Forms
    if (defined('FLUENTFORM_VERSION') || defined('FLUENTFORM')) {
        add_action('fluentform/submission_inserted', function($insert_id, $form_data, $form) {
            $session_id = sanitize_text_field(wp_unslash($_POST['kantan_session_id'] ?? ''));
            $visitor_id = sanitize_text_field(wp_unslash($_POST['kantan_visitor_id'] ?? ''));
            $form_title = $form->title ?? 'Fluent Form';

            kantan_record_form_conversion($session_id, $visitor_id, 'Fluent Forms', $form_title);
        }, 10, 3);
    }

    // Forminator
    if (defined('FORMINATOR_VERSION')) {
        add_action('forminator_form_after_save_entry', function($form_id, $response) {
            $session_id = sanitize_text_field(wp_unslash($_POST['kantan_session_id'] ?? ''));
            $visitor_id = sanitize_text_field(wp_unslash($_POST['kantan_visitor_id'] ?? ''));

            $form_title = 'Forminator Form';
            if (class_exists('Forminator_API')) {
                $form = Forminator_API::get_module($form_id);
                if ($form && isset($form->settings['formName'])) {
                    $form_title = $form->settings['formName'];
                }
            }

            kantan_record_form_conversion($session_id, $visitor_id, 'Forminator', $form_title);
        }, 10, 2);
    }
}
add_action('plugins_loaded', 'kantan_register_form_integrations', 20);
