<?php
/**
 * Plugin Name: LeadMachine Connector
 * Plugin URI: https://leadmachine.fyi/wordpress
 * Description: Connect your WordPress site to LeadMachine to capture and manage leads seamlessly. Supports native forms and Gravity Forms.
 * Version: 2.5.1
 * Author: LeadMachine
 * Author URI: https://leadmachine.fyi
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: leadmachine-connector
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('LEADMACHINE_VERSION', '2.5.1');
define('LEADMACHINE_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('LEADMACHINE_PLUGIN_URL', plugin_dir_url(__FILE__));

// Include post sync functionality
require_once LEADMACHINE_PLUGIN_DIR . 'includes/post-sync.php';

/**
 * Main LeadMachine Connector Class
 */
class LeadMachine_Connector {

    private static $instance = null;

    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_assets'));

        // Form shortcodes
        add_shortcode('leadmachine_form', array($this, 'render_lead_form'));
        add_shortcode('leadmachine_newsletter', array($this, 'render_newsletter_form'));

        // AJAX handlers for form submissions
        add_action('wp_ajax_leadmachine_submit', array($this, 'handle_form_submission'));
        add_action('wp_ajax_nopriv_leadmachine_submit', array($this, 'handle_form_submission'));
        add_action('wp_ajax_leadmachine_newsletter_submit', array($this, 'handle_newsletter_submission'));
        add_action('wp_ajax_nopriv_leadmachine_newsletter_submit', array($this, 'handle_newsletter_submission'));

        // AJAX handler for getting Gravity Forms fields
        add_action('wp_ajax_leadmachine_get_gf_fields', array($this, 'ajax_get_gf_fields'));

