<?php
 
 /**
 * =============================================================================
 * @package			    Blue Raven (Free Version)
 * @Plugin URI			https://enterrahost.com/plugins/blue-raven
 * 
 * @Author			    EnterraHost
 * @Author URI			https://enterrahost.com
 * @License			    GPL-2.0-or-later
 *  
 * @Copyright			(c) 2025 EnterraHost
 * @File Description	Various Hooks for tools and functionality
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - VERIFICATION META TAG
 * ||   - ANALYTICS META 
 * ||   - SITE SCHEMA
 * ||   - SITE MAP INDEXNOW
 * ||   - PRODUCT UPDATES AND DELETING
 * ||   - STOCK PRODUCT UPDATES
 * ||   - BLUE RAVEN ADD PRODUCT SCHEMA
 * ||   - WC TRACK PRODUCT SLUG CHANGE
 * ||   - WC HANDLE PRODUCT REDIRECTS
 * ||   - WC CLEANUP PRODUCT REDIRECTS
 * ||   - BLUE RAVEN FORM HOOK 
 * ||   - HOOK ACTIONS 
 * ||   - SHORT CODES
 * ||   - CSS FRONT END
 * || 
 * =============================================================================
 */

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

/*
============================================================
    VERIFICATION META TAG
============================================================
*/

function BlueRaven_add_site_verification_meta_tag() {
    global $wpdb;

    ## =========== Check if site verification is enabled =========== ##
    
    $result = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}BlueRavenValues WHERE setting = %s", 'overall-site-verification'));
    
    if ($result && $result->enabled) {

        $verification_settings = ['bing-site-verification','google-site-verification','facebook-site-verification','ahref-site-verification'];
        $placeholders = implode(',', array_fill(0, count($verification_settings), '%s'));
        $results_codes = $wpdb->get_results($wpdb->prepare("SELECT setting, value, enabled FROM {$wpdb->prefix}BlueRavenValues WHERE setting IN ($placeholders)",...$verification_settings));

    ## =========== Loop through the results and display the meta tags =========== ##
        
        foreach ($results_codes as $result_code) {
            if ($result_code->enabled) {
                switch ($result_code->setting) {
                    case 'google-site-verification':
                        echo '<meta name="google-site-verification" content="' . esc_attr($result_code->value) . '" />';
                        break;
                    case 'bing-site-verification':
                        echo '<meta name="msvalidate.01" content="' . esc_attr($result_code->value) . '" />';
                        break;
                    case 'facebook-site-verification':
                        echo '<meta name="facebook-domain-verification" content="' . esc_attr($result_code->value) . '" />';
                        break;
                    case 'ahref-site-verification':
                        echo '<meta name="ahrefs-site-verification" content="' . esc_attr($result_code->value) . '" />';
                        break;        
                }
            }
        }
    }
}

/*
============================================================
    ANALYTICS META 
============================================================
*/

