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

// =============================================
// ✅ 1. THEME SUPPORT
// =============================================
add_theme_support('post-thumbnails');
add_theme_support('title-tag');
add_theme_support('custom-logo');

// =============================================
// ✅ 2. INCLUDE FILES SAFELY
// =============================================
$inc_path = get_template_directory() . '/inc/';

if (file_exists($inc_path . 'custom-post-types.php')) include_once $inc_path . 'custom-post-types.php';
if (file_exists($inc_path . 'custom-dashboard.php')) include_once $inc_path . 'custom-dashboard.php';
if (file_exists($inc_path . 'order-management.php')) include_once $inc_path . 'order-management.php';
if (file_exists($inc_path . 'tracking-apis.php')) include_once $inc_path . 'tracking-apis.php';

// =============================================
// ✅ 3. ENQUEUE SCRIPTS & STYLES
// =============================================
if (!function_exists('herbal_shop_scripts')) {
    function herbal_shop_scripts() {
        $css_ver = file_exists(get_stylesheet_directory() . '/style.css') ? filemtime(get_stylesheet_directory() . '/style.css') : '1.0';
        wp_enqueue_style('main-style', get_stylesheet_uri(), array(), $css_ver);
        wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', array(), null, true);
        wp_enqueue_script('jquery');
        
        wp_localize_script('jquery', 'herbal_ajax_obj', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('herbal_ajax_nonce')
        ));
        
        if (file_exists(get_template_directory() . '/assets/js/main.js')) {
            $js_ver = filemtime(get_template_directory() . '/assets/js/main.js');
            wp_enqueue_script('custom-js', get_template_directory_uri() . '/assets/js/main.js', array('jquery'), $js_ver, true);
            wp_localize_script('custom-js', 'herbal_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
        }
    }
    add_action('wp_enqueue_scripts', 'herbal_shop_scripts');
}

// =============================================
// ✅ 4. NO-CACHE HEADERS
// =============================================
if (!function_exists('add_no_cache_headers')) {
    function add_no_cache_headers($headers) {
        if (!is_admin()) {
            $headers['Cache-Control'] = 'no-cache, must-revalidate, max-age=0';
        }
        return $headers;
    }
    add_filter('wp_headers', 'add_no_cache_headers');
}

// =============================================
// ✅ 5. DATABASE TABLES AUTO-CREATION
// =============================================
if (!function_exists('herbal_check_and_create_tables')) {
    function herbal_check_and_create_tables() {
        global $wpdb;
        $table_orders = $wpdb->prefix . 'herbal_orders';
        $table_views  = $wpdb->prefix . 'herbal_page_views';
        $table_live   = $wpdb->prefix . 'herbal_live_visitors';
        $charset_collate = $wpdb->get_charset_collate();

        $sql1 = "CREATE TABLE IF NOT EXISTS $table_orders (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            product_id bigint(20) DEFAULT 0,
            product_name varchar(255) DEFAULT '',
            quantity int(11) DEFAULT 1,
            customer_name varchar(255) NOT NULL,
            phone varchar(50) NOT NULL,
            district varchar(100) DEFAULT '',
            delivery_charge decimal(10,2) DEFAULT 0.00,
            address text NOT NULL,
            total_price decimal(10,2) DEFAULT 0.00,
            status varchar(50) DEFAULT 'pending',
            ip_address varchar(45) DEFAULT '',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id)
        ) $charset_collate;";

        $sql2 = "CREATE TABLE IF NOT EXISTS $table_views (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            page_url varchar(255) NOT NULL,
            page_title varchar(255) NOT NULL,
            ip_address varchar(45) NOT NULL,
            user_agent text,
            session_id varchar(100) NOT NULL,
            view_time datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY session_id (session_id)
        ) $charset_collate;";

        $sql3 = "CREATE TABLE IF NOT EXISTS $table_live (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            session_id varchar(100) NOT NULL,
            ip_address varchar(45) NOT NULL,
            country varchar(100) DEFAULT 'Bangladesh',
            city varchar(100) DEFAULT 'Dhaka',
            page_title text,
            page_url text,
            time_spent int(11) DEFAULT 5,
            last_active datetime DEFAULT CURRENT_TIMESTAMP,
            is_checkout tinyint(1) DEFAULT 0,
            PRIMARY KEY (id),
            UNIQUE KEY session_id (session_id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql1);
        dbDelta($sql2);
        dbDelta($sql3);

        $existing_columns = $wpdb->get_col("DESC $table_orders", 0);
        $required_cols = array('product_id', 'product_name', 'quantity', 'district', 'delivery_charge', 'total_price', 'ip_address');
        foreach ($required_cols as $col) {
            if (!in_array($col, $existing_columns)) {
                $wpdb->query("ALTER TABLE $table_orders ADD $col varchar(255) DEFAULT ''");
            }
        }
    }
    add_action('init', 'herbal_check_and_create_tables');
}

