<?php
// Centralized third‑party integrations loader.

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

if (!interface_exists('Sentinel_Integration_Interface')) {
    interface Sentinel_Integration_Interface
    {
        public function get_key();              // e.g., 'woocommerce'
        public function get_name();             // e.g., 'WooCommerce'
        public function get_prefix();           // e.g., 'woo_'
        public function is_active();            // plugin detection
        public function get_plugin_files();     // plugin main files for mapping/cleanup
        public function get_events();           // [event_key => config]
        public function register_hooks($shouldHook); // attach runtime hooks
    }
}

if (!class_exists('Sentinel_Integration_Registry')) {
    class Sentinel_Integration_Registry
    {
        /** @return Sentinel_Integration_Interface[] */
        public static function get_integrations()
        {
            static $integrations = null;
            if ($integrations !== null) {
                return $integrations;
            }

            $integrations = array(
                new Sentinel_WooCommerce_Integration(),
                new Sentinel_CF7_Integration(),
                new Sentinel_WPForms_Integration(),
                new Sentinel_GravityForms_Integration(),
                new Sentinel_YoastSEO_Integration(),
            );

            return $integrations;
        }

        public static function init()
        {
            // Provide standard shouldHook closure used by all integrations
            $custom_events = get_option('sentinel_custom_events', array());
            $disabled_events = get_option('sentinel_disabled_events', array());
            $shouldHook = function ($event_key) use ($custom_events, $disabled_events) {
                return isset($custom_events[$event_key]) && !in_array($event_key, $disabled_events);
            };

            foreach (self::get_integrations() as $integration) {
                if ($integration->is_active()) {
                    $integration->register_hooks($shouldHook);
                }
            }
        }

        public static function get_templates()
        {
            $templates = array();
            foreach (self::get_integrations() as $integration) {
                $templates[$integration->get_key()] = array(
                    'name' => $integration->get_name(),
                    'plugin_active' => $integration->is_active(),
                    'events' => $integration->get_events(),
                );
            }
            return $templates;
        }

        /** Map plugin file => prefix for cleanup */
        public static function get_cleanup_map()
        {
            $map = array();
            foreach (self::get_integrations() as $integration) {
                foreach ($integration->get_plugin_files() as $file) {
                    $map[$file] = $integration->get_prefix();
                }
            }
            return $map;
        }
    }
}