function BlueRaven_add_site_analytics_meta_tag() {
    
    global $wpdb;

    ## =========== Check if site analytics is enabled =========== ##
    
    $result = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}BlueRavenValues WHERE setting = %s", 'overall-site-analytics'));
    
    if ($result && $result->enabled) {
        
        $analytic_settings = ['meta-site-analytics','google-site-analytics','ahref-site-analytics','microsoft-site-analytics'];
        $placeholders = implode(',', array_fill(0, count($analytic_settings), '%s'));
        $results_codes = $wpdb->get_results($wpdb->prepare("SELECT setting, value, enabled  FROM {$wpdb->prefix}BlueRavenValues  WHERE setting IN ($placeholders)", ...$analytic_settings));

    ## =========== Loop through the results and display the meta tags =========== ##
        
        foreach ($results_codes as $result_code) {
			if (!$result_code->enabled) {
				continue;
			}

			switch ($result_code->setting) {
				case 'google-site-analytics':
					
                    ///-- Enqueue external script

					wp_enqueue_script(
						'google-BlueRaven_gtag',
						'https://www.googletagmanager.com/gtag/js?id=' . esc_attr($result_code->value),
						[],
						null,
						false
					);

					///-- Add inline script

					$inline = "
                        window.dataLayer = window.dataLayer || [];
                        function BlueRaven_gtag(){dataLayer.push(arguments);}
                        BlueRaven_gtag('js', new Date());
                        BlueRaven_gtag('config', " . wp_json_encode($result_code->value) . ");
                    ";
                    wp_add_inline_script('google-BlueRaven_gtag', $inline);
					break;

				case 'microsoft-site-analytics':
					$clarity = "(function(c,l,a,r,i,t,y){
						c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
						t=l.createElement(r);t.async=1;
						t.src='https://www.clarity.ms/tag/' + i + '?ref=bwt';
						y=l.getElementsByTagName(r)[0];
						y.parentNode.insertBefore(t,y);
					})(window, document, 'clarity', 'script', '{$result_code->value}');";

					wp_register_script('clarity-placeholder', '', [], null);
					wp_enqueue_script('clarity-placeholder');
					wp_add_inline_script('clarity-placeholder', $clarity);
					break;

				case 'meta-site-analytics':
					$inline = "
                    !function(f,b,e,v,n,t,s){
                      if(f.fbq)return;n=f.fbq=function(){n.callMethod?
                      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
                      if(!f._fbq)f._fbq=n;
                      n.push=n;n.loaded=!0;n.version='2.0';
                      n.queue=[];t=b.createElement(e);t.async=!0;
                      t.src=v;s=b.getElementsByTagName(e)[0];
                      s.parentNode.insertBefore(t,s)
                    }(window, document,'script',
                    'https://connect.facebook.net/en_US/fbevents.js');
                    fbq('init', '{$result_code->value}');
                    fbq('track', 'PageView');
                    ";
                    wp_register_script('fb-pixel', false);
                    wp_enqueue_script('fb-pixel');
                    wp_add_inline_script('fb-pixel', $inline);

					add_action('wp_footer', function () use ($result_code) {
						echo '<noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=' . esc_attr($result_code->value) . '&ev=PageView&noscript=1"/></noscript>';
					});
					break;

				case 'ahref-site-analytics':
					wp_enqueue_script(
						'ahrefs-analytics',
						'https://analytics.ahrefs.com/analytics.js',
						[],
						null,
						false
					);

					///-- Add data-key attribute via filter
                    
					add_filter('script_loader_tag', function ($tag, $handle, $src) use ($result_code) {
						if ($handle === 'ahrefs-analytics') {
							return str_replace(
								'<script ',
								'<script async data-key="' . esc_attr($result_code->value) . '" ',
								$tag
							);
						}
						return $tag;
					}, 10, 3);
					break;
			}
    	}
    }
}

/*
============================================================
   CUSTOM META 
============================================================
*/