// =============================================
// ✅ 6. CHECKOUT AJAX PROCESSOR (EXACT INPUT SAVING)
// =============================================
if (!function_exists('herbal_process_checkout_callback')) {
    function herbal_process_checkout_callback() {
        global $wpdb;
        $table_orders = $wpdb->prefix . 'herbal_orders';

        // REAL IP DETECTION
        $user_ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
        if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $user_ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $user_ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        }

        // CHECK IF IP IS BLOCKED
        $blocked_arr = get_option('sobkishu_blocked_ips_arr', array());
        if (in_array(trim($user_ip), $blocked_arr)) {
            wp_send_json_error(['message' => 'আপনার IP থেকে অনাকাঙ্ক্ষিত অ্যাক্টিভিটির কারণে অর্ডার গ্রহণ বন্ধ রাখা হয়েছে।']);
            return;
        }

        $c_name     = sanitize_text_field($_POST['customer_name'] ?? $_POST['name'] ?? '');
        $c_phone    = sanitize_text_field($_POST['phone'] ?? '');
        $c_district = sanitize_text_field($_POST['district'] ?? 'inside_dhaka');
        $del_charge = floatval($_POST['delivery_charge'] ?? 0);
        $c_address  = sanitize_textarea_field($_POST['address'] ?? '');
        $p_id       = intval($_POST['product_id'] ?? 0);
        $p_name     = sanitize_text_field($_POST['product_name'] ?? ($p_id ? get_the_title($p_id) : 'হেয়ার এক্সটেনশন'));
        $qty        = intval($_POST['quantity'] ?? 1);
        $total_price= floatval($_POST['total_price'] ?? $_POST['total'] ?? 0);
        $status     = sanitize_text_field($_POST['status'] ?? 'pending');

        if ($status === 'pending') {
            if (empty($c_phone) || strlen($c_phone) < 6) {
                wp_send_json_error(['message' => 'সঠিক মোবাইল নম্বর দিন']);
                return;
            }
            if (empty($c_address)) {
                wp_send_json_error(['message' => 'আপনার সম্পূর্ণ ঠিকানা লিখুন']);
                return;
            }

            $recent_same_order = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $table_orders 
                 WHERE (phone = %s OR ip_address = %s) 
                 AND product_id = %d 
                 AND status = 'pending' 
                 AND created_at >= NOW() - INTERVAL 10 MINUTE",
                $c_phone, $user_ip, $p_id
            ));

            if ($recent_same_order > 0) {
                wp_send_json_error(['message' => 'আপনার অর্ডারটি ইতোমধ্যে নেওয়া হয়েছে! ১০ মিনিট পর আবার চেষ্টা করুন।']);
                return;
            }
        } else {
            if (empty($c_phone)) {
                wp_send_json_error(['message' => 'ফোন নম্বর প্রয়োজন']);
                return;
            }
        }

        // FIND EXISTING INCOMPLETE ORDER BY IP ADDRESS OR PHONE
        $existing = $wpdb->get_row($wpdb->prepare(
            "SELECT id FROM $table_orders WHERE (ip_address = %s OR phone = %s) AND status = 'incomplete' ORDER BY id DESC LIMIT 1",
            $user_ip, $c_phone
        ));

        if ($existing) {
            $wpdb->update($table_orders, array(
                'customer_name'   => $c_name ?: 'ইনকমপ্লিট গ্রাহক',
                'phone'           => $c_phone,
                'address'         => $c_address,
                'district'        => $c_district,
                'delivery_charge' => $del_charge,
                'product_id'      => $p_id,
                'product_name'    => $p_name,
                'quantity'        => $qty,
                'total_price'     => $total_price,
                'status'          => $status,
                'ip_address'      => $user_ip,
                'created_at'      => current_time('mysql')
            ), array('id' => $existing->id));
            $order_id = $existing->id;
        } else {
            $wpdb->insert($table_orders, array(
                'product_id'      => $p_id,
                'product_name'    => $p_name,
                'quantity'        => $qty,
                'customer_name'   => $c_name ?: 'ইনকমপ্লিট গ্রাহক',
                'phone'           => $c_phone,
                'district'        => $c_district,
                'delivery_charge' => $del_charge,
                'address'         => $c_address,
                'total_price'     => $total_price,
                'status'          => $status,
                'ip_address'      => $user_ip,
                'created_at'      => current_time('mysql')
            ));
            $order_id = $wpdb->insert_id;
        }

        if ($order_id) {
            // ONLY CONFIRMED PENDING ORDERS TRIGGER PIXEL & TELEGRAM
            if ($status === 'pending') {
                if (function_exists('send_telegram_order_alert')) {
                    send_telegram_order_alert(array(
                        'order_id'        => $order_id,
                        'name'            => $c_name,
                        'phone'           => $c_phone,
                        'district'        => ($c_district === 'inside_dhaka') ? 'ঢাকার ভেতরে' : 'ঢাকার বাইরে',
                        'delivery_charge' => $del_charge,
                        'address'         => $c_address,
                        'product_name'    => $p_name,
                        'quantity'        => $qty,
                        'total_price'     => $total_price,
                        'ip_address'      => $user_ip
                    ));
                }

                do_action('herbal_order_confirmed', $order_id, array(
                    'total'      => $total_price,
                    'product_id' => $p_id,
                    'quantity'   => $qty
                ));
            }

            wp_send_json_success(array(
                'order_id'     => $order_id,
                'redirect_url' => home_url('/thank-you/?order_id=' . $order_id . '&name=' . urlencode($c_name))
            ));
        } else {
            wp_send_json_error(array('message' => 'অর্ডার সংরক্ষণ করা যায়নি।'));
        }
    }
    add_action('wp_ajax_submit_herbal_order', 'herbal_process_checkout_callback');
    add_action('wp_ajax_nopriv_submit_herbal_order', 'herbal_process_checkout_callback');
}