        // Gravity Forms integration hook
        add_action('gform_after_submission', array($this, 'handle_gravity_form_submission'), 10, 2);
    }

    /**
     * Add admin menu page
     */
    public function add_admin_menu() {
        add_menu_page(
            'LeadMachine Settings',
            'LeadMachine',
            'manage_options',
            'leadmachine-connector',
            array($this, 'render_settings_page'),
            'dashicons-admin-users',
            30
        );
    }

    /**
     * Register plugin settings
     */
    public function register_settings() {
        // Connection settings
        register_setting('leadmachine_settings', 'leadmachine_company_id', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_api_key', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_api_url', array(
            'type' => 'string',
            'sanitize_callback' => 'esc_url_raw',
        ));

        // Form customization settings
        register_setting('leadmachine_settings', 'leadmachine_form_title', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_form_description', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_success_message', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_button_text', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_button_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ));
        register_setting('leadmachine_settings', 'leadmachine_background_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ));
        register_setting('leadmachine_settings', 'leadmachine_title_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ));
        register_setting('leadmachine_settings', 'leadmachine_description_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ));
        register_setting('leadmachine_settings', 'leadmachine_label_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ));
        register_setting('leadmachine_settings', 'leadmachine_input_background', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ));
        register_setting('leadmachine_settings', 'leadmachine_input_border_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ));
        register_setting('leadmachine_settings', 'leadmachine_input_text_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ));

        // Gravity Forms settings
        register_setting('leadmachine_settings', 'leadmachine_gf_enabled', array(
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
        ));
        register_setting('leadmachine_settings', 'leadmachine_gf_forms', array(
            'type' => 'string',
            'sanitize_callback' => array($this, 'sanitize_json_field'),
        ));
        register_setting('leadmachine_settings', 'leadmachine_gf_default_tags', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ));

        // Post sync settings
        register_setting('leadmachine_settings', 'leadmachine_post_sync_enabled', array(
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
        ));
        register_setting('leadmachine_settings', 'leadmachine_post_sync_categories', array(
            'type' => 'array',
            'sanitize_callback' => array($this, 'sanitize_category_array'),
        ));

        // Newsletter form settings
        register_setting('leadmachine_settings', 'leadmachine_newsletter_title', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_newsletter_description', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_newsletter_success_message', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_newsletter_button_text', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_newsletter_optin_text', array(
            'type' => 'string',
            'sanitize_callback' => 'wp_kses_post',
        ));
        register_setting('leadmachine_settings', 'leadmachine_newsletter_name_label', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('leadmachine_settings', 'leadmachine_newsletter_email_label', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ));
    }

    /**
     * Sanitize category array for post sync
     */
    public function sanitize_category_array($value) {
        if (!is_array($value)) {
            return array();
        }
        return array_map('absint', $value);
    }

    /**
     * Sanitize JSON field for Gravity Forms mappings
     * Validates structure and sanitizes all values within the mapping
     */
    public function sanitize_json_field($value) {
        if (empty($value)) {
            return '{}';
        }

        // Validate it's valid JSON
        $decoded = json_decode($value, true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) {
            return '{}';
        }

        // Sanitize the decoded content - this is a form mappings structure
        // Expected format: { "form_id": { "enabled": bool, "first_name": "field_id", ... } }
        $sanitized = array();
        $allowed_mapping_keys = array('enabled', 'first_name', 'last_name', 'email', 'phone', 'company', 'message', 'tags');

        foreach ($decoded as $form_id => $form_mapping) {
            // Form ID must be a positive integer
            $form_id = absint($form_id);
            if ($form_id <= 0) {
                continue;
            }

            // Form mapping must be an array
            if (!is_array($form_mapping)) {
                continue;
            }

            $sanitized_mapping = array();

            foreach ($form_mapping as $key => $value) {
                // Only allow expected keys
                if (!in_array($key, $allowed_mapping_keys, true)) {
                    continue;
                }

                if ($key === 'enabled') {
                    // Boolean value
                    $sanitized_mapping[$key] = (bool) $value;
                } elseif ($key === 'tags') {
                    // Tags are comma-separated text
                    $sanitized_mapping[$key] = sanitize_text_field((string) $value);
                } else {
                    // Field IDs can be integers or decimals like "1.3" for compound fields
                    $field_value = (string) $value;
                    // Only allow numeric values (integers or decimals)
                    if ($field_value === '' || preg_match('/^\d+(\.\d+)?$/', $field_value)) {
                        $sanitized_mapping[$key] = $field_value;
                    }
                }
            }

            if (!empty($sanitized_mapping)) {
                $sanitized[$form_id] = $sanitized_mapping;
            }
        }

        return wp_json_encode($sanitized);
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook) {
        if ('toplevel_page_leadmachine-connector' !== $hook) {
            return;
        }

        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        wp_enqueue_style(
            'leadmachine-admin-css',
            LEADMACHINE_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            LEADMACHINE_VERSION
        );
        wp_enqueue_script(
            'leadmachine-admin-js',
            LEADMACHINE_PLUGIN_URL . 'assets/js/admin.js',
            array('jquery', 'wp-color-picker'),
            LEADMACHINE_VERSION,
            true
        );

        // Pass data to admin JS
        wp_localize_script('leadmachine-admin-js', 'leadmachineAdmin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('leadmachine_admin_nonce'),
            'gf_forms' => $this->get_gravity_forms_list()
        ));
    }

    /**
     * Enqueue frontend assets
     */
    public function enqueue_frontend_assets() {
        wp_enqueue_style(
            'leadmachine-frontend-css',
            LEADMACHINE_PLUGIN_URL . 'assets/css/frontend.css',
            array(),
            LEADMACHINE_VERSION
        );

        wp_enqueue_script(
            'leadmachine-frontend-js',
            LEADMACHINE_PLUGIN_URL . 'assets/js/frontend.js',
            array('jquery'),
            LEADMACHINE_VERSION,
            true
        );

        wp_localize_script('leadmachine-frontend-js', 'leadmachineData', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('leadmachine_nonce')
        ));
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        include LEADMACHINE_PLUGIN_DIR . 'includes/admin-settings.php';
    }

    /**
     * Render lead capture form
     */
    public function render_lead_form($atts) {
        $company_id = get_option('leadmachine_company_id');
        $api_key = get_option('leadmachine_api_key');

        if (empty($company_id)) {
            return '<div class="leadmachine-error">Please configure your LeadMachine Company ID in the plugin settings.</div>';
        }

        if (empty($api_key)) {
            return '<div class="leadmachine-error">Please configure your LeadMachine API Key in the plugin settings.</div>';
        }

        $atts = shortcode_atts(array(
            'title' => get_option('leadmachine_form_title', 'Get in Touch'),
            'description' => get_option('leadmachine_form_description', 'Fill out the form below and we\'ll get back to you soon.'),
            'button_text' => get_option('leadmachine_button_text', 'Submit'),
            'button_color' => get_option('leadmachine_button_color', '#0073aa'),
            'tags' => '', // Comma-separated list of tags, e.g., "newsletter,website"
            'background' => get_option('leadmachine_background_color', 'transparent'),
            'title_color' => get_option('leadmachine_title_color', '#333333'),
            'description_color' => get_option('leadmachine_description_color', '#666666'),
            'label_color' => get_option('leadmachine_label_color', '#333333'),
            'input_background' => get_option('leadmachine_input_background', '#ffffff'),
            'input_border_color' => get_option('leadmachine_input_border_color', '#dddddd'),
            'input_text_color' => get_option('leadmachine_input_text_color', '#333333'),
        ), $atts);

        ob_start();
        include LEADMACHINE_PLUGIN_DIR . 'includes/lead-form.php';
        return ob_get_clean();
    }

    /**
     * Render the newsletter signup form
     * Usage: [leadmachine_newsletter] or [leadmachine_newsletter title="Subscribe" tags="newsletter,website"]
     */
    public function render_newsletter_form($atts) {
        $company_id = get_option('leadmachine_company_id');
        $api_key = get_option('leadmachine_api_key');

        if (empty($company_id)) {
            return '<div class="leadmachine-error">Please configure your LeadMachine Company ID in the plugin settings.</div>';
        }

        if (empty($api_key)) {
            return '<div class="leadmachine-error">Please configure your LeadMachine API Key in the plugin settings.</div>';
        }

        $atts = shortcode_atts(array(
            'title' => get_option('leadmachine_newsletter_title', 'Subscribe to Our Newsletter'),
            'description' => get_option('leadmachine_newsletter_description', 'Get the latest updates delivered to your inbox.'),
            'button_text' => get_option('leadmachine_newsletter_button_text', 'Subscribe'),
            'button_color' => get_option('leadmachine_button_color', '#0073aa'),
            'tags' => 'newsletter', // Default tag for newsletter signups
            'background' => get_option('leadmachine_background_color', 'transparent'),
            'title_color' => get_option('leadmachine_title_color', '#333333'),
            'description_color' => get_option('leadmachine_description_color', '#666666'),
            'label_color' => get_option('leadmachine_label_color', '#333333'),
            'input_background' => get_option('leadmachine_input_background', '#ffffff'),
            'input_border_color' => get_option('leadmachine_input_border_color', '#dddddd'),
            'input_text_color' => get_option('leadmachine_input_text_color', '#333333'),
            'optin_text' => get_option('leadmachine_newsletter_optin_text', 'I agree to receive email updates and accept the <a href="https://app.leadmachine.fyi/pages/privacy.php" target="_blank" rel="noopener noreferrer">Privacy Policy</a>'),
            'name_label' => get_option('leadmachine_newsletter_name_label', 'Full Name'),
            'email_label' => get_option('leadmachine_newsletter_email_label', 'Email Address'),
            'name_placeholder' => 'John Smith',
            'email_placeholder' => 'your@email.com',
        ), $atts);

        ob_start();
        include LEADMACHINE_PLUGIN_DIR . 'includes/newsletter-form.php';
        return ob_get_clean();
    }

    /**
     * Handle newsletter form submission via AJAX
     */
    public function handle_newsletter_submission() {
        check_ajax_referer('leadmachine_nonce', 'nonce');

        // ─────────────── SPAM PROTECTION ───────────────

        // Check 1: Honeypot field (should be empty - bots fill hidden fields)
        $honeypot = isset($_POST['website_url']) ? sanitize_text_field(wp_unslash($_POST['website_url'])) : '';
        if (!empty($honeypot)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine Newsletter: Spam blocked (honeypot) from IP: ' . $this->get_client_ip());
            }
            wp_send_json_error(array('message' => 'Unable to submit form. Please try again.'));
        }

        // Check 2: Time-based validation
        $form_token = isset($_POST['form_token']) ? sanitize_text_field(wp_unslash($_POST['form_token'])) : '';
        if (!empty($form_token)) {
            $decoded = base64_decode($form_token);
            $parts = explode(':', $decoded);
            if (count($parts) >= 1) {
                $form_time = intval($parts[0]);
                $current_time = time();
                $elapsed = $current_time - $form_time;

                if ($elapsed < 3) {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                        error_log('LeadMachine Newsletter: Spam blocked (too fast: ' . $elapsed . 's) from IP: ' . $this->get_client_ip());
                    }
                    wp_send_json_error(array('message' => 'Please wait a moment before submitting.'));
                }

                if ($elapsed > 3600) {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                        error_log('LeadMachine Newsletter: Spam blocked (stale token: ' . $elapsed . 's) from IP: ' . $this->get_client_ip());
                    }
                    wp_send_json_error(array('message' => 'Form has expired. Please refresh the page and try again.'));
                }
            }
        }

        // ─────────────── END SPAM PROTECTION ───────────────

        $company_id = get_option('leadmachine_company_id');
        $api_key = get_option('leadmachine_api_key');
        $api_url = get_option('leadmachine_api_url', 'https://app.leadmachine.fyi');

        if (empty($company_id) || empty($api_key)) {
            wp_send_json_error(array('message' => 'Plugin not configured properly.'));
        }

        // Parse full name into first/last
        $full_name = isset($_POST['full_name']) ? sanitize_text_field(wp_unslash($_POST['full_name'])) : '';
        $name_parts = explode(' ', trim($full_name), 2);
        $first_name = $name_parts[0] ?? '';
        $last_name = $name_parts[1] ?? '';

        $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';

        // Validate required fields
        if (empty($full_name) || empty($email)) {
            wp_send_json_error(array('message' => 'Name and email are required.'));
        }

        if (!is_email($email)) {
            wp_send_json_error(array('message' => 'Please enter a valid email address.'));
        }

        // Get and sanitize analytics data
        $analytics_data = isset($_POST['analytics_data']) ? sanitize_text_field(wp_unslash($_POST['analytics_data'])) : '';

        $data = array(
            'company_id' => $company_id,
            'api_key' => $api_key,
            'first_name' => $first_name,
            'last_name' => $last_name,
            'contact_name' => trim($full_name),
            'contact_email' => $email,
            'source' => 'WordPress Newsletter',
            'source_url' => isset($_POST['source_url']) ? esc_url_raw(wp_unslash($_POST['source_url'])) : '',
            'tags' => isset($_POST['tags']) ? sanitize_text_field(wp_unslash($_POST['tags'])) : 'newsletter',
            'form_type' => 'newsletter',
            'analytics_data' => $analytics_data,
        );

        // Send to LeadMachine API
        $response = wp_remote_post(
            rtrim($api_url, '/') . '/api/leads/wordpress-submit.php',
            array(
                'body' => $data,
                'timeout' => 30,
                'headers' => array(
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ),
            )
        );

        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine Newsletter API Error: ' . $error_message);
            }
            wp_send_json_error(array('message' => 'Failed to submit: ' . $error_message));
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        $result = json_decode($response_body, true);

        if ($response_code === 200 && isset($result['success']) && $result['success']) {
            $success_message = get_option('leadmachine_newsletter_success_message', 'Thank you for subscribing! You\'ll hear from us soon.');
            wp_send_json_success(array('message' => $success_message));
        } else {
            $error_message = $result['error'] ?? 'Failed to submit. Server returned: ' . $response_code;
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine Newsletter submission failed: ' . $error_message);
            }
            wp_send_json_error(array('message' => $error_message));
        }
    }

    /**
     * Handle form submission via AJAX (native LeadMachine form)
     */
    public function handle_form_submission() {
        check_ajax_referer('leadmachine_nonce', 'nonce');

        // ─────────────── SPAM PROTECTION ───────────────

        // Check 1: Honeypot field (should be empty - bots fill hidden fields)
        $honeypot = isset($_POST['website_url']) ? sanitize_text_field(wp_unslash($_POST['website_url'])) : '';
        if (!empty($honeypot)) {
            // Log spam attempt but return generic error to not tip off bots
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine: Spam blocked (honeypot triggered) from IP: ' . $this->get_client_ip());
            }
            wp_send_json_error(array('message' => 'Unable to submit form. Please try again.'));
        }

        // Check 2: Time-based validation (form submitted too quickly = bot)
        $form_token = isset($_POST['form_token']) ? sanitize_text_field(wp_unslash($_POST['form_token'])) : '';
        if (!empty($form_token)) {
            $decoded = base64_decode($form_token);
            $parts = explode(':', $decoded);
            if (count($parts) >= 1) {
                $form_time = intval($parts[0]);
                $current_time = time();
                $elapsed = $current_time - $form_time;

                // If form was submitted in less than 3 seconds, likely a bot
                if ($elapsed < 3) {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                        error_log('LeadMachine: Spam blocked (too fast: ' . $elapsed . 's) from IP: ' . $this->get_client_ip());
                    }
                    wp_send_json_error(array('message' => 'Please wait a moment before submitting.'));
                }

                // If form token is older than 1 hour, reject (stale form)
                if ($elapsed > 3600) {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                        error_log('LeadMachine: Spam blocked (stale token: ' . $elapsed . 's) from IP: ' . $this->get_client_ip());
                    }
                    wp_send_json_error(array('message' => 'Form has expired. Please refresh the page and try again.'));
                }
            }
        }

        // ─────────────── END SPAM PROTECTION ───────────────

        $company_id = get_option('leadmachine_company_id');
        $api_key = get_option('leadmachine_api_key');
        $api_url = get_option('leadmachine_api_url', 'https://app.leadmachine.fyi');

        if (empty($company_id)) {
            wp_send_json_error(array('message' => 'Plugin not configured properly. Missing Company ID.'));
        }

        if (empty($api_key)) {
            wp_send_json_error(array('message' => 'Plugin not configured properly. Missing API Key.'));
        }

        // Sanitize input
        $first_name = isset($_POST['first_name']) ? sanitize_text_field(wp_unslash($_POST['first_name'])) : '';
        $last_name = isset($_POST['last_name']) ? sanitize_text_field(wp_unslash($_POST['last_name'])) : '';
        $contact_name = trim($first_name . ' ' . $last_name);

        // Get and sanitize analytics data
        $analytics_data = isset($_POST['analytics_data']) ? sanitize_text_field(wp_unslash($_POST['analytics_data'])) : '';

        $data = array(
            'company_id' => $company_id,
            'api_key' => $api_key,
            'company' => isset($_POST['company']) ? sanitize_text_field(wp_unslash($_POST['company'])) : '',
            'first_name' => $first_name,
            'last_name' => $last_name,
            'contact_name' => $contact_name,
            'contact_email' => isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '',
            'contact_phone' => isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : '',
            'message' => isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : '',
            'source' => 'WordPress Plugin',
            'source_url' => isset($_POST['source_url']) ? esc_url_raw(wp_unslash($_POST['source_url'])) : '',
            'tags' => isset($_POST['tags']) ? sanitize_text_field(wp_unslash($_POST['tags'])) : '',
            'form_type' => 'contact',
            'analytics_data' => $analytics_data,
        );

        // Validate required fields
        if (empty($first_name) || empty($last_name) || empty($data['contact_email'])) {
            wp_send_json_error(array('message' => 'First name, last name, and email are required.'));
        }

        if (!is_email($data['contact_email'])) {
            wp_send_json_error(array('message' => 'Please enter a valid email address.'));
        }

        // Send to LeadMachine API
        $response = wp_remote_post(
            rtrim($api_url, '/') . '/api/leads/wordpress-submit.php',
            array(
                'body' => $data,
                'timeout' => 30,
                'headers' => array(
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ),
            )
        );

        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine API Error: ' . $error_message);
            }
            wp_send_json_error(array('message' => 'Failed to submit lead: ' . $error_message));
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        // Log response for debugging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
            error_log('LeadMachine API Response Code: ' . $response_code);
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
            error_log('LeadMachine API Response Body: ' . $response_body);
        }

        $result = json_decode($response_body, true);

        if ($response_code === 200 && isset($result['success']) && $result['success']) {
            $success_message = get_option('leadmachine_success_message', 'Thank you! Your message has been received.');
            wp_send_json_success(array('message' => $success_message));
        } else {
            $error_message = $result['error'] ?? 'Failed to submit lead. Server returned: ' . $response_code;
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine submission failed: ' . $error_message);
            }
            wp_send_json_error(array('message' => $error_message));
        }
    }

    /**
     * Handle Gravity Forms submission
     */
    public function handle_gravity_form_submission($entry, $form) {
        // Check if Gravity Forms integration is enabled
        if (!get_option('leadmachine_gf_enabled')) {
            return;
        }

        // Check if entry is marked as spam by Gravity Forms
        if (isset($entry['status']) && $entry['status'] === 'spam') {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine GF: Entry marked as spam by Gravity Forms');
            }
            return;
        }

        $company_id = get_option('leadmachine_company_id');
        $api_key = get_option('leadmachine_api_key');
        $api_url = get_option('leadmachine_api_url', 'https://app.leadmachine.fyi');

        if (empty($company_id) || empty($api_key)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine GF: Missing Company ID or API Key');
            }
            return;
        }

        // Get form mappings
        $gf_forms = get_option('leadmachine_gf_forms', '{}');
        $mappings = json_decode($gf_forms, true);

        $form_id = $form['id'];

        // Check if this form has a mapping configured
        if (!isset($mappings[$form_id]) || empty($mappings[$form_id]['enabled'])) {
            // Form not configured for LeadMachine
            return;
        }

        $form_mapping = $mappings[$form_id];

        // Extract values from entry using field mappings
        $first_name = $this->get_gf_entry_value($entry, $form_mapping['first_name'] ?? '');
        $last_name = $this->get_gf_entry_value($entry, $form_mapping['last_name'] ?? '');
        $email = $this->get_gf_entry_value($entry, $form_mapping['email'] ?? '');
        $phone = $this->get_gf_entry_value($entry, $form_mapping['phone'] ?? '');
        $company_name = $this->get_gf_entry_value($entry, $form_mapping['company'] ?? '');
        $message = $this->get_gf_entry_value($entry, $form_mapping['message'] ?? '');

        // Validate required fields
        if (empty($email)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine GF: No email found in form submission');
            }
            return;
        }

        // Spam detection for names and content
        $spam_reason = $this->detect_spam($first_name, $last_name, $email, $message);
        if ($spam_reason) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine GF: Spam blocked (' . $spam_reason . ') - Name: ' . $first_name . ' ' . $last_name . ', Email: ' . $email);
            }
            return;
        }

        // Build contact name
        $contact_name = trim($first_name . ' ' . $last_name);
        if (empty($contact_name)) {
            $contact_name = $email; // Fallback to email if no name
        }

        // Get tags (form-specific + default)
        $tags = [];
        if (!empty($form_mapping['tags'])) {
            $tags[] = $form_mapping['tags'];
        }
        $default_tags = get_option('leadmachine_gf_default_tags', '');
        if (!empty($default_tags)) {
            $tags[] = $default_tags;
        }
        $tags_string = implode(',', $tags);

        // Prepare data
        $data = array(
            'company_id' => $company_id,
            'api_key' => $api_key,
            'company' => $company_name,
            'first_name' => $first_name,
            'last_name' => $last_name,
            'contact_name' => $contact_name,
            'contact_email' => $email,
            'contact_phone' => $phone,
            'message' => $message,
            'source' => 'Gravity Forms: ' . $form['title'],
            'source_url' => $entry['source_url'] ?? '',
            'tags' => $tags_string,
        );

        // Send to LeadMachine API
        $response = wp_remote_post(
            rtrim($api_url, '/') . '/api/leads/wordpress-submit.php',
            array(
                'body' => $data,
                'timeout' => 30,
                'headers' => array(
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ),
            )
        );

        if (is_wp_error($response)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine GF API Error: ' . $response->get_error_message());
            }
            return;
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
            error_log('LeadMachine GF Response [' . $response_code . ']: ' . $response_body);
        }

        if ($response_code !== 200) {
            $result = json_decode($response_body, true);
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging
                error_log('LeadMachine GF submission failed: ' . ($result['error'] ?? 'Unknown error'));
            }
        }
    }

    /**
     * Get value from Gravity Forms entry
     * Handles both simple fields and compound fields (like name, address)
     */
    private function get_gf_entry_value($entry, $field_id) {
        if (empty($field_id)) {
            return '';
        }

        // Handle compound field IDs like "1.3" (first name) or "1.6" (last name)
        if (isset($entry[$field_id])) {
            return $entry[$field_id];
        }

        return '';
    }

    /**
     * Detect spam submissions based on name patterns, email, and content
     *
     * @param string $first_name First name
     * @param string $last_name Last name
     * @param string $email Email address
     * @param string $message Message content
     * @return string|false Spam reason if detected, false otherwise
     */
    private function detect_spam($first_name, $last_name, $email, $message) {
        $full_name = $first_name . ' ' . $last_name;

        // Known spam bot name suffixes (case-insensitive)
        $spam_suffixes = array(
            'taics',    // Common bot pattern: Roberttaics, NathantaicsGM
            'tics',     // Variation
            'bup',      // Another common pattern
            'tyday',    // Spam pattern
            'Dup',      // Duplicate bot
            'Wep',      // Web bot pattern
            'Sog',      // Bot pattern
            'Riz',      // Bot pattern
            'Hix',      // Bot pattern
        );

        foreach ($spam_suffixes as $suffix) {
            if (stripos($first_name, $suffix) !== false || stripos($last_name, $suffix) !== false) {
                return 'name_suffix_' . $suffix;
            }
        }

        // Check for gibberish names (no vowels in 5+ character name)
        if (strlen($first_name) >= 5 && !preg_match('/[aeiouAEIOU]/', $first_name)) {
            return 'no_vowels_firstname';
        }
        if (strlen($last_name) >= 5 && !preg_match('/[aeiouAEIOU]/', $last_name)) {
            return 'no_vowels_lastname';
        }

        // Check for repeating character patterns (e.g., "aaaaaa", "ababab")
        if (preg_match('/(.)\1{4,}/', $first_name) || preg_match('/(.)\1{4,}/', $last_name)) {
            return 'repeating_chars';
        }
        if (preg_match('/(.{2,3})\1{2,}/', $first_name) || preg_match('/(.{2,3})\1{2,}/', $last_name)) {
            return 'repeating_pattern';
        }

        // Check for suspicious TLDs in email
        $spam_tlds = array('.ru', '.cn', '.xyz', '.top', '.buzz', '.work', '.click', '.link', '.surf');
        foreach ($spam_tlds as $tld) {
            if (substr(strtolower($email), -strlen($tld)) === $tld) {
                return 'suspicious_tld_' . $tld;
            }
        }

        // Check for excessive URLs in message (more than 3)
        if (!empty($message)) {
            $url_count = preg_match_all('/https?:\/\/[^\s]+/', $message);
            if ($url_count > 3) {
                return 'too_many_urls';
            }

            // Check for common spam keywords in message
            $spam_keywords = array(
                'buy now', 'click here', 'limited time', 'act now', 'free money',
                'casino', 'viagra', 'crypto trading', 'bitcoin profit', 'make money fast'
            );
            $message_lower = strtolower($message);
            foreach ($spam_keywords as $keyword) {
                if (strpos($message_lower, $keyword) !== false) {
                    return 'spam_keyword_' . str_replace(' ', '_', $keyword);
                }
            }
        }

        // Check for disposable email domains
        $disposable_domains = array(
            'tempmail.com', 'throwaway.email', 'guerrillamail.com', 'mailinator.com',
            'temp-mail.org', '10minutemail.com', 'fakemailgenerator.com', 'yopmail.com'
        );
        $email_domain = substr(strrchr($email, '@'), 1);
        foreach ($disposable_domains as $domain) {
            if (strtolower($email_domain) === $domain) {
                return 'disposable_email_' . $domain;
            }
        }

        return false; // Not spam
    }

    /**
     * Get list of Gravity Forms for admin UI
     */
    private function get_gravity_forms_list() {
        if (!class_exists('GFAPI')) {
            return array();
        }

        $forms = GFAPI::get_forms();
        $form_list = array();

        foreach ($forms as $form) {
            $form_list[] = array(
                'id' => $form['id'],
                'title' => $form['title']
            );
        }

        return $form_list;
    }

    /**
     * AJAX handler to get Gravity Forms fields for a specific form
     */
    public function ajax_get_gf_fields() {
        check_ajax_referer('leadmachine_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }

        $form_id = intval($_POST['form_id'] ?? 0);

        if (!$form_id || !class_exists('GFAPI')) {
            wp_send_json_error(array('message' => 'Invalid form ID or Gravity Forms not installed'));
        }

        $form = GFAPI::get_form($form_id);

        if (!$form) {
            wp_send_json_error(array('message' => 'Form not found'));
        }

        $fields = array();

        foreach ($form['fields'] as $field) {
            // Handle compound fields (name, address, etc.)
            if (!empty($field->inputs) && is_array($field->inputs)) {
                foreach ($field->inputs as $input) {
                    if (!empty($input['isHidden'])) {
                        continue;
                    }
                    $fields[] = array(
                        'id' => $input['id'],
                        'label' => $field->label . ' - ' . $input['label'],
                        'type' => $field->type
                    );
                }
            } else {
                $fields[] = array(
                    'id' => $field->id,
                    'label' => $field->label,
                    'type' => $field->type
                );
            }
        }

        wp_send_json_success(array('fields' => $fields));
    }

    /**
     * Get client IP address for spam logging
     */
    private function get_client_ip() {
        $ip_keys = array(
            'HTTP_CF_CONNECTING_IP', // Cloudflare
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_REAL_IP',
            'REMOTE_ADDR'
        );

        foreach ($ip_keys as $key) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- IP validated with FILTER_VALIDATE_IP below
            if (isset($_SERVER[$key]) && !empty($_SERVER[$key])) {
                $ip = sanitize_text_field(wp_unslash($_SERVER[$key]));
                // Handle comma-separated list (X-Forwarded-For can have multiple IPs)
                if (strpos($ip, ',') !== false) {
                    $ip = trim(explode(',', $ip)[0]);
                }
                if (filter_var($ip, FILTER_VALIDATE_IP)) {
                    return $ip;
                }
            }
        }

        return 'unknown';
    }
}

// Initialize the plugin
function leadmachine_connector_init() {
    return LeadMachine_Connector::get_instance();
}
add_action('plugins_loaded', 'leadmachine_connector_init');