function blue_raven_output_custom_meta() {
    
    global $wpdb;
        
    $mainMetaEnabled = $wpdb->get_var( $wpdb->prepare( "SELECT enabled FROM {$wpdb->prefix}BlueRavenValues  WHERE setting LIKE %s",'main-site-meta%'));
    
    if($mainMetaEnabled){
    
    ## =========== Only proceed if we're on a singular page or post =========== ##
    
        if (!is_singular()) return;
        global $post;
    
    ## =========== Get the meta description =========== ## 
    
        $meta_description = get_post_meta($post->ID, '_blue_raven_meta_description', true);
        if (!empty($meta_description)) echo '<meta name="description" content="' . esc_attr($meta_description) . '">' . "\n";
    
    ## =========== Get the meta tags =========== ##  
    
        $meta_tags = get_post_meta($post->ID, '_blue_raven_meta_tags', true);
        if (!empty($meta_tags)) {
            $tags_array = array_map('trim', explode(',', $meta_tags)); 
            $tags_array = array_filter($tags_array);
            
            if (!empty($tags_array)) echo '<meta name="keywords" content="' . esc_attr(implode(', ', $tags_array)) . '">' . "\n";
        }
        
    ## =========== Get the current post/page data =========== ##  
    
        $post_id = get_the_ID();
        $post_title = get_the_title();
        $post_excerpt = get_the_excerpt();
        $post_url = get_permalink();
        
        $og_type;
        if (is_front_page()) {
            $og_type = 'website';
        } elseif (is_singular('post')) {
            $og_type = 'article';
        } elseif (function_exists('is_product') && is_product()) {
            $og_type = 'product';
        } elseif (is_author()) {
            $og_type = 'profile';
        } else {
            $og_type = 'website'; 
        }
        
    ## =========== Get featured image URL =========== ##  
    
        $featured_image = '';
        if (has_post_thumbnail($post_id)) $featured_image = get_the_post_thumbnail_url($post_id, 'full');
        
    ## =========== Default description (can be modified) =========== ##  
    
        $description = !empty($post_excerpt) ? wp_strip_all_tags($post_excerpt) : get_bloginfo('description');
        
    ## =========== Set the meta tags =========== ##  

        ?>
        
<!-- Open Graph Tags for Facebook, LinkedIn, etc. -->
<meta property="og:title" content="<?php echo esc_attr($post_title); ?> - <?php echo esc_attr(get_bloginfo('name')); ?>" />
<meta property="og:description" content="<?php echo esc_attr($description); ?>" />
<?php if ($featured_image) : ?>
<meta property="og:image" content="<?php echo esc_url($featured_image); ?>" />
<?php endif; ?>
<meta property="og:url" content="<?php echo esc_url($post_url); ?>" />
<meta property="og:type" content="<?php echo esc_attr($og_type); ?>" />
<meta property="og:site_name" content="<?php echo esc_attr(get_bloginfo('name')); ?>" />

<!-- Twitter Card Tags -->
<?php $twitter_card_type = (has_post_thumbnail()) ? 'summary_large_image' : 'summary'; ?>
<meta name="twitter:card" content="<?php echo esc_attr($twitter_card_type); ?>" />
<meta name="twitter:title" content="<?php echo esc_attr($post_title); ?> - <?php echo esc_attr(get_bloginfo('name')); ?>" />
<meta name="twitter:description" content="<?php echo esc_attr($description); ?>" />
<?php if ($featured_image) : ?>
<meta name="twitter:image" content="<?php echo esc_url($featured_image); ?>" />
<?php endif;
        
    }
}

/*
============================================================
   SITE SCHEMA
============================================================
*/

function blue_raven_site_schema() { 
    global $wpdb;

    $schemaEnable = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$wpdb->prefix}BlueRavenValues WHERE setting LIKE %s",'%schema-enable%'));

    if (!empty($schemaEnable) && !empty($schemaEnable[0]->enabled)) {
        $schemaText = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}BlueRavenValues WHERE setting LIKE %s",'%schema-script%'));
        if (!empty($schemaText) && isset($schemaText[0]->value)) echo $schemaText[0]->value . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is trusted JSON-LD schema
    }
}

/*
============================================================
   SITE MAP INDEXNOW
============================================================
*/

function blue_raven_contactIndexNow($post_id) {
    
    global $wpdb;
    if (wp_is_post_revision($post_id) || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) return;
    $url = get_permalink($post_id);

    $bingSiteMapKeys = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$wpdb->prefix}BlueRavenValues  WHERE setting LIKE %s",'%bing-site-map-key%') );
    
     ## =========== Notify Bing =========== ## 

    if (!empty($bingSiteMapKeys) && !empty($bingSiteMapKeys[0]->enabled)) {
        $key = $bingSiteMapKeys[0]->value;

        $response = wp_remote_post('https://api.indexnow.org/indexnow', [ 'headers' => ['Content-Type' => 'application/json'],'body'    => json_encode(['host'    => wp_parse_url(home_url(), PHP_URL_HOST),'key'     => $key,'urlList' => [$url],]) ]);
        
        if (is_wp_error($response)) {
            BlueRaven_SendError("ERROR", "blue-raven/includes/hooks.php", "IndexNow ping failed", $response->get_error_message()); 
            error_log('IndexNow ping failed: ' . $response->get_error_message());
        }    
    }
}

/*
============================================================
   PRODUCT UPDATES AND DELETING
============================================================
*/