// =============================================
// ✅ 7. TELEGRAM ORDER NOTIFICATION
// =============================================
if (!function_exists('send_telegram_order_alert')) {
    function send_telegram_order_alert($order_data) {
        $bot_token = get_option('sobkishu_telegram_bot_token', '');
        $chat_id   = get_option('sobkishu_telegram_chat_id', '');

        if (empty($bot_token) || empty($chat_id)) return;

        $qty = isset($order_data['quantity']) ? $order_data['quantity'] : 1;

        $msg  = "🛒 *নতুন অর্ডার এসেছে! (Hair Extensions BD)*\n\n";
        $msg .= "🆔 *অর্ডার আইডি:* #" . ($order_data['order_id'] ?? 'N/A') . "\n";
        $msg .= "👤 *গ্রাহক:* " . ($order_data['name'] ?? 'N/A') . "\n";
        $msg .= "📞 *ফোন:* " . ($order_data['phone'] ?? 'N/A') . "\n";
        $msg .= "🚚 *এলাকা:* " . ($order_data['district'] ?? 'N/A') . " (চার্জ: ৳" . ($order_data['delivery_charge'] ?? 0) . ")\n";
        $msg .= "🏠 *ঠিকানা:* " . ($order_data['address'] ?? 'N/A') . "\n";
        $msg .= "📦 *প্রোডাক্ট:* " . ($order_data['product_name'] ?? 'N/A') . " (পরিমাণ: " . $qty . " টি)\n";
        $msg .= "💰 *মোট মূল্য:* ৳" . ($order_data['total_price'] ?? 0) . "\n";
        $msg .= "🌐 *IP:* " . ($order_data['ip_address'] ?? $_SERVER['REMOTE_ADDR']) . "\n";

        $url = "https://api.telegram.org/bot{$bot_token}/sendMessage";
        wp_remote_post($url, array(
            'body' => array(
                'chat_id'    => $chat_id,
                'text'       => $msg,
                'parse_mode' => 'Markdown'
            ),
            'timeout' => 10
        ));
    }
}

// =============================================
// ✅ 8. DYNAMIC SEO DOCUMENT TITLE
// =============================================
if (!function_exists('herbal_custom_seo_document_title')) {
    function herbal_custom_seo_document_title($title) {
        $site_name = 'Hair Extensions BD';

        if (is_front_page() || is_home()) {
            return $site_name . ' - প্রিমিয়াম হেয়ার এক্সটেনশন স্টোর';
        }
        if (is_singular('hair_product') || is_singular('herbal_product')) {
            return single_post_title('', false) . ' | ' . $site_name;
        }
        
        $request_uri = $_SERVER['REQUEST_URI'];
        if (strpos($request_uri, 'checkout') !== false) {
            return 'অর্ডার কনফার্ম করুন | ' . $site_name;
        }
        if (strpos($request_uri, 'thank-you') !== false) {
            return 'অর্ডার সফল হয়েছে! ধন্যবাদ | ' . $site_name;
        }
        if (is_tax('hair_product_cat')) {
            return single_term_title('', false) . ' | ' . $site_name;
        }
        if (is_single() || is_page()) {
            return single_post_title('', false) . ' | ' . $site_name;
        }

        return $site_name;
    }
    add_filter('pre_get_document_title', 'herbal_custom_seo_document_title', 9999);
}

// =============================================
// ✅ 9. CUSTOM ROUTING
// =============================================
if (!function_exists('herbal_handle_custom_page_routes')) {
    function herbal_handle_custom_page_routes() {
        global $wp_query;
        $request_uri = $_SERVER['REQUEST_URI'];
        $request_path = parse_url($request_uri, PHP_URL_PATH);
        $request_path = trim($request_path, '/');

        if (strpos($request_path, 'product/') !== false || strpos($request_path, 'herbal_product/') !== false) {
            $path_parts = explode('/', $request_path);
            $post_slug = end($path_parts) ?: prev($path_parts);

            $product_post = get_page_by_path($post_slug, OBJECT, array('hair_product', 'herbal_product'));

            if ($product_post) {
                $single_file = get_template_directory() . '/single-hair_product.php';
                if (!file_exists($single_file)) {
                    $single_file = get_template_directory() . '/single-herbal_product.php';
                }

                if (file_exists($single_file)) {
                    status_header(200);
                    $wp_query->is_404 = false;
                    $wp_query->is_single = true;
                    $wp_query->is_singular = true;
                    $wp_query->queried_object = $product_post;
                    $wp_query->queried_object_id = $product_post->ID;
                    $wp_query->post = $product_post;
                    $wp_query->posts = array($product_post);
                    $wp_query->post_count = 1;

                    setup_postdata($product_post);
                    include $single_file;
                    exit;
                }
            }
        }

        if (strpos($request_path, 'checkout') !== false || $request_path === 'checkout') {
            $checkout_file = get_template_directory() . '/page-checkout.php';
            if (file_exists($checkout_file)) {
                status_header(200);
                $wp_query->is_404 = false;
                $wp_query->is_page = true;
                include $checkout_file;
                exit;
            }
        }

        if (strpos($request_path, 'thank-you') !== false || $request_path === 'thank-you') {
            $thankyou_file = get_template_directory() . '/page-thank-you.php';
            if (file_exists($thankyou_file)) {
                status_header(200);
                $wp_query->is_404 = false;
                $wp_query->is_page = true;
                include $thankyou_file;
                exit;
            }
        }
    }
    add_action('template_redirect', 'herbal_handle_custom_page_routes', 1);
}

if (!function_exists('herbal_fix_page_redirects')) {
    function herbal_fix_page_redirects() {
        if (is_404()) {
            $request_uri = $_SERVER['REQUEST_URI'];
            if (strpos($request_uri, 'checkout') !== false || 
                strpos($request_uri, 'thank-you') !== false || 
                strpos($request_uri, 'product/') !== false || 
                strpos($request_uri, 'herbal_product/') !== false) {
                status_header(200);
                if (function_exists('herbal_handle_custom_page_routes')) {
                    herbal_handle_custom_page_routes();
                }
                exit;
            }
        }
    }
    add_action('wp', 'herbal_fix_page_redirects', 1);
}