// --------------------------------
// WooCommerce Integration
// --------------------------------
if (!class_exists('Sentinel_WooCommerce_Integration')) {
    class Sentinel_WooCommerce_Integration implements Sentinel_Integration_Interface
    {
        public function get_key()
        {
            return 'woocommerce';
        }
        public function get_name()
        {
            return 'WooCommerce';
        }
        public function get_prefix()
        {
            return 'woo_';
        }
        public function is_active()
        {
            return (function_exists('is_plugin_active') && is_plugin_active('woocommerce/woocommerce.php')) && class_exists('WooCommerce');
        }
        public function get_plugin_files()
        {
            return array('woocommerce/woocommerce.php');
        }
        public function get_events()
        {
            return array(
                'woo_new_order' => array('label' => 'New Order Placed', 'category' => 'ecommerce', 'priority' => 'medium', 'description' => 'Triggered when a new WooCommerce order is placed'),
                'woo_payment_complete' => array('label' => 'Payment Completed', 'category' => 'ecommerce', 'priority' => 'high', 'description' => 'Triggered when a WooCommerce payment is completed'),
                'woo_order_status_changed' => array('label' => 'Order Status Changed', 'category' => 'ecommerce', 'priority' => 'low', 'description' => 'Triggered when a WooCommerce order status changes'),
                'woo_payment_failed' => array('label' => 'Payment Failed', 'category' => 'ecommerce', 'priority' => 'high', 'description' => 'Triggered when a WooCommerce payment fails'),
            );
        }
        public function register_hooks($shouldHook)
        {
            if (!$this->is_active()) {
                return;
            }

            // New Order
            add_action('woocommerce_new_order', function ($order_id, $order = null) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['woo_new_order']) || in_array('woo_new_order', $disabled_events)) {
                    return;
                }
                if (!$order && function_exists('wc_get_order')) {
                    $order = wc_get_order($order_id);
                }
                if (!$order) return;
                $data = array(
                    'order_id' => $order_id,
                    'order_number' => method_exists($order, 'get_order_number') ? $order->get_order_number() : '',
                    'status' => method_exists($order, 'get_status') ? $order->get_status() : '',
                    'total' => method_exists($order, 'get_total') ? $order->get_total() : 0,
                    'currency' => method_exists($order, 'get_currency') ? $order->get_currency() : '',
                    'payment_method' => method_exists($order, 'get_payment_method') ? $order->get_payment_method() : '',
                    'payment_method_title' => method_exists($order, 'get_payment_method_title') ? $order->get_payment_method_title() : '',
                    'customer_id' => method_exists($order, 'get_customer_id') ? $order->get_customer_id() : 0,
                    'customer_email' => method_exists($order, 'get_billing_email') ? $order->get_billing_email() : '',
                    'customer_name' => (method_exists($order, 'get_billing_first_name') ? $order->get_billing_first_name() : '') . ' ' . (method_exists($order, 'get_billing_last_name') ? $order->get_billing_last_name() : ''),
                    'items_count' => method_exists($order, 'get_item_count') ? $order->get_item_count() : 0,
                    'created_date' => method_exists($order, 'get_date_created') && $order->get_date_created() ? $order->get_date_created()->format('Y-m-d H:i:s') : null
                );
                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('woo_new_order', $data, $data['customer_id']);
                }
            }, 10, 2);

            // Payment Complete
            add_action('woocommerce_payment_complete', function ($order_id) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['woo_payment_complete']) || in_array('woo_payment_complete', $disabled_events)) {
                    return;
                }
                $order = function_exists('wc_get_order') ? wc_get_order($order_id) : null;
                if (!$order) return;
                $data = array(
                    'order_id' => $order_id,
                    'order_number' => method_exists($order, 'get_order_number') ? $order->get_order_number() : '',
                    'total_paid' => method_exists($order, 'get_total') ? $order->get_total() : 0,
                    'currency' => method_exists($order, 'get_currency') ? $order->get_currency() : '',
                    'payment_method' => method_exists($order, 'get_payment_method') ? $order->get_payment_method() : '',
                    'payment_method_title' => method_exists($order, 'get_payment_method_title') ? $order->get_payment_method_title() : '',
                    'customer_id' => method_exists($order, 'get_customer_id') ? $order->get_customer_id() : 0,
                    'customer_email' => method_exists($order, 'get_billing_email') ? $order->get_billing_email() : '',
                    'transaction_id' => method_exists($order, 'get_transaction_id') ? $order->get_transaction_id() : '',
                    'payment_date' => method_exists($order, 'get_date_paid') && $order->get_date_paid() ? $order->get_date_paid()->format('Y-m-d H:i:s') : current_time('mysql')
                );
                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('woo_payment_complete', $data, $data['customer_id']);
                }
            }, 10, 1);

            // Order Status Changed
            add_action('woocommerce_order_status_changed', function ($order_id, $old_status, $new_status) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['woo_order_status_changed']) || in_array('woo_order_status_changed', $disabled_events)) {
                    return;
                }
                $order = function_exists('wc_get_order') ? wc_get_order($order_id) : null;
                if (!$order) return;
                $data = array(
                    'order_id' => $order_id,
                    'order_number' => method_exists($order, 'get_order_number') ? $order->get_order_number() : '',
                    'old_status' => $old_status,
                    'new_status' => $new_status,
                    'total' => method_exists($order, 'get_total') ? $order->get_total() : 0,
                    'currency' => method_exists($order, 'get_currency') ? $order->get_currency() : '',
                    'customer_id' => method_exists($order, 'get_customer_id') ? $order->get_customer_id() : 0,
                    'customer_email' => method_exists($order, 'get_billing_email') ? $order->get_billing_email() : '',
                    'changed_by' => get_current_user_id(),
                    'changed_date' => current_time('mysql')
                );
                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('woo_order_status_changed', $data, $data['customer_id']);
                }
            }, 10, 3);

            // Payment Failed
            add_action('woocommerce_payment_failed', function ($order_id, $error_message = '') {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['woo_payment_failed']) || in_array('woo_payment_failed', $disabled_events)) {
                    return;
                }
                $order = function_exists('wc_get_order') ? wc_get_order($order_id) : null;
                if (!$order) return;
                $data = array(
                    'order_id' => $order_id,
                    'order_number' => method_exists($order, 'get_order_number') ? $order->get_order_number() : '',
                    'total' => method_exists($order, 'get_total') ? $order->get_total() : 0,
                    'currency' => method_exists($order, 'get_currency') ? $order->get_currency() : '',
                    'payment_method' => method_exists($order, 'get_payment_method') ? $order->get_payment_method() : '',
                    'payment_method_title' => method_exists($order, 'get_payment_method_title') ? $order->get_payment_method_title() : '',
                    'customer_id' => method_exists($order, 'get_customer_id') ? $order->get_customer_id() : 0,
                    'customer_email' => method_exists($order, 'get_billing_email') ? $order->get_billing_email() : '',
                    'error_message' => is_string($error_message) ? $error_message : 'Payment failed',
                    'failure_date' => current_time('mysql')
                );
                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('woo_payment_failed', $data, $data['customer_id']);
                }
            }, 10, 2);
        }
    }
}