function blue_raven_updateProduct($post_id) {

    ## ===========  Skip autosaves, revisions, and non-products =========== ## 

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (wp_is_post_revision($post_id)) return;
    if (get_post_type($post_id) !== 'product') return;
    if (get_post_status($post_id) === 'trash') return;
    
    ## =========== Mark as processed so next time it counts as an update =========== ## 
    
    $is_new = get_post_meta($post_id, '_blue_raven_already_processed', true) !== 'yes';
    if ($is_new) {
        update_post_meta($post_id, '_blue_raven_already_processed', 'yes'); return;

    }else{
        global $wpdb;
        $table_name = $wpdb->prefix . 'BlueRavenProducts';
        $db_product_id = $wpdb->get_var($wpdb->prepare("SELECT id FROM $table_name WHERE woo_product_id = %d",$post_id));
        if (!$db_product_id) return; 

    }
    
    ## =========== Export the product =========== ## 

    require_once BLUERAVEN_PLUGIN_DIR . 'includes/third-party/class-blue-raven-woo-exporter.php';
    exportWooProduct($post_id);
}

function blue_raven_delete_product($post_id) {

    ## =========== Delete Product =========== ## 
    
    if (get_post_type($post_id) !== 'product') return;

    global $wpdb;
    $table_name = $wpdb->prefix . 'BlueRavenProducts';
    $wpdb->delete($table_name,array('woo_product_id' => $post_id),array('%d'));
    
    if ($wpdb->last_error) {BlueRaven_SendError("ERROR", "blue-raven/includes/hooks.php", "Deleting a product", "Failed to delete product ID {$post_id} from BlueRavenProducts: " . $wpdb->last_error);}
}

/*
============================================================
   STOCKS PRODUCT UPDATES
============================================================
*/

    ## =========== Hook when product stock is set/updated =========== ##

function blue_raven_export_on_stock_change( $product ) {
    if ( ! $product instanceof WC_Product ) return;
    $post_id = $product->get_id();

    global $wpdb;
    $table_name = $wpdb->prefix . 'BlueRavenProducts';
    $product_exists = $wpdb->get_var($wpdb->prepare("SELECT 1 FROM $table_name WHERE woo_product_id = %d LIMIT 1",$post_id));
    if ( ! $product_exists ) return;

    require_once BLUERAVEN_PLUGIN_DIR . 'includes/third-party/class-blue-raven-woo-exporter.php';
    exportWooProduct($post_id);
}

    ## =========== Hook when stock status changes (optional, if you want to track in-stock/out-of-stock transitions) =========== ##

function blue_raven_export_on_stock_status_change( $product_id, $stock_status ) {
    $product = wc_get_product( $product_id );
    if ( ! $product ) return;

    global $wpdb;
    $table_name = $wpdb->prefix . 'BlueRavenProducts';
    $product_exists = $wpdb->get_var($wpdb->prepare( "SELECT 1 FROM $table_name WHERE woo_product_id = %d LIMIT 1",$product_id));
    if ( ! $product_exists ) return;

    require_once BLUERAVEN_PLUGIN_DIR . 'includes/third-party/class-blue-raven-woo-exporter.php';
    exportWooProduct($product_id);
}

    ## =========== Hook when order reduces stock (purchase) =========== ##
 
function blue_raven_export_on_order_stock_reduce( $order ) {
    if ( ! $order instanceof WC_Order ) return;

    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        if ( $product ) {
            $post_id = $product->get_id();

            global $wpdb;
            $table_name = $wpdb->prefix . 'BlueRavenProducts';
            $product_exists = $wpdb->get_var($wpdb->prepare("SELECT 1 FROM $table_name WHERE woo_product_id = %d LIMIT 1",$post_id));
            if ( ! $product_exists ) return;

            require_once BLUERAVEN_PLUGIN_DIR . 'includes/third-party/class-blue-raven-woo-exporter.php';
            exportWooProduct($post_id);
        }
    }
}

/*
============================================================
    BLUE RAVEN ADD PRODUCT SCHEMA
============================================================
*/