// =============================================
// ✅ 10. ADMIN MENU & SETTINGS PAGE
// =============================================
add_action('admin_menu', function() {
    if (function_exists('render_herbal_dashboard_page')) {
        add_menu_page('Analytics', '📊 Analytics', 'manage_options', 'herbal-dashboard', 'render_herbal_dashboard_page', 'dashicons-chart-bar', 2);
    }
    if (function_exists('render_herbal_orders_page')) {
        add_menu_page('Order Management', '📦 Orders', 'manage_options', 'herbal-orders', 'render_herbal_orders_page', 'dashicons-cart', 3);
    }
    if (function_exists('render_tracking_apis_page')) {
        add_submenu_page('herbal-dashboard', 'Tracking APIs', '📡 Tracking APIs', 'manage_options', 'herbal-tracking-apis', 'render_tracking_apis_page');
    }
    if (function_exists('render_herbal_theme_settings_page')) {
        add_menu_page('Theme Settings', '⚙️ Settings', 'manage_options', 'herbal-theme-settings', 'render_herbal_theme_settings_page', 'dashicons-admin-generic', 4);
    }
});

if (!function_exists('render_herbal_theme_settings_page')) {
    function render_herbal_theme_settings_page() {
        if (isset($_POST['save_herbal_settings'])) {
            update_option('sobkishu_header_title', sanitize_text_field($_POST['sobkishu_header_title'] ?? ''));
            update_option('sobkishu_header_bg_color', sanitize_hex_color($_POST['sobkishu_header_bg_color'] ?? '#D4A5A5'));
            update_option('sobkishu_site_logo', esc_url_raw($_POST['sobkishu_site_logo'] ?? ''));
            update_option('sobkishu_banner_slider_urls', sanitize_textarea_field($_POST['sobkishu_banner_slider_urls'] ?? ''));
            
            update_option('sobkishu_inside_dhaka_charge', floatval($_POST['sobkishu_inside_dhaka_charge'] ?? 60));
            update_option('sobkishu_outside_dhaka_charge', floatval($_POST['sobkishu_outside_dhaka_charge'] ?? 120));

            update_option('sobkishu_enable_free_delivery_notice', sanitize_text_field($_POST['sobkishu_enable_free_delivery_notice'] ?? 'no'));
            update_option('sobkishu_free_delivery_notice_text', sanitize_text_field($_POST['sobkishu_free_delivery_notice_text'] ?? 'আজকের জন্য শুধু ডেলিভারি চার্জ সম্পূর্ণ ফ্রি'));
            update_option('sobkishu_order_btn_animation', sanitize_text_field($_POST['sobkishu_order_btn_animation'] ?? 'yes'));
            update_option('sobkishu_order_btn_color', sanitize_hex_color($_POST['sobkishu_order_btn_color'] ?? '#e53935'));

            update_option('sobkishu_enable_reviews', sanitize_text_field($_POST['sobkishu_enable_reviews'] ?? 'yes'));

            if (isset($_POST['review_img1']) && is_array($_POST['review_img1'])) {
                $reviews = array();
                for ($i = 0; $i < count($_POST['review_img1']); $i++) {
                    $img1 = esc_url_raw($_POST['review_img1'][$i] ?? '');
                    $img2 = esc_url_raw($_POST['review_img2'][$i] ?? '');
                    if (!empty($img1)) {
                        $reviews[] = array('img1' => $img1, 'img2' => $img2);
                    }
                }
                update_option('sobkishu_customer_review_screenshots', $reviews);
            }

            update_option('sobkishu_offer_title', sanitize_text_field($_POST['sobkishu_offer_title'] ?? ''));
            update_option('sobkishu_offer_subtitle', sanitize_text_field($_POST['sobkishu_offer_subtitle'] ?? ''));
            update_option('sobkishu_telegram_bot_token', sanitize_text_field($_POST['sobkishu_telegram_bot_token'] ?? ''));
            update_option('sobkishu_telegram_chat_id', sanitize_text_field($_POST['sobkishu_telegram_chat_id'] ?? ''));
            
            update_option('herbal_phone_number', sanitize_text_field($_POST['herbal_phone_number'] ?? ''));
            update_option('herbal_whatsapp_number', sanitize_text_field($_POST['herbal_whatsapp_number'] ?? ''));
            update_option('herbal_messenger_link', esc_url_raw($_POST['herbal_messenger_link'] ?? ''));

            echo '<div class="notice notice-success is-dismissible"><p>✅ সেটিংস সফলভাবে সেভ করা হয়েছে!</p></div>';
        }

        if (isset($_POST['add_block_ip'])) {
            $ip_to_block = sanitize_text_field($_POST['ip_to_block'] ?? '');
            if (!empty($ip_to_block)) {
                $blocked = get_option('sobkishu_blocked_ips_arr', array());
                if (!in_array($ip_to_block, $blocked)) {
                    $blocked[] = trim($ip_to_block);
                    update_option('sobkishu_blocked_ips_arr', $blocked);
                    echo '<div class="notice notice-success is-dismissible"><p>🚫 IP <strong>' . esc_html($ip_to_block) . '</strong> ব্লক করা হয়েছে!</p></div>';
                }
            }
        }

        if (isset($_POST['unblock_ip'])) {
            $ip_to_unblock = sanitize_text_field($_POST['unblock_ip'] ?? '');
            $blocked = get_option('sobkishu_blocked_ips_arr', array());
            if (($key = array_search($ip_to_unblock, $blocked)) !== false) {
                unset($blocked[$key]);
                update_option('sobkishu_blocked_ips_arr', array_values($blocked));
                echo '<div class="notice notice-success is-dismissible"><p>🔓 IP <strong>' . esc_html($ip_to_unblock) . '</strong> আনব্লক করা হয়েছে!</p></div>';
            }
        }

        $header_title          = get_option('sobkishu_header_title', '✂️ প্রিমিয়াম হেয়ার এক্সটেনশন – সরাসরি কারখানা থেকে!');
        $header_bg             = get_option('sobkishu_header_bg_color', '#D4A5A5');
        $logo_url              = get_option('sobkishu_site_logo', '');
        $banner_urls           = get_option('sobkishu_banner_slider_urls', '');
        $inside_dhaka          = get_option('sobkishu_inside_dhaka_charge', '60');
        $outside_dhaka         = get_option('sobkishu_outside_dhaka_charge', '120');

        $enable_free_notice    = get_option('sobkishu_enable_free_delivery_notice', 'no');
        $free_notice_text      = get_option('sobkishu_free_delivery_notice_text', 'আজকের জন্য শুধু ডেলিভারি চার্জ সম্পূর্ণ ফ্রি');
        $order_btn_animation   = get_option('sobkishu_order_btn_animation', 'yes');
        $order_btn_color       = get_option('sobkishu_order_btn_color', '#e53935');

        $enable_reviews        = get_option('sobkishu_enable_reviews', 'yes');
        $saved_screenshots     = get_option('sobkishu_customer_review_screenshots', array());
        $offer_title           = get_option('sobkishu_offer_title', '🔥 আজকের বিশেষ অফার!');
        $offer_sub             = get_option('sobkishu_offer_subtitle', 'অর্ডার করলে ফ্রি ডেলিভারি!');
        $tg_token              = get_option('sobkishu_telegram_bot_token', '');
        $tg_chat_id            = get_option('sobkishu_telegram_chat_id', '');
        $phone_no              = get_option('herbal_phone_number', '01846898657');
        $whatsapp_no           = get_option('herbal_whatsapp_number', '8801846898657');
        $messenger_url         = get_option('herbal_messenger_link', 'https://m.me/');
        $blocked_arr           = get_option('sobkishu_blocked_ips_arr', array());
        ?>
        <div class="wrap">
            <h2>⚙️ Hair Extensions BD - সেটিংস প্যানেল</h2>
            
            <form method="POST" action="" style="background: #fff; padding: 25px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); max-width: 800px; margin-bottom: 25px;">
                
                <h3 style="color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px;">🚚 ডেলিভারি চার্জ & অফার সেটিংস</h3>
                <div style="display: flex; gap: 15px; margin-bottom: 15px; flex-wrap: wrap;">
                    <div style="flex: 1; min-width: 200px;">
                        <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">ঢাকার ভেতরে (৳):</label>
                        <input type="number" name="sobkishu_inside_dhaka_charge" value="<?php echo esc_attr($inside_dhaka); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                    </div>
                    <div style="flex: 1; min-width: 200px;">
                        <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">ঢাকার বাইরে (৳):</label>
                        <input type="number" name="sobkishu_outside_dhaka_charge" value="<?php echo esc_attr($outside_dhaka); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                    </div>
                </div>

                <div style="margin-bottom: 15px; background: #f8fafc; padding: 12px; border-radius: 8px; border: 1px solid #cbd5e1;">
                    <label style="font-weight: 700; color: #0f172a; display: block; margin-bottom: 6px;">চেকআউট পেজে 'ফ্রি ডেলিভারি নোটিশ' দেখাবেন?</label>
                    <select name="sobkishu_enable_free_delivery_notice" style="padding: 8px; border-radius: 6px; border: 1px solid #cbd5e1; font-weight: bold; background: #fff;">
                        <option value="no" <?php selected($enable_free_notice, 'no'); ?>>❌ না (সাধারণ চার্জ দেখাবে)</option>
                        <option value="yes" <?php selected($enable_free_notice, 'yes'); ?>>✅ হ্যাঁ (ফ্রি ডেলিভারি নোটিশ দেখাবে)</option>
                    </select>
                </div>

                <div style="margin-bottom: 20px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">ফ্রি ডেলিভারি নোটিশ টেক্সট:</label>
                    <input type="text" name="sobkishu_free_delivery_notice_text" value="<?php echo esc_attr($free_notice_text); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;" placeholder="যেমন: আজকের জন্য শুধু ডেলিভারি চার্জ সম্পূর্ণ ফ্রি">
                </div>

                <h3 style="color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px; margin-top: 25px;">🔴 অর্ডার বাটন ডিজাইন সেটিংস</h3>
                <div style="display: flex; gap: 15px; margin-bottom: 20px; flex-wrap: wrap;">
                    <div style="flex: 1; min-width: 200px;">
                        <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">বাটন অ্যানিমেশন (নড়াচড়া):</label>
                        <select name="sobkishu_order_btn_animation" style="width: 100%; padding: 9px; border-radius: 6px; border: 1px solid #cbd5e1; font-weight: bold; background: #fff;">
                            <option value="yes" <?php selected($order_btn_animation, 'yes'); ?>>✅ অন (নড়াচড়া করবে)</option>
                            <option value="no" <?php selected($order_btn_animation, 'no'); ?>>❌ অফ (সাধারণ স্থির থাকবে)</option>
                        </select>
                    </div>
                    <div style="flex: 1; min-width: 200px;">
                        <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">বাটনের ব্যাকগ্রাউন্ড কালার:</label>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <input type="color" name="sobkishu_order_btn_color" value="<?php echo esc_attr($order_btn_color); ?>" style="width: 50px; height: 40px; border: none; cursor: pointer;">
                            <input type="text" value="<?php echo esc_attr($order_btn_color); ?>" readonly style="padding: 8px; width: 100px; border: 1px solid #cbd5e1; border-radius: 4px; font-weight: bold;">
                        </div>
                    </div>
                </div>

                <h3 style="color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px; margin-top: 25px;">💬 কাস্টমার রিভিউ</h3>
                <div style="margin-bottom: 15px; background: #f8fafc; padding: 12px; border-radius: 8px; border: 1px solid #cbd5e1;">
                    <label style="font-weight: 700; color: #0f172a; display: block; margin-bottom: 4px;">হোমপেজে রিভিউ দেখাবেন?</label>
                    <select name="sobkishu_enable_reviews" style="padding: 8px; border-radius: 6px; border: 1px solid #cbd5e1; font-weight: bold; background: #fff;">
                        <option value="yes" <?php selected($enable_reviews, 'yes'); ?>>✅ দেখাব</option>
                        <option value="no" <?php selected($enable_reviews, 'no'); ?>>❌ দেখাব না</option>
                    </select>
                </div>

                <div id="review-screenshot-wrap">
                    <?php if(!empty($saved_screenshots)): foreach ($saved_screenshots as $idx => $rev): ?>
                        <div class="single-review-box" style="background: #f8fafc; padding: 15px; border: 1px solid #cbd5e1; border-radius: 8px; margin-bottom: 12px;">
                            <div style="margin-bottom: 8px;">
                                <label style="font-weight: 700; display: block; margin-bottom: 4px;">📷 স্ক্রিনশট ১:</label>
                                <input type="url" name="review_img1[]" value="<?php echo esc_url($rev['img1'] ?? ''); ?>" placeholder="https://..." style="width:100%; padding:8px; border:1px solid #cbd5e1; border-radius:4px; box-sizing:border-box;" required>
                            </div>
                            <div>
                                <label style="font-weight: 700; display: block; margin-bottom: 4px;">📷 স্ক্রিনশট ২ (ঐচ্ছিক):</label>
                                <input type="url" name="review_img2[]" value="<?php echo esc_url($rev['img2'] ?? ''); ?>" placeholder="https://..." style="width:100%; padding:8px; border:1px solid #cbd5e1; border-radius:4px; box-sizing:border-box;">
                            </div>
                        </div>
                    <?php endforeach; else: ?>
                        <div class="single-review-box" style="background: #f8fafc; padding: 15px; border: 1px solid #cbd5e1; border-radius: 8px; margin-bottom: 12px;">
                            <div style="margin-bottom: 8px;">
                                <label style="font-weight: 700; display: block; margin-bottom: 4px;">📷 স্ক্রিনশট ১:</label>
                                <input type="url" name="review_img1[]" placeholder="https://..." style="width:100%; padding:8px; border:1px solid #cbd5e1; border-radius:4px; box-sizing:border-box;">
                            </div>
                            <div>
                                <label style="font-weight: 700; display: block; margin-bottom: 4px;">📷 স্ক্রিনশট ২ (ঐচ্ছিক):</label>
                                <input type="url" name="review_img2[]" placeholder="https://..." style="width:100%; padding:8px; border:1px solid #cbd5e1; border-radius:4px; box-sizing:border-box;">
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
                <button type="button" onclick="addNewScreenshotField()" class="button" style="margin-bottom: 20px; font-weight:bold; background:#f1f5f9;">➕ আরও যোগ করুন</button>

                <h3 style="color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px; margin-top: 25px;">📢 হেডার সেটিংস</h3>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">টপ বার টেক্সট:</label>
                    <input type="text" name="sobkishu_header_title" value="<?php echo esc_attr($header_title); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                </div>
                <div style="margin-bottom: 20px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">টপ বার কালার:</label>
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <input type="color" name="sobkishu_header_bg_color" value="<?php echo esc_attr($header_bg); ?>" style="width: 50px; height: 40px; border: none; cursor: pointer;">
                        <input type="text" value="<?php echo esc_attr($header_bg); ?>" readonly style="padding: 8px; width: 100px; border: 1px solid #cbd5e1; border-radius: 4px; font-weight: bold;">
                    </div>
                </div>

                <h3 style="color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px; margin-top: 25px;">🖼️ লোগো ও ব্যানার</h3>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">লোগো URL:</label>
                    <input type="url" name="sobkishu_site_logo" value="<?php echo esc_url($logo_url); ?>" placeholder="https://..." style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                </div>
                <div style="margin-bottom: 20px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">ব্যানার স্লাইডার (প্রতি লাইনে ১টি):</label>
                    <textarea name="sobkishu_banner_slider_urls" rows="5" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;"><?php echo esc_textarea($banner_urls); ?></textarea>
                </div>

                <h3 style="color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px; margin-top: 25px;">📞 যোগাযোগ</h3>
                <div style="margin-bottom: 12px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">ফোন নম্বর:</label>
                    <input type="text" name="herbal_phone_number" value="<?php echo esc_attr($phone_no); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                </div>
                <div style="margin-bottom: 12px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">হোয়াটসঅ্যাপ:</label>
                    <input type="text" name="herbal_whatsapp_number" value="<?php echo esc_attr($whatsapp_no); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                </div>
                <div style="margin-bottom: 20px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">মেসেঞ্জার লিংক:</label>
                    <input type="url" name="herbal_messenger_link" value="<?php echo esc_url($messenger_url); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                </div>

                <h3 style="color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px; margin-top: 25px;">🔥 অফার বক্স</h3>
                <div style="margin-bottom: 12px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">অফার টাইটেল:</label>
                    <input type="text" name="sobkishu_offer_title" value="<?php echo esc_attr($offer_title); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                </div>
                <div style="margin-bottom: 20px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">অফার সাবটাইটেল:</label>
                    <input type="text" name="sobkishu_offer_subtitle" value="<?php echo esc_attr($offer_sub); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                </div>

                <h3 style="color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px; margin-top: 25px;">✉️ টেলিগ্রাম API</h3>
                <div style="margin-bottom: 12px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">Bot Token:</label>
                    <input type="text" name="sobkishu_telegram_bot_token" value="<?php echo esc_attr($tg_token); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                </div>
                <div style="margin-bottom: 25px;">
                    <label style="display: block; font-weight: 700; color: #334155; margin-bottom: 6px;">Chat ID:</label>
                    <input type="text" name="sobkishu_telegram_chat_id" value="<?php echo esc_attr($tg_chat_id); ?>" style="width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px;">
                </div>

                <button type="submit" name="save_herbal_settings" class="button button-primary button-large" style="padding: 6px 25px; font-size: 15px; font-weight: bold; border-radius: 6px;">💾 সেটিংস সেভ করুন</button>
            </form>

            <div style="background: #fff; padding: 25px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); max-width: 800px;">
                <h3 style="color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px; margin-top: 0;">🚫 IP ব্লক ম্যানেজার</h3>
                
                <form method="POST" action="" style="display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap;">
                    <input type="text" name="ip_to_block" placeholder="IP ঠিকানা (যেমন: 103.120.4.5)" required style="flex: 1; padding: 8px 12px; border: 1px solid #cbd5e1; border-radius: 6px; min-width: 200px;">
                    <button type="submit" name="add_block_ip" class="button" style="background: #ef4444; color: #fff; border: none; font-weight: bold; cursor: pointer; padding: 8px 20px; border-radius: 6px;">🚫 ব্লক করুন</button>
                </form>

                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr><th>ব্লক করা IP</th><th style="width: 130px; text-align: right;">অ্যাকশন</th></tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($blocked_arr)): foreach ($blocked_arr as $b_ip): ?>
                            <tr>
                                <td><strong><code><?php echo esc_html($b_ip); ?></code></strong></td>
                                <td style="text-align: right;">
                                    <form method="POST" action="" style="display: inline;">
                                        <input type="hidden" name="unblock_ip" value="<?php echo esc_attr($b_ip); ?>">
                                        <button type="submit" class="button button-small" style="background: #10b981; color: #fff; border: none; font-weight: bold; cursor: pointer; padding: 4px 12px; border-radius: 4px;">🔓 আনব্লক</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="2" style="text-align: center; color: #94a3b8;">কোনো IP ব্লক করা নেই</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <script>
        function addNewScreenshotField() {
            var wrap = document.getElementById('review-screenshot-wrap');
            var html = '<div class="single-review-box" style="background: #f8fafc; padding: 15px; border: 1px solid #cbd5e1; border-radius: 8px; margin-bottom: 12px;">' +
                '<div style="margin-bottom: 8px;">' +
                    '<label style="font-weight: 700; display: block; margin-bottom: 4px;">📷 স্ক্রিনশট ১:</label>' +
                    '<input type="url" name="review_img1[]" placeholder="https://..." style="width:100%; padding:8px; border:1px solid #cbd5e1; border-radius:4px; box-sizing:border-box;" required>' +
                '</div>' +
                '<div>' +
                    '<label style="font-weight: 700; display: block; margin-bottom: 4px;">📷 স্ক্রিনশট ২ (ঐচ্ছিক):</label>' +
                    '<input type="url" name="review_img2[]" placeholder="https://..." style="width:100%; padding:8px; border:1px solid #cbd5e1; border-radius:4px; box-sizing:border-box;">' +
                '</div>' +
            '</div>';
            wrap.insertAdjacentHTML('beforeend', html);
        }
        </script>
        <?php
    }
}