// --------------------------------
// Contact Form 7 Integration
// --------------------------------
if (!class_exists('Sentinel_CF7_Integration')) {
    class Sentinel_CF7_Integration implements Sentinel_Integration_Interface
    {
        public function get_key()
        {
            return 'contact-form-7';
        }
        public function get_name()
        {
            return 'Contact Form 7';
        }
        public function get_prefix()
        {
            return 'cf7_';
        }
        public function is_active()
        {
            return (function_exists('is_plugin_active') && is_plugin_active('contact-form-7/wp-contact-form-7.php')) && class_exists('WPCF7');
        }
        public function get_plugin_files()
        {
            return array('contact-form-7/wp-contact-form-7.php');
        }
        public function get_events()
        {
            return array(
                'cf7_form_submitted' => array('label' => 'Form Submitted', 'category' => 'content', 'priority' => 'low', 'description' => 'Triggered when a Contact Form 7 form is successfully submitted'),
                'cf7_form_failed' => array('label' => 'Form Submission Failed', 'category' => 'content', 'priority' => 'medium', 'description' => 'Triggered when a Contact Form 7 form submission fails'),
            );
        }
        public function register_hooks($shouldHook)
        {
            if (!$this->is_active()) {
                return;
            }

            // Form submitted
            add_action('wpcf7_mail_sent', function ($contact_form) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['cf7_form_submitted']) || in_array('cf7_form_submitted', $disabled_events)) {
                    return;
                }
                if (!$contact_form || !is_object($contact_form)) return;
                $submission = class_exists('WPCF7_Submission') ? WPCF7_Submission::get_instance() : null;
                $posted_data = $submission ? $submission->get_posted_data() : array();
                $field_count = 0;
                if (is_array($posted_data)) {
                    foreach ($posted_data as $key => $value) {
                        if (strpos($key, '_wpcf7') === 0) {
                            continue;
                        }
                        $field_count++;
                    }
                }
                $data = array(
                    'form_id' => method_exists($contact_form, 'id') ? $contact_form->id() : 0,
                    'form_title' => method_exists($contact_form, 'title') ? $contact_form->title() : 'Contact Form',
                    'form_slug' => method_exists($contact_form, 'name') ? $contact_form->name() : '',
                    'field_count' => $field_count,
                    'has_file_upload' => $submission ? !empty($submission->uploaded_files()) : false,
                    'submission_id' => $submission ? ($submission->get_meta('remote_ip') . '-' . time()) : null,
                    'user_ip' => $submission ? $submission->get_meta('remote_ip') : ($_SERVER['REMOTE_ADDR'] ?? 'Unknown'),
                    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
                    'submitted_date' => current_time('mysql')
                );
                if (isset($_SERVER['HTTP_REFERER'])) {
                    $data['referrer'] = $_SERVER['HTTP_REFERER'];
                }
                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('cf7_form_submitted', $data, get_current_user_id());
                }
            }, 10, 1);

            // Form failed
            add_action('wpcf7_mail_failed', function ($contact_form) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['cf7_form_failed']) || in_array('cf7_form_failed', $disabled_events)) {
                    return;
                }
                if (!$contact_form || !is_object($contact_form)) return;
                $submission = class_exists('WPCF7_Submission') ? WPCF7_Submission::get_instance() : null;
                $posted_data = $submission ? $submission->get_posted_data() : array();
                $field_count = 0;
                if (is_array($posted_data)) {
                    foreach ($posted_data as $key => $value) {
                        if (strpos($key, '_wpcf7') === 0) {
                            continue;
                        }
                        $field_count++;
                    }
                }
                $data = array(
                    'form_id' => method_exists($contact_form, 'id') ? $contact_form->id() : 0,
                    'form_title' => method_exists($contact_form, 'title') ? $contact_form->title() : 'Contact Form',
                    'form_slug' => method_exists($contact_form, 'name') ? $contact_form->name() : '',
                    'field_count' => $field_count,
                    'has_file_upload' => $submission ? !empty($submission->uploaded_files()) : false,
                    'failure_reason' => 'mail_send_failed',
                    'submission_id' => $submission ? ($submission->get_meta('remote_ip') . '-' . time()) : null,
                    'user_ip' => $submission ? $submission->get_meta('remote_ip') : ($_SERVER['REMOTE_ADDR'] ?? 'Unknown'),
                    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
                    'failed_date' => current_time('mysql')
                );
                if (isset($_SERVER['HTTP_REFERER'])) {
                    $data['referrer'] = $_SERVER['HTTP_REFERER'];
                }
                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('cf7_form_failed', $data, get_current_user_id());
                }
            }, 10, 1);
        }
    }
}