function blue_raven_add_product_schema() {

    if ( ! function_exists( 'is_product' ) ) return;
    if (!is_product()) return;

    global $product;

    if (!$product || !is_a($product, 'WC_Product')) return;

    $product_id = $product->get_id();
    $currency = get_woocommerce_currency();
    $price = $product->get_price();
    $sku = $product->get_sku() ?: 'SKU-' . $product_id;
    $availability = $product->is_in_stock() ? 'http://schema.org/InStock' : 'http://schema.org/OutOfStock';
    $condition = 'http://schema.org/NewCondition';
    $image = wp_get_attachment_url($product->get_image_id());
    $reviews_enabled = comments_open($product_id);
    $rating_count = $product->get_rating_count();
    $average_rating = $product->get_average_rating();

    // Get store unit settings
    $weight_unit = get_option('woocommerce_weight_unit');
    $dimension_unit = get_option('woocommerce_dimension_unit');

    // Map WooCommerce units to Schema.org unitCode values
    function BlueRaven_br_get_unit_code($type, $unit) {
        $unit_map = [
            'weight' => [
                'kg' => 'KGM',
                'g' => 'GRM',
                'lbs' => 'LBR',
                'oz' => 'ONZ'
            ],
            'dimension' => [
                'cm' => 'CMT',
                'mm' => 'MMT',
                'm' => 'MTR',
                'in' => 'INH',
                'ft' => 'FOT'
            ]
        ];
        return $unit_map[$type][$unit] ?? null;
    }

    $weight_code = BlueRaven_br_get_unit_code('weight', $weight_unit);
    $dimension_code = BlueRaven_br_get_unit_code('dimension', $dimension_unit);

    $schema = [
        '@context' => 'https://schema.org/',
        '@type' => 'Product',
        'name' => $product->get_name(),
        'description' => wp_strip_all_tags($product->get_description()),
        'sku' => $sku,
        'url' => get_permalink($product_id),
        'image' => $image,
        'brand' => [
            '@type' => 'Thing',
            'name' => get_bloginfo('name')
        ],
        'offers' => [
            '@type' => 'Offer',
            'priceCurrency' => $currency,
            'price' => $price,
            'availability' => $availability,
            'itemCondition' => $condition,
            'url' => get_permalink($product_id),
            'priceValidUntil' => gmdate('Y-12-31'),
        ],
    ];

        ///-- Optional: Aggregate rating

    if ($rating_count > 0) {
        $schema['aggregateRating'] = [
            '@type' => 'AggregateRating',
            'ratingValue' => $average_rating,
            'reviewCount' => $rating_count,
        ];
    }

        ///-- Optional: Weight and dimensions

    $weight = $product->get_weight();
    $length = $product->get_length();
    $width = $product->get_width();
    $height = $product->get_height();

    if ($weight && $weight_code) {
        $schema['shippingDetails'] = [
            '@type' => 'OfferShippingDetails',
            'shippingWeight' => [
                '@type' => 'QuantitativeValue',
                'value' => floatval($weight),
                'unitCode' => $weight_code
            ]
        ];
    }

    if (($length || $width || $height) && $dimension_code) {
        if ($height) {
            $schema['height'] = [
                '@type' => 'QuantitativeValue',
                'value' => floatval($height),
                'unitCode' => $dimension_code
            ];
        }
        if ($width) {
            $schema['width'] = [
                '@type' => 'QuantitativeValue',
                'value' => floatval($width),
                'unitCode' => $dimension_code
            ];
        }
        if ($length) {
            $schema['depth'] = [
                '@type' => 'QuantitativeValue',
                'value' => floatval($length),
                'unitCode' => $dimension_code
            ];
        }
    }

        ///-- Optional: Sample review

    if ($reviews_enabled && $rating_count > 0) {
        $args = [
            'post_id' => $product_id,
            'number' => 1,
            'status' => 'approve',
            'meta_key' => 'rating',
        ];
        $comments = get_comments($args);

        if (!empty($comments)) {
            $comment = $comments[0];
            $rating = intval(get_comment_meta($comment->comment_ID, 'rating', true));
            $schema['review'] = [
                '@type' => 'Review',
                'author' => $comment->comment_author,
                'datePublished' => get_comment_date('c', $comment),
                'reviewBody' => wp_strip_all_tags($comment->comment_content),
                'reviewRating' => [
                    '@type' => 'Rating',
                    'ratingValue' => $rating
                ]
            ];
        }
    }

    echo '<script type="application/ld+json">' . wp_json_encode($schema, JSON_UNESCAPED_SLASHES) . '</script>';
}