// =============================================
// ✅ 11. IP BLOCK CHECK SYSTEM
// =============================================
add_action('init', function() {
    $user_ip = $_SERVER['REMOTE_ADDR'] ?? '';
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $user_ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $user_ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    }

    $blocked_arr = get_option('sobkishu_blocked_ips_arr', array());
    if (!empty($user_ip) && in_array(trim($user_ip), $blocked_arr)) {
        wp_die('<div style="text-align:center; padding:50px; font-family:sans-serif;">
                <h1 style="color:#ef4444;">🚫 অ্যাক্সেস স্থগিত!</h1>
                <p>আপনার IP ঠিকানা থেকে ওয়েবসাইটের সার্ভিস ব্যবহারের অনুমতি দেওয়া হচ্ছে না।</p>
              </div>', 'অ্যাক্সেস বন্ধ', array('response' => 403));
    }
});

// =============================================
// ✅ 12. HD IMAGE QUALITY
// =============================================
add_filter('jpeg_quality', function() { return 100; });

// =============================================
// ✅ 13. PIXEL TRACKING
// =============================================
if (!function_exists('herbal_facebook_pixel_event')) {
    function herbal_facebook_pixel_event($event_name, $params = array(), $event_id = '') {
        $pixel_id = get_option('herbal_fb_pixel_id', '');
        $access_token = get_option('herbal_fb_access_token', '');
        if (empty($pixel_id) || empty($access_token)) return false;
        
        $user_ip = $_SERVER['REMOTE_ADDR'] ?? '';
        if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $user_ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        }

        $user_data = array(
            'client_ip_address' => $user_ip,
            'client_user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'fbp' => $_COOKIE['_fbp'] ?? '',
            'fbc' => $_COOKIE['_fbc'] ?? ''
        );

        $event_data = array(
            'event_name' => $event_name,
            'event_time' => time(),
            'user_data'  => $user_data,
            'custom_data'=> $params
        );

        if (!empty($event_id)) {
            $event_data['event_id'] = $event_id;
        }

        $payload = array(
            'data' => array($event_data),
            'access_token' => $access_token
        );
        
        $url = "https://graph.facebook.com/v18.0/{$pixel_id}/events";
        $response = wp_remote_post($url, array(
            'headers' => array('Content-Type' => 'application/json'),
            'body'    => json_encode($payload),
            'timeout' => 5
        ));
        return !is_wp_error($response);
    }
}