// --------------------------------
// WPForms Integration
// --------------------------------
if (!class_exists('Sentinel_WPForms_Integration')) {
    class Sentinel_WPForms_Integration implements Sentinel_Integration_Interface
    {
        public function get_key()
        {
            return 'wpforms';
        }
        public function get_name()
        {
            return 'WPForms';
        }
        public function get_prefix()
        {
            return 'wpf_';
        }
        public function is_active()
        {
            return (function_exists('is_plugin_active') && (is_plugin_active('wpforms-lite/wpforms.php') || is_plugin_active('wpforms/wpforms.php'))) || class_exists('WPForms');
        }
        public function get_plugin_files()
        {
            return array('wpforms-lite/wpforms.php', 'wpforms/wpforms.php');
        }
        public function get_events()
        {
            return array(
                'wpf_form_submitted' => array('label' => 'Form Submitted', 'category' => 'content', 'priority' => 'low', 'description' => 'Triggered when a WPForms form entry is successfully saved'),
                'wpf_payment_completed' => array('label' => 'Payment Completed', 'category' => 'ecommerce', 'priority' => 'high', 'description' => 'Triggered when a WPForms payment is completed'),
            );
        }
        public function register_hooks($shouldHook)
        {
            if (!$this->is_active()) {
                return;
            }

            // Entry saved
            add_action('wpforms_process_entry_save', function ($fields, $entry, $form_id, $form_data) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['wpf_form_submitted']) || in_array('wpf_form_submitted', $disabled_events)) {
                    return;
                }
                if (!$form_data || empty($form_id)) return;
                $field_count = 0;
                $has_file_upload = false;
                if (is_array($fields)) {
                    foreach ($fields as $field) {
                        if (!empty($field['type']) && !in_array($field['type'], array('pagebreak', 'divider', 'html'))) {
                            $field_count++;
                            if ($field['type'] === 'file-upload') {
                                $has_file_upload = true;
                            }
                        }
                    }
                }
                $data = array(
                    'form_id' => $form_id,
                    'form_title' => isset($form_data['settings']['form_title']) ? $form_data['settings']['form_title'] : 'WPForm',
                    'field_count' => $field_count,
                    'has_file_upload' => $has_file_upload,
                    'entry_id' => (is_array($entry) && isset($entry['entry_id'])) ? $entry['entry_id'] : null,
                    'user_ip' => $_SERVER['REMOTE_ADDR'] ?? 'Unknown',
                    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
                    'submitted_date' => current_time('mysql')
                );
                if (isset($_SERVER['HTTP_REFERER'])) {
                    $data['referrer'] = $_SERVER['HTTP_REFERER'];
                }
                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('wpf_form_submitted', $data, get_current_user_id());
                }
            }, 10, 4);

            // Payment saved
            add_action('wpforms_process_payment_saved', function ($payment_id, $fields, $form_data) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['wpf_payment_completed']) || in_array('wpf_payment_completed', $disabled_events)) {
                    return;
                }
                if (!$payment_id || !$form_data) return;
                $data = array(
                    'form_id' => isset($form_data['id']) ? $form_data['id'] : 0,
                    'form_title' => isset($form_data['settings']['form_title']) ? $form_data['settings']['form_title'] : 'WPForm',
                    'payment_id' => $payment_id,
                    'has_payment_fields' => !empty($fields) && is_array($fields),
                    'user_ip' => $_SERVER['REMOTE_ADDR'] ?? 'Unknown',
                    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
                    'payment_date' => current_time('mysql')
                );
                if (isset($_SERVER['HTTP_REFERER'])) {
                    $data['referrer'] = $_SERVER['HTTP_REFERER'];
                }
                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('wpf_payment_completed', $data, get_current_user_id());
                }
            }, 10, 3);
        }
    }
}