/*
============================================================
    WC TRACK PRODUCT SLUG CHANGE
============================================================
*/

function BlueRaven_wc_track_product_slug_changes($post_id, $post_after, $post_before) {
    if ($post_after->post_type !== 'product') return;
    if ($post_after->post_name === $post_before->post_name) return;
    $redirects = get_option('blue_raven_wc_product_slug_redirects', array());
    foreach ($redirects as $old_slug => $new_slug) {if ($new_slug === $post_before->post_name) unset($redirects[$old_slug]);}
    $redirects[$post_before->post_name] = $post_after->post_name;
    update_option('blue_raven_wc_product_slug_redirects', $redirects);
}

/*
============================================================
   WC HANDLE PRODUCT REDIRECTS
============================================================
*/

function BlueRaven_wc_handle_product_redirects() {
    if (!is_404()) return;

    global $wp;
    $requested_slug = basename($wp->request);

    $redirects = get_option('blue_raven_wc_product_slug_redirects', array());
    if (isset($redirects[$requested_slug])) {
        $new_slug = $redirects[$requested_slug];
        $product = get_page_by_path($new_slug, OBJECT, 'product');
        if ($product) { wp_redirect(get_permalink($product->ID), 301);  exit;}
    }
}

/*
============================================================
   WC CLEANUP PRODUCT REDIRECTS
============================================================
*/

function BlueRaven_wc_cleanup_product_redirects($post_id) {
    $post = get_post($post_id);
    if ($post->post_type !== 'product') return;
    $redirects = get_option('blue_raven_wc_product_slug_redirects', array());
    foreach ($redirects as $old_slug => $new_slug) {if ($new_slug === $post->post_name) unset($redirects[$old_slug]);}
    if (isset($redirects[$post->post_name])) {unset($redirects[$post->post_name]);}
    update_option('blue_raven_wc_product_slug_redirects', $redirects);
}

/*
============================================================
    BLUE RAVEN FORM HOOK
============================================================
*/