if (!function_exists('herbal_tiktok_pixel_event')) {
    function herbal_tiktok_pixel_event($event_name, $params = array(), $event_id = '') {
        $pixel_code = get_option('herbal_tiktok_pixel_code', '');
        $access_token = get_option('herbal_tiktok_access_token', '');
        if (empty($pixel_code) || empty($access_token)) return false;
        
        $user_ip = $_SERVER['REMOTE_ADDR'] ?? '';
        if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $user_ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        }

        $event_data = array(
            'event_name' => $event_name,
            'event_time' => time(),
            'user' => array(
                'ip'         => $user_ip,
                'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
            ),
            'properties' => $params
        );

        if (!empty($event_id)) {
            $event_data['event_id'] = $event_id;
        }

        $payload = array(
            'pixel_code' => $pixel_code,
            'event'      => $event_data
        );
        
        $url = "https://business-api.tiktok.com/open_api/v1.3/pixel/track/";
        $response = wp_remote_post($url, array(
            'headers' => array(
                'Content-Type' => 'application/json',
                'Access-Token' => $access_token
            ),
            'body'    => json_encode($payload),
            'timeout' => 5
        ));
        return !is_wp_error($response);
    }
}

if (!function_exists('herbal_track_order_pixels')) {
    function herbal_track_order_pixels($order_id, $order_data) {
        $event_id = 'order_' . $order_id;
        
        if (function_exists('herbal_facebook_pixel_event')) {
            herbal_facebook_pixel_event('Purchase', array(
                'currency'     => 'BDT',
                'value'        => $order_data['total'] ?? 0,
                'order_id'     => $order_id,
                'content_type' => 'product',
                'content_ids'  => array(strval($order_data['product_id'] ?? 0))
            ), $event_id);
        }
        if (function_exists('herbal_tiktok_pixel_event')) {
            herbal_tiktok_pixel_event('PlaceOrder', array(
                'currency'   => 'BDT',
                'value'      => $order_data['total'] ?? 0,
                'order_id'   => $order_id,
                'content_id' => strval($order_data['product_id'] ?? 0)
            ), $event_id);
        }
    }
    add_action('herbal_order_confirmed', 'herbal_track_order_pixels', 10, 2);
}