// --------------------------------
// Gravity Forms Integration (templates only)
// --------------------------------
if (!class_exists('Sentinel_GravityForms_Integration')) {
    class Sentinel_GravityForms_Integration implements Sentinel_Integration_Interface
    {
        public function get_key()
        {
            return 'gravity-forms';
        }
        public function get_name()
        {
            return 'Gravity Forms';
        }
        public function get_prefix()
        {
            return 'gf_';
        }
        public function is_active()
        {
            return class_exists('GFForms');
        }
        public function get_plugin_files()
        {
            return array('gravityforms/gravityforms.php');
        }
        public function get_events()
        {
            return array(
                'gf_form_submitted' => array('label' => 'Form Submitted', 'category' => 'content', 'priority' => 'low', 'description' => 'Triggered when a Gravity Form is successfully submitted'),
                'gf_payment_complete' => array('label' => 'Payment Completed', 'category' => 'ecommerce', 'priority' => 'high', 'description' => 'Triggered when a Gravity Forms payment is completed'),
            );
        }
        public function register_hooks($shouldHook)
        {
            // Hooks can be added in future; templates available now
        }
    }
}

// --------------------------------
// Yoast SEO Integration
// --------------------------------
if (!class_exists('Sentinel_YoastSEO_Integration')) {
    class Sentinel_YoastSEO_Integration implements Sentinel_Integration_Interface
    {
        public function get_key()
        {
            return 'yoast-seo';
        }
        public function get_name()
        {
            return 'Yoast SEO';
        }
        public function get_prefix()
        {
            return 'yoast_';
        }
        public function is_active()
        {
            return (function_exists('is_plugin_active') && is_plugin_active('wordpress-seo/wp-seo.php')) && class_exists('WPSEO_Options');
        }
        public function get_plugin_files()
        {
            return array('wordpress-seo/wp-seo.php');
        }
        public function get_events()
        {
            return array(
                'yoast_meta_updated' => array('label' => 'SEO Meta Updated', 'category' => 'seo', 'priority' => 'medium', 'description' => 'Meta title, description, or focus keyword was updated'),
                'yoast_score_changed' => array('label' => 'SEO Score Changed', 'category' => 'seo', 'priority' => 'low', 'description' => 'SEO readability or keyword score changed'),
                'yoast_schema_updated' => array('label' => 'Schema Markup Updated', 'category' => 'seo', 'priority' => 'medium', 'description' => 'Structured data or schema markup was modified'),
                'yoast_bulk_action' => array('label' => 'Bulk SEO Action', 'category' => 'seo', 'priority' => 'high', 'description' => 'Bulk SEO optimization was performed'),
            );
        }
        public function register_hooks($shouldHook)
        {
            if (!$this->is_active()) {
                return;
            }

            // Use updated_post_meta hook specifically for Yoast meta changes
            add_action('updated_post_meta', function ($meta_id, $post_id, $meta_key, $meta_value) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['yoast_meta_updated']) || in_array('yoast_meta_updated', $disabled_events)) {
                    return;
                }

                // Skip WordPress internal meta fields that cause spam
                $skip_meta_keys = array('_edit_lock', '_edit_last', '_wp_old_slug', '_wp_old_date');
                if (in_array($meta_key, $skip_meta_keys)) {
                    return;
                }

                // Skip Yoast score-related meta keys - these are handled by the score change hook
                $score_meta_keys = array('_yoast_wpseo_linkdex', '_yoast_wpseo_content_score');
                if (in_array($meta_key, $score_meta_keys)) {
                    return;
                }

                // Skip Yoast schema-related meta keys - these are handled by the schema change hook
                if (strpos($meta_key, '_yoast_wpseo_schema_') === 0) {
                    return;
                }

                // Check if this is a Yoast SEO meta field
                if (strpos($meta_key, '_yoast_wpseo_') === 0) {
                    $post = get_post($post_id);
                    if (!$post) return;

                    $data = array(
                        'post_id' => $post_id,
                        'post_title' => $post->post_title,
                        'post_type' => $post->post_type,
                        'meta_key' => $meta_key,
                        'meta_value' => is_string($meta_value) ? $meta_value : json_encode($meta_value),
                        'updated_by' => get_current_user_id(),
                        'updated_date' => current_time('mysql')
                    );

                    if (function_exists('sentinel_log_event')) {
                        sentinel_log_event('yoast_meta_updated', $data, get_current_user_id());
                    }
                }
            }, 10, 4);

            // Hook into updated_post_meta specifically for score changes
            add_action('updated_post_meta', function ($meta_id, $post_id, $meta_key, $meta_value) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['yoast_score_changed']) || in_array('yoast_score_changed', $disabled_events)) {
                    return;
                }

                // Only handle Yoast score meta keys
                $score_meta_keys = array('_yoast_wpseo_linkdex', '_yoast_wpseo_content_score');
                if (!in_array($meta_key, $score_meta_keys)) {
                    return;
                }

                $post = get_post($post_id);
                if (!$post) return;

                // Determine score type
                $score_type = '';
                if ($meta_key === '_yoast_wpseo_linkdex') {
                    $score_type = 'SEO score';
                } elseif ($meta_key === '_yoast_wpseo_content_score') {
                    $score_type = 'readability score';
                }

                $data = array(
                    'post_id' => $post_id,
                    'post_title' => $post->post_title,
                    'post_type' => $post->post_type,
                    'score_type' => $score_type,
                    'meta_key' => $meta_key,
                    'new_score' => $meta_value,
                    'updated_by' => get_current_user_id(),
                    'updated_date' => current_time('mysql')
                );

                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('yoast_score_changed', $data, get_current_user_id());
                }
            }, 10, 4);

            // Hook into updated_post_meta specifically for schema changes
            add_action('updated_post_meta', function ($meta_id, $post_id, $meta_key, $meta_value) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['yoast_schema_updated']) || in_array('yoast_schema_updated', $disabled_events)) {
                    return;
                }

                // Only handle Yoast schema meta keys
                if (strpos($meta_key, '_yoast_wpseo_schema_') !== 0) {
                    return;
                }

                $post = get_post($post_id);
                if (!$post) return;

                // Map schema meta keys to friendly names
                $schema_friendly_names = array(
                    '_yoast_wpseo_schema_page_type' => 'Page Type',
                    '_yoast_wpseo_schema_article_type' => 'Article Type',
                    '_yoast_wpseo_schema_organization_type' => 'Organization Type',
                    '_yoast_wpseo_schema_person_type' => 'Person Type'
                );

                $schema_field = isset($schema_friendly_names[$meta_key]) ? $schema_friendly_names[$meta_key] : 'Schema Field';

                $data = array(
                    'post_id' => $post_id,
                    'post_title' => $post->post_title,
                    'post_type' => $post->post_type,
                    'schema_field' => $schema_field,
                    'meta_key' => $meta_key,
                    'new_value' => $meta_value,
                    'updated_by' => get_current_user_id(),
                    'updated_date' => current_time('mysql')
                );

                if (function_exists('sentinel_log_event')) {
                    sentinel_log_event('yoast_schema_updated', $data, get_current_user_id());
                }
            }, 10, 4);

            // Hook for bulk actions - detect multiple Yoast meta updates in quick succession
            add_action('updated_post_meta', function ($meta_id, $post_id, $meta_key, $meta_value) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['yoast_bulk_action']) || in_array('yoast_bulk_action', $disabled_events)) {
                    return;
                }

                // Only handle Yoast meta keys
                if (strpos($meta_key, '_yoast_wpseo_') !== 0) {
                    return;
                }

                // Skip score and schema keys as they have their own handlers
                if (
                    strpos($meta_key, '_yoast_wpseo_linkdex') === 0 ||
                    strpos($meta_key, '_yoast_wpseo_content_score') === 0 ||
                    strpos($meta_key, '_yoast_wpseo_schema_') === 0
                ) {
                    return;
                }

                // Check if this is part of a bulk operation
                // We'll use a transient to track recent Yoast meta updates
                $bulk_tracker = get_transient('sentinel_yoast_bulk_tracker');
                if (!$bulk_tracker) {
                    $bulk_tracker = array();
                }

                $current_time = time();
                $bulk_tracker[] = array(
                    'post_id' => $post_id,
                    'meta_key' => $meta_key,
                    'timestamp' => $current_time
                );

                // Clean old entries (older than 10 seconds)
                $bulk_tracker = array_filter($bulk_tracker, function ($entry) use ($current_time) {
                    return ($current_time - $entry['timestamp']) < 10;
                });

                // If we have 3 or more Yoast meta updates in the last 10 seconds, consider it a bulk action
                if (count($bulk_tracker) >= 3) {
                    $post = get_post($post_id);
                    if (!$post) return;

                    $affected_posts = array_unique(array_column($bulk_tracker, 'post_id'));
                    $meta_keys_updated = array_unique(array_column($bulk_tracker, 'meta_key'));

                    $data = array(
                        'post_id' => $post_id,
                        'post_title' => $post->post_title,
                        'post_type' => $post->post_type,
                        'action' => 'bulk SEO optimization',
                        'affected_posts_count' => count($affected_posts),
                        'meta_keys_updated' => $meta_keys_updated,
                        'updated_by' => get_current_user_id(),
                        'updated_date' => current_time('mysql')
                    );

                    if (function_exists('sentinel_log_event')) {
                        sentinel_log_event('yoast_bulk_action', $data, get_current_user_id());
                    }

                    // Clear the tracker to avoid duplicate logs
                    delete_transient('sentinel_yoast_bulk_tracker');
                } else {
                    // Update the transient
                    set_transient('sentinel_yoast_bulk_tracker', $bulk_tracker, 10);
                }
            }, 10, 4);

            // Hook for WordPress bulk edit actions
            add_action('bulk_edit_posts', function ($post_ids, $post_data) {
                $custom_events = get_option('sentinel_custom_events', array());
                $disabled_events = get_option('sentinel_disabled_events', array());
                if (!isset($custom_events['yoast_bulk_action']) || in_array('yoast_bulk_action', $disabled_events)) {
                    return;
                }

                // Check if any Yoast SEO fields were updated
                $yoast_fields_updated = false;
                $yoast_fields = array();

                foreach ($post_data as $field => $value) {
                    if (strpos($field, '_yoast_wpseo_') === 0) {
                        $yoast_fields_updated = true;
                        $yoast_fields[] = $field;
                    }
                }

                if ($yoast_fields_updated) {
                    $data = array(
                        'action' => 'bulk edit SEO fields',
                        'affected_posts_count' => count($post_ids),
                        'yoast_fields_updated' => $yoast_fields,
                        'updated_by' => get_current_user_id(),
                        'updated_date' => current_time('mysql')
                    );

                    if (function_exists('sentinel_log_event')) {
                        sentinel_log_event('yoast_bulk_action', $data, get_current_user_id());
                    }
                }
            }, 10, 2);
        }
    }
}

// End of integrations