function blueRaven_Form_shortcode($atts) {
    global $wpdb;

    $atts = shortcode_atts(['id' => '',], $atts);
    if (empty($atts['id'])) return 'No ID provided.';
    $shortcode_key = 'blueRaven_Form id="' . esc_attr($atts['id']) . '"';
    $messages_table_name = $wpdb->prefix . 'BlueRavenMessages';

    // =========== Query the DB for the row with the matching shortcode string =========== //
    
    $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$messages_table_name} WHERE shortcode = %s",$shortcode_key), ARRAY_A);
    if (!$row) return 'No Form found.';

    $form_data = json_decode($row['form'] ?? '[]', true);
    $form_data = is_array($form_data) ? $form_data : [];

    // =========== Prepare values for frontend =========== //
    
    $form_html          = BlueRaven_buildHTML($form_data);
    $messages           = $row['messages'] ?? '{}';
    $bot_config         = json_decode($row['bot_prevention'] ?? '{}', true);
    $provider           = $bot_config['provider'] ?? 'none';
    $site_key           = esc_attr($bot_config['site_key'] ?? '');
    $template           = $row['template'];

    // =========== Encode values for use in hidden fields or JS =========== //
    
    $unique_form_id = esc_attr($atts['id']);
    // These scripts must be loaded from their official endpoints for security reasons
    switch ($provider) {
        case 'turnstile':
            wp_enqueue_script('cf-turnstile', 'https://challenges.cloudflare.com/turnstile/v0/api.js', [], null, true);
            break;

        case 'recaptcha':
            wp_enqueue_script('google-recaptcha', 'https://www.google.com/recaptcha/api.js', [], null, true);
            break;

        case 'hcaptcha':
            wp_enqueue_script('hcaptcha', 'https://js.hcaptcha.com/1/api.js', [], null, true);
            break;
    }

    ob_start();
    ?>
        <form class="blue-raven-form" data-form-id="<?php echo esc_attr($unique_form_id); ?>" method="post" novalidate>
			<?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $form_html contains trusted, pre-rendered HTML
			echo $form_html; ?>
			<input type="hidden" name="captcha_token" class="captcha-token-field">

			<?php if ($provider === 'turnstile'): ?>
				<div class="cf-turnstile" data-sitekey="<?php echo esc_attr($site_key); ?>" data-callback="BlueRaven_onTurnstileSuccess"></div>

			<?php elseif ($provider === 'recaptcha'): ?>
				<div class="g-recaptcha"
					 data-sitekey="<?php echo esc_attr($site_key); ?>"
					 data-callback="BlueRaven_onReCaptchaSuccess"
					 data-size="invisible"></div>

			<?php elseif ($provider === 'hcaptcha'): ?>
				<div class="h-captcha"
					 data-sitekey="<?php echo esc_attr($site_key); ?>"
					 data-callback="BlueRaven_onHcaptchaSuccess"></div>
			<?php endif; ?>
		</form>
        <script>
            function BlueRaven_onTurnstileSuccess(token) { document.querySelector('.captcha-token-field').value = token; }
            function BlueRaven_onReCaptchaSuccess(token) { document.querySelector('.captcha-token-field').value = token; }
            function BlueRaven_onHcaptchaSuccess(token) { document.querySelector('.captcha-token-field').value = token;}
            const msg = document.getElementById('br-mf-m');
            if (msg) msg.innerHTML = '';
        </script>
        
        <style>@media (max-width: 920px) {#br-mf-f {display: block !important;}#br-mf-l,#br-mf-r { width: 100% !important;}} </style>
    <?php
    return ob_get_clean();
}

/*
============================================================
    HOOK ACTIONS 
============================================================
*/

    ## =========== Tools =========== ##

add_action('wp_head', 'BlueRaven_add_site_verification_meta_tag');
add_action('wp_head', 'BlueRaven_add_site_analytics_meta_tag');
add_action('wp_head', 'blue_raven_output_custom_meta');
add_action('wp_head', 'blue_raven_site_schema');
add_action('wp_head', 'blue_raven_add_product_schema');
add_action('save_post', 'blue_raven_contactIndexNow');

    ## =========== Product =========== ##
    
add_action('save_post', 'blue_raven_updateProduct');
add_action('trashed_post', 'blue_raven_delete_product');
add_action('deleted_post', 'blue_raven_delete_product');

add_action('woocommerce_product_set_stock', 'blue_raven_export_on_stock_change', 10, 1);
add_action('woocommerce_product_set_stock_status', 'blue_raven_export_on_stock_status_change', 10, 2);
add_action('woocommerce_reduce_order_stock', 'blue_raven_export_on_order_stock_reduce', 10, 1);

add_action('post_updated', 'BlueRaven_wc_track_product_slug_changes', 10, 3);
add_action('template_redirect', 'BlueRaven_wc_handle_product_redirects');
add_action('before_delete_post', 'BlueRaven_wc_cleanup_product_redirects');

/*
============================================================
    SHORT CODES
============================================================
*/

add_shortcode('blueRaven_Form', 'blueRaven_Form_shortcode');

/*
============================================================
    CSS FRONT END
============================================================
*/

function enqueue_blue_raven_styles() {
    $css_path = BLUERAVEN_PLUGIN_DIR . 'assets/css/blue-raven.css';
    $css_url  = BLUERAVEN_PLUGIN_URL . 'assets/css/blue-raven.css';

    if (file_exists($css_path)) {
        wp_enqueue_style(
            'blue-raven-style',
            $css_url,
            array(),
            filemtime($css_path)
        );
    }
}
add_action('wp_enqueue_scripts', 'enqueue_blue_raven_styles');