// =============================================
// ✅ 14. LIVE VISITOR TRACKING PING
// =============================================
if (!function_exists('herbal_track_live_ping_callback')) {
    function herbal_track_live_ping_callback() {
        global $wpdb;
        $table_live = $wpdb->prefix . 'herbal_live_visitors';

        $page_url   = esc_url_raw($_POST['page_url'] ?? '');
        $page_title = sanitize_text_field($_POST['page_title'] ?? '');
        $session_id = sanitize_text_field($_POST['session_id'] ?? '');

        if (empty($session_id) || empty($page_url)) {
            wp_send_json_error();
            return;
        }

        $page_title = trim(str_replace(array('My Blog', 'Page not found | '), '', $page_title), ' |-');
        if (empty($page_title)) {
            $page_title = 'Hair Extensions BD';
        }

        $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
        if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        }

        $is_checkout = (strpos($page_url, 'checkout') !== false) ? 1 : 0;

        $existing = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_live WHERE session_id = %s", $session_id));

        if ($existing) {
            $wpdb->update(
                $table_live,
                array(
                    'page_title'  => $page_title,
                    'page_url'    => $page_url,
                    'time_spent'  => intval($existing->time_spent) + 10,
                    'last_active' => current_time('mysql'),
                    'is_checkout' => $is_checkout
                ),
                array('session_id' => $session_id)
            );
        } else {
            $wpdb->insert(
                $table_live,
                array(
                    'session_id'  => $session_id,
                    'ip_address'  => $ip,
                    'country'     => 'Bangladesh',
                    'city'        => 'Dhaka',
                    'page_title'  => $page_title,
                    'page_url'    => $page_url,
                    'time_spent'  => 10,
                    'last_active' => current_time('mysql'),
                    'is_checkout' => $is_checkout
                )
            );
        }

        wp_send_json_success();
    }
    add_action('wp_ajax_herbal_track_live_ping', 'herbal_track_live_ping_callback');
    add_action('wp_ajax_nopriv_herbal_track_live_ping', 'herbal_track_live_ping_callback');
}

add_action('wp_footer', function() {
    if (is_admin()) return;
    ?>
    <script>
    (function() {
        let sessId = localStorage.getItem('sk_sess_id');
        if (!sessId) {
            sessId = 'sk_' + Math.random().toString(36).substring(2, 11) + '_' + Date.now();
            localStorage.setItem('sk_sess_id', sessId);
        }

        function sendPing() {
            let pTitle = document.title || '';
            pTitle = pTitle.replace(/My Blog/g, 'Hair Extensions BD').replace(/Page not found \| /g, '');

            let formData = new FormData();
            formData.append('action', 'herbal_track_live_ping');
            formData.append('page_url', window.location.href);
            formData.append('page_title', pTitle);
            formData.append('session_id', sessId);

            fetch("<?php echo admin_url('admin-ajax.php'); ?>", {
                method: 'POST',
                body: formData
            }).catch(function() {});
        }

        sendPing();
        setInterval(sendPing, 10000);
    })();
    </script>
    <?php
});