403Webshell
Server IP : 65.108.144.40  /  Your IP : 216.73.217.165
Web Server : Apache/2.4.52 (Ubuntu)
System : Linux ubuntu-8gb-hel1-1 5.15.0-173-generic #183-Ubuntu SMP Fri Mar 6 13:29:34 UTC 2026 x86_64
User : dev ( 1000)
PHP Version : 8.2.30
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/capital-catering/web/app/themes/capital-catering/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/capital-catering/web/app/themes/capital-catering/functions.php
<?php

function init_wc_session() {
    if (WC()->session && !WC()->session->has_session()) {
        WC()->session->init();
        WC()->session->set_customer_session_cookie(true);
    }
}

add_action('init', 'init_wc_session', 1);

if (!isset($content_width)) {
    $content_width = 800;
}
if (!function_exists('theme_setup')) :

    function theme_setup() {
        /**
         * Make theme available for translation.
         * Translations can be placed in the /languages/ directory.
         */
        load_theme_textdomain('customtheme', get_template_directory() . '/languages');

        /* Add default posts and comments RSS feed links to <head>. */
        add_theme_support('automatic-feed-links');

        /* Enable support for post thumbnails and featured images. */
        add_theme_support('post-thumbnails');

        /* Add support for two custom navigation menus. */
        register_nav_menus(array(
            'header_menu' => __('Header Menu'),
            'quick_links' => __('Quick Links'),
            'mobile_menu' => __('Mobile Menu'),
            'mega-menu' => __('Mega Menu'),
        ));

        /**
         * Enable support for the following post formats:
         * aside, gallery, quote, image, and video
         */
        add_theme_support('post-formats', array('aside', 'gallery', 'quote', 'image', 'video'));
        add_filter('disable_wpseo_json_ld_search', '__return_true');
        //add_filter('use_block_editor_for_post', '__return_false');
        // Add Thumbnail Support
        add_theme_support('post-thumbnails');
    }

endif; // theme_setup
add_action('after_setup_theme', 'theme_setup');

require_once get_template_directory() . '/inc/class-walker-mega-menu.php';
require_once get_template_directory() . '/inc/mega-menu-function.php';
require_once get_template_directory() . '/custom-functions.php';

get_template_part('/inc/functions/enqueue', 'scripts');
get_template_part('/inc/functions/post', 'type');
get_template_part('/inc/functions/grouped', 'products');
get_template_part('/inc/functions/grouped', 'products-new');
get_template_part('/inc/functions/form', 'codes');
get_template_part('/inc/functions/account', 'report');
get_template_part('/inc/functions/shipping', 'codes');
get_template_part('/inc/functions/shipping', 'address');

// Removed Script Attribute
add_filter('style_loader_tag', 'codeless_remove_type_attr', 10, 2);
add_filter('script_loader_tag', 'codeless_remove_type_attr', 10, 2);

function codeless_remove_type_attr($tag, $handle) {
    return preg_replace("/type=['\"]text\/(javascript|css)['\"]/", '', $tag);
}

// REMOVE WP EMOJI
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');

/* new theme options for header and footer */
if (function_exists('acf_add_options_page')) {
    acf_add_options_page(array(
        'page_title' => 'Theme General Settings',
        'menu_title' => 'Theme Settings',
        'menu_slug' => 'theme-general-settings',
        'capability' => 'edit_posts',
        'redirect' => false
    ));
}

/* * **********Ipad Function************* */
add_filter('wp_is_mobile', 'mobile_edits');

function mobile_edits() {
    static $is_mobile;

    if (isset($is_mobile))
        return $is_mobile;

    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $is_mobile = false;
    } elseif (
            strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
    ) {
        $is_mobile = true;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') == false) {
        $is_mobile = true;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') !== false) {
        $is_mobile = false;
    } else {
        $is_mobile = false;
    }
    return $is_mobile;
}

add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);

/**
 * Replace # with js
 * @param string $menu_item item HTML
 * @return string item HTML
 */
function wpse_226884_replace_hash($menu_item) {
    if (strpos($menu_item, 'href="#"') !== false) {
        $menu_item = str_replace('href="#"', 'href="javascript:void(0);"', $menu_item);
    }
    return $menu_item;
}

/*  Disable the Schema - Yoast */

function disable_yoast_schema_data($data) {
    $data = array();
    return $data;
}

add_filter('wpseo_json_ld_output', 'disable_yoast_schema_data', 10, 1);
// Remove the second home if it exists
add_filter('wpseo_breadcrumb_links', 'remove_duplicate_home');

function remove_duplicate_home($links) {
    if (isset($links[1]) && $links[1]['text'] === 'Home') {
        unset($links[1]);
    }
    return array_values($links);
}

/* SVG Upload Code */

function cc_mime_types($mimes) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}

add_filter('upload_mimes', 'cc_mime_types');

/* Remove Default P tag in Contact Form 7 */
add_filter('wpcf7_autop_or_not', '__return_false');

// Add Meta Box for Custom Fields
function custom_product_dates_meta_box() {
    add_meta_box(
            'custom_product_dates',
            'Disable Product',
            'custom_product_dates_callback',
            'product',
            'normal',
            'high'
    );
}

add_action('add_meta_boxes', 'custom_product_dates_meta_box');

// Callback Function to Display Fields
function custom_product_dates_callback($post) {
    $dates = get_post_meta($post->ID, '_custom_product_dates', true);

    wp_nonce_field('save_custom_product_dates', 'custom_product_dates_nonce');
    ?>
    <div id="custom_product_dates_wrapper">
        <table id="custom_product_dates_repeater">
            <tr>
                <th>Message</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>Action</th>
            </tr>
            <?php
            if (!empty($dates)) {
                foreach ($dates as $key => $date_entry) {
                    ?>
                    <tr>
                        <td><input type="text" name="custom_product_dates[<?php echo $key; ?>][message]" value="<?php echo esc_attr($date_entry['message']); ?>" /></td>
                        <td><input type="date" name="custom_product_dates[<?php echo $key; ?>][inactive_date]" value="<?php echo esc_attr($date_entry['inactive_date']); ?>" /></td>
                        <td><input type="date" name="custom_product_dates[<?php echo $key; ?>][active_date]" value="<?php echo esc_attr($date_entry['active_date']); ?>" /></td>
                        <td><button type="button" class="remove_date_row">Remove</button></td>
                    </tr>
                    <?php
                }
            }
            ?>
        </table>
        <button type="button" class="button add_date_row">+ Add Date</button>
    </div>


    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const wrapper = document.getElementById("custom_product_dates_repeater");
            const addButton = document.querySelector(".add_date_row");

            addButton.addEventListener("click", function () {
                let index = wrapper.children.length;
                let row = document.createElement("tr");
                row.innerHTML = `
                    <td><input type="text" name="custom_product_dates[${index}][message]" /></td>
                    <td><input type="date" name="custom_product_dates[${index}][inactive_date]" /></td>
                    <td><input type="date" name="custom_product_dates[${index}][active_date]" /></td>
                    <td><button type="button" class="remove_date_row">Remove</button></td>
                `;
                wrapper.appendChild(row);
            });

            wrapper.addEventListener("click", function (e) {
                if (e.target.classList.contains("remove_date_row")) {
                    e.target.parentElement.parentElement.remove();
                }
            });
        });
    </script>
    <?php
}

// Save Custom Fields Data
function save_custom_product_dates($post_id) {
    if (!isset($_POST['custom_product_dates_nonce']) || !wp_verify_nonce($_POST['custom_product_dates_nonce'], 'save_custom_product_dates')) {
        return;
    }

    if (isset($_POST['custom_product_dates']) && !empty($_POST['custom_product_dates'])) {
        update_post_meta($post_id, '_custom_product_dates', $_POST['custom_product_dates']);
    } else {
        delete_post_meta($post_id, '_custom_product_dates'); // Delete if empty
    }
}

add_action('save_post_product', 'save_custom_product_dates');

// Add "Inactive" Class to Products Based on Date
function add_inactive_class_to_shop_products($classes, $product) {
    $product_id = $product->get_id();
    $dates = get_post_meta($product_id, '_custom_product_dates', true);
    $current_time = WC()->session->get('selected_order_date');
    $current_time = strtotime($current_time);
    if (!empty($dates)) {
        foreach ($dates as $date_entry) {
            $inactive_date = isset($date_entry['inactive_date']) ? strtotime($date_entry['inactive_date'] . ' 00:01:00') : 0;
            $active_date = isset($date_entry['active_date']) ? strtotime($date_entry['active_date'] . ' 00:01:00 +1 day') : 0;

            if ($inactive_date && $active_date) {
                if ($current_time >= $inactive_date && $current_time < $active_date) {
                    $classes[] = 'product-inactive'; // Add inactive class
                    break;
                }
            }
        }
    }
    return $classes;
}

add_filter('woocommerce_post_class', 'add_inactive_class_to_shop_products', 10, 2);



/* * ************************ */
// Enqueue Flatpickr on WooCommerce Product Pages
function enqueue_flatpickr_scripts() {
    if (is_product()) { // Only load on product pages
        wp_enqueue_style('flatpickr-css', 'https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css');
        wp_enqueue_script('flatpickr-js', 'https://cdn.jsdelivr.net/npm/flatpickr', array('jquery'), '', true);
    }
}

add_action('wp_enqueue_scripts', 'enqueue_flatpickr_scripts');

function enqueue_ajax_script() {
    wp_localize_script('your-script-handle', 'ajax_object', array('ajaxurl' => admin_url('admin-ajax.php')));
}

add_action('wp_enqueue_scripts', 'enqueue_ajax_script');

// Store Selected Date & Time in WooCommerce Session
function store_selected_date() {
    if (!isset($_POST['order_date'])) {
        wp_send_json_error(['message' => 'No order date received']);
    }

    $selected_date = sanitize_text_field($_POST['order_date']);

    // Store the selected date in session
    WC()->session->set('selected_order_date', $selected_date);
    WC()->session->set('buffet_style', 'Golden setup');

    // Check if session variable is actually set
    wp_send_json_success([
        'message' => 'Order date stored successfully',
        'selected_date' => WC()->session->get('selected_order_date') // Ensure it returns correctly
    ]);
}

add_action('wp_ajax_store_selected_date', 'store_selected_date');
add_action('wp_ajax_nopriv_store_selected_date', 'store_selected_date');

add_action('wp_ajax_store_selected_cartmeta', 'store_selected_cartmeta');
add_action('wp_ajax_nopriv_store_selected_cartmeta', 'store_selected_cartmeta');

function store_selected_cartmeta() {

    $key   = sanitize_key($_POST['service_key'] ?? '');
    $value = sanitize_text_field($_POST['service_value'] ?? '');
    $image = esc_url_raw($_POST['service_image'] ?? '');

    if (!$key || !$value) {
        wp_send_json_error(['message' => 'Missing service key or value']);
    }

    // Loop through cart to find and update included_options
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        if (!empty($cart_item['included_options']) && is_array($cart_item['included_options'])) {
            foreach ($cart_item['included_options'] as $index => $option) {
                // Match by serviceKey
                if (isset($option['serviceKey']) && $option['serviceKey'] === $key) {
                    WC()->cart->cart_contents[$cart_item_key]['included_options'][$index]['value'] = $value;

                    // Optionally, also store image if you want to display it later
                    WC()->cart->cart_contents[$cart_item_key]['included_options'][$index]['image'] = $image;
                }
            }
        }
    }

    // Save cart
    WC()->cart->set_session();

    wp_send_json_success([
        'message' => 'Service updated in cart',
        'stored'  => WC()->session->get("selected_service_{$key}")
    ]);
}

function store_selected_time() {
    if (!isset($_POST['order_time'])) {
        wp_send_json_error(['message' => 'No order time received']);
    }

    $selected_time = sanitize_text_field($_POST['order_time']);

    // Store the selected date in session
    WC()->session->set('selected_order_time', $selected_time);
// console.log(localStorage.getItem('selected_order_time'));
    // Check if session variable is actually set
    wp_send_json_success([
        'message' => 'Order time stored successfully',
        'selected_time' => WC()->session->get('selected_order_time') // Ensure it returns correctly
    ]);
}

add_action('wp_ajax_store_selected_time', 'store_selected_time');
add_action('wp_ajax_nopriv_store_selected_time', 'store_selected_time');

function preserve_order_date_in_cart($cart_item, $cart_item_key) {
    if (isset($cart_item['order_date'])) {
        $cart_item['order_date'] = $cart_item['order_date'];
    }
    return $cart_item;
}

add_filter('woocommerce_get_cart_item_from_session', 'preserve_order_date_in_cart', 10, 2);

// Save Order Date in Cart Item Meta
function save_order_date_to_cart($cart_item_data, $product_id, $variation_id) {
    $order_date = WC()->session->get('selected_order_date');
    $order_time = WC()->session->get('selected_order_time');
    if ($order_date) {
        $cart_item_data['order_date'] = $order_date;
    }
    if ($order_time) {
        $cart_item_data['order_time'] = $order_time;
    }
    return $cart_item_data;
}

add_filter('woocommerce_add_cart_item_data', 'save_order_date_to_cart', 10, 3);

// Display Order Date in Cart
function display_order_date_cart($item_data, $cart_item) {
    if (isset($cart_item['order_date'])) {
        $item_data[] = array(
            'name' => 'Order Date & Time',
            'value' => esc_html($cart_item['order_date'] . ' ' . $cart_item['order_time'])
        );
    }
    return $item_data;
}

add_filter('woocommerce_get_item_data', 'display_order_date_cart', 10, 2);

// Show Order Date on Checkout Page
function display_order_date_checkout() {
    $order_date = WC()->session->get('selected_order_date');
    if ($order_date) {
        echo '<p><strong>Selected Order Date:</strong> ' . esc_html($order_date) . '</p>';
    }
}

add_action('woocommerce_review_order_before_payment', 'display_order_date_checkout');

// Save Order Date and Time in Order Meta
function save_order_date_meta($order_id) {
    $cart = WC()->cart->get_cart();

    foreach ( $cart as $cart_item_key => $cart_item ) {
         // Save order date and time from cart item meta to order meta
        if ( isset( $cart_item['order_date'] ) ) {
            update_post_meta( $order_id, '_selected_order_date', $cart_item['order_date'] );
        }
        if ( isset( $cart_item['order_time'] ) ) {
            update_post_meta( $order_id, '_selected_order_time', $cart_item['order_time'] );
        }
    }
}

add_action('woocommerce_checkout_update_order_meta', 'save_order_date_meta', 9);

// Validate Order Date and Time Based on Menu Type
function validate_order_date_time() {
    // Check cart items to determine menu type
    $cart = WC()->cart->get_cart();
    $has_package_menu = false;
    $has_itemized_menu = false;
    
    // Package menu product IDs (from the checkout form)
    $package_menu_products = array(463);
    
    $order_date = $order_time = '';
    foreach ($cart as $cart_item_key => $cart_item) {
        $product_id = $cart_item['product_id'];
        
        if (in_array($product_id, $package_menu_products)) {
            $has_package_menu = true;
        } else {
            $has_itemized_menu = true;
        }
        $order_date = $cart_item['order_date'];
        $order_time = $cart_item['order_time'];
    }
    
    if (empty($order_date) || empty($order_time)) {
        wp_send_json_error(['message' => 'Please select both order date and time. You will be redirected shortly. Please create new order.']);
    }
    
    // Parse the ISO 8601 date format (2025-09-12T00:00)
    $date_obj = new DateTime($order_date);
    
    // Parse the 12-hour time format with AM/PM (01:00 PM)
    $time_obj = DateTime::createFromFormat('h:i A', $order_time);
    
    if ($date_obj && $time_obj) {
        // Combine date and time
        $date_obj->setTime($time_obj->format('H'), $time_obj->format('i'));
        $order_timestamp = $date_obj->getTimestamp();
        $current_timestamp = current_time('timestamp');
    } else {
        wp_send_json_error(['message' => 'Invalid date or time format. You will be redirected shortly. Please create new order.']);
    }

    // Calculate time difference in hours
    $time_diff_hours = ($order_timestamp - $current_timestamp) / 3600;
    
    // Validate based on menu type
    if ($has_package_menu) {
        // Package menu: 72 hours validation
        if ($time_diff_hours < 72) {
            wp_send_json_error(['message' => 'Package menu order is not allowed within 72hrs. You will be redirected shortly. Please create new order.']);
        }
    } elseif ($has_itemized_menu) {
        // Itemized menu: 24 hours validation
        if ($time_diff_hours < 24) {
            wp_send_json_error(['message' => 'Itemized menu order is not allowed within 24hrs. You will be redirected shortly. Please create new order.']);
        }
    }
    
    // If validation passes
    wp_send_json_success(['message' => 'Order date and time are valid.']);
}

// Add AJAX handler for order date validation
add_action('wp_ajax_validate_order_date_time', 'validate_order_date_time');
add_action('wp_ajax_nopriv_validate_order_date_time', 'validate_order_date_time');

/* * *************** */

function enqueue_custom_scripts() {
    wp_enqueue_script('jquery-ui-tabs');
}

add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');

function enqueue_remove_category_script() {
    if (is_cart()) {
        wp_enqueue_script('remove-category-script', get_template_directory_uri() . '/assets/js/remove-category.js', array('jquery'), null, true);

        wp_localize_script('remove-category-script', 'cart_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
        ));
    }
}

add_action('wp_enqueue_scripts', 'enqueue_remove_category_script');

function remove_category_from_cart() {
    if (!isset($_POST['category_name'], $_POST['order_date'])) {
        wp_send_json_error(['message' => 'Invalid request - Missing category or order date']);
    }

    $category_name = sanitize_text_field($_POST['category_name']);
    $order_date = sanitize_text_field($_POST['order_date']);

    error_log("Received AJAX: Category: $category_name, Order Date: $order_date");

    if (empty($category_name) || empty($order_date)) {
        wp_send_json_error(['message' => 'Invalid request - Empty category or order date']);
    }

    // Normalize order date format for comparison
    $order_date_obj = DateTime::createFromFormat('d/m/Y', $order_date);
    if ($order_date_obj) {
        $order_date = $order_date_obj->format('d/m/Y'); // Ensure it's in d/m/Y format
    }

    $items_removed = false; // Track if any items were removed

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $product_id = $cart_item['product_id'];
        $cart_order_date = isset($cart_item['order_date']) ? $cart_item['order_date'] : '';

        // Convert cart order date to d/m/Y
        if (!empty($cart_order_date)) {
            $cart_date_obj = DateTime::createFromFormat('Y-m-d\TH:i', $cart_order_date);
            if ($cart_date_obj) {
                $cart_order_date = $cart_date_obj->format('d/m/Y');
            }
        }

        $terms = get_the_terms($product_id, 'product_cat');
        if (!$terms || is_wp_error($terms))
            continue;

        foreach ($terms as $term) {
            if ($term->name === $category_name && $cart_order_date === $order_date) {
                WC()->cart->remove_cart_item($cart_item_key);
                $items_removed = true;
            }
        }
    }

    if ($items_removed) {
        WC()->cart->calculate_totals();
        wp_send_json_success(['message' => 'Selected items have been removed.']);
    } else {
        wp_send_json_error(['message' => 'No items found matching this category and order date.']);
    }
}

add_action('wp_ajax_remove_category_from_cart', 'remove_category_from_cart');
add_action('wp_ajax_nopriv_remove_category_from_cart', 'remove_category_from_cart');

/* Change currency symbol to AED */
add_filter('woocommerce_currency_symbol', 'custom_currency_symbol', 10, 2);

function custom_currency_symbol($currency_symbol, $currency) {
    if ($currency == 'AED') {
        $currency_symbol = 'AED';
    }
    return $currency_symbol;
}

/* Clear cart */
add_action('wp_ajax_clear_cart', 'clear_cart');
add_action('wp_ajax_nopriv_clear_cart', 'clear_cart');

function clear_cart() {
    WC()->cart->empty_cart();
    wp_send_json_success();
}

function update_cart_quantities() {
    if (!isset($_POST['quantities']) || !is_array($_POST['quantities'])) {
        wp_send_json_error(['message' => 'Invalid data']);
    }

    foreach ($_POST['quantities'] as $cart_item_key => $quantity) {
        $quantity = intval($quantity);
        if (isset(WC()->cart->cart_contents[$cart_item_key])) {
            WC()->cart->set_quantity($cart_item_key, $quantity);
        }
    }

    wc()->cart->calculate_totals();
    wp_send_json_success(['message' => 'Cart updated']);
}

add_action('wp_ajax_update_cart_quantities', 'update_cart_quantities');
add_action('wp_ajax_nopriv_update_cart_quantities', 'update_cart_quantities');

/* * *** Duplicate in Cart **** */
add_action('wp_ajax_duplicate_full_cart_group', 'duplicate_full_cart_group');
add_action('wp_ajax_nopriv_duplicate_full_cart_group', 'duplicate_full_cart_group');

function duplicate_full_cart_group() {
    if (!isset($_POST['category'], $_POST['order_date'], $_POST['products'])) {
        wp_send_json_error(['message' => 'Invalid data.']);
    }

    $category = sanitize_text_field($_POST['category']);
    $new_order_date = sanitize_text_field($_POST['order_date']);
    $delivery_method = sanitize_text_field($_POST['delivery_method']);
    $products = json_decode(stripslashes($_POST['products']), true);
    WC()->session->set('selected_order_date', $new_order_date);
    if (!$products) {
        wp_send_json_error(['message' => 'Invalid products data.']);
    }
    foreach ($products as $product) {
        $product_id = $product['product']['id']; // Get ID via SKU
        $quantity = intval($product['quantity']);

        if ($product_id) {
            // Ensure order date is set dynamically
            $cart_item_key = WC()->cart->add_to_cart(
                    $product_id,
                    $quantity,
                    0,
                    [],
                    [
                        'order_date' => $new_order_date,
                        'delivery_method' => $delivery_method,
                    ]
            );

            if (!$cart_item_key) {
                wp_send_json_error(['message' => 'Failed to add product to cart.']);
            }
        }
    }

    wp_send_json_success(['message' => 'Category group duplicated successfully.']);
}

/* * ************* */
add_action('woocommerce_review_order_before_submit', function () {
    $delivery_method = WC()->session->get('selected_delivery_method');
    if ($delivery_method) {
        echo '<p><strong>Delivery Method:</strong> ' . esc_html($delivery_method) . '</p>';
    }
});
add_action('woocommerce_checkout_update_order_meta', function ($order_id) {
    $delivery_method = WC()->session->get('selected_delivery_method');
    if (!empty($delivery_method)) {
        update_post_meta($order_id, '_delivery_method', $delivery_method);
    }
});
add_action('woocommerce_admin_order_data_after_billing_address', function ($order) {
    $delivery_method = get_post_meta($order->get_id(), '_delivery_method', true);
    if ($delivery_method) {
        echo '<p><strong>Delivery Method:</strong> ' . esc_html($delivery_method) . '</p>';
    }
});

function custom_taxonomy_allergens() {
    $labels = array(
        'name' => _x('Allergens', 'taxonomy general name', 'textdomain'),
        'singular_name' => _x('Allergen', 'taxonomy singular name', 'textdomain'),
        'search_items' => __('Search Allergens', 'textdomain'),
        'all_items' => __('All Allergens', 'textdomain'),
        'parent_item' => __('Parent Allergen', 'textdomain'),
        'parent_item_colon' => __('Parent Allergen:', 'textdomain'),
        'edit_item' => __('Edit Allergen', 'textdomain'),
        'update_item' => __('Update Allergen', 'textdomain'),
        'add_new_item' => __('Add New Allergen', 'textdomain'),
        'new_item_name' => __('New Allergen Name', 'textdomain'),
        'menu_name' => __('Allergens', 'textdomain'),
    );

    $args = array(
        'hierarchical' => true, // Set to false if you want tags-like behavior instead of categories
        'labels' => $labels,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'allergen'),
    );

    register_taxonomy('allergens', array('product'), $args);
}

add_action('init', 'custom_taxonomy_allergens');

function custom_ajax_add_all_to_cart() {
    if (!isset($_POST['items'])) {
        wp_send_json_error(['message' => 'No data received']);
    }

    //Clear cart before adding new products
    WC()->cart->empty_cart();

    $items = json_decode(stripslashes($_POST['items']), true);
    $delivery_method = sanitize_text_field($_POST['delivery_method'] ?? '');

    if (empty($items)) {
        wp_send_json_error(['message' => 'Invalid data received']);
    }

    foreach ($items as $item) {
        $product_id = intval($item['product_id'] ?? 0);
        $variation_name = !empty($item['variation_name']) ? $item['variation_name'] : "";

        $quantity = intval($item['quantity'] ?? 0);
        $new_order_date = WC()->session->get('selected_order_date');

        if ($product_id > 0 && $quantity > 0) {
            $custom_data = array();
            if (isset($_POST['included_options']) && !empty($_POST['included_options'])) {
                $custom_data = json_decode(stripslashes($_POST['included_options']), true);
            }
            $rr = WC()->cart->add_to_cart(
                    $product_id,
                    $quantity,
                    0,
                    [],
                    [
                        'order_date' => $new_order_date,
                        'variation_name' => $variation_name,
                        'included_options' => $custom_data
                    ]
            );
        }
    }

    wp_send_json_success(['message' => 'All products added successfully!', 'data' => $rr]);
    wp_die();
}

add_action('wp_ajax_add_all_to_cart', 'custom_ajax_add_all_to_cart');
add_action('wp_ajax_nopriv_add_all_to_cart', 'custom_ajax_add_all_to_cart');

/* * ****Header cart***** */

function update_cart_icon_callback() {
    wp_send_json_success([
        'cart_count' => WC()->cart->get_cart_contents_count(),
        'cart_total' => WC()->cart->get_cart_total()
    ]);
}

add_action('wp_ajax_update_cart_icon', 'update_cart_icon_callback');
add_action('wp_ajax_nopriv_update_cart_icon', 'update_cart_icon_callback');

function enqueue_cart_ajax_script() {
    wp_enqueue_script('cart-ajax', get_template_directory_uri() . '/assets/js/cart-ajax.js', array('jquery'), null, true);

    // Localize script to pass AJAX URL
    wp_localize_script('cart-ajax', 'ajax_obj', array(
        'ajaxurl' => admin_url('admin-ajax.php') // ✅ Provides correct AJAX URL
    ));
}

add_action('wp_enqueue_scripts', 'enqueue_cart_ajax_script');

/* * ********* */
add_action('wp_ajax_woocommerce_update_cart_quantity', 'update_cart_quantity_callback');
add_action('wp_ajax_nopriv_woocommerce_update_cart_quantity', 'update_cart_quantity_callback');

function update_cart_quantity_callback() {
    // check_ajax_referer('woocommerce-cart', 'security');

    $cart_item_key = sanitize_text_field($_POST['cart_item_key']);
    $quantity = intval($_POST['quantity']);

    if (WC()->cart->set_quantity($cart_item_key, $quantity)) {
        WC()->cart->calculate_totals();
        wp_send_json_success([
            'message' => 'Cart updated',
            'cart_total' => WC()->cart->get_cart_total()
        ]);
    } else {
        wp_send_json_error('Failed to update cart');
    }

    wp_die();
}

function enqueue_cart_scripts() {
    if (is_cart() || is_checkout()) {

        // wp_enqueue_style(
        //     'sweetalertkr-css',
        //     get_theme_file_uri('assets/css/sweetalertkr.css'),
        //     array(),
        //     null // or a version number like '1.0.0'
        // );
        wp_enqueue_script('custom-cart', get_template_directory_uri() . '/assets/js/custom-cart.js', array('jquery'), null, true);
        // wp_enqueue_script('sweetalert-js', get_template_directory_uri() . '/assets/js/sweetalert.js', array('jquery'), null, true);
        // // Localize script only if custom-cart.js is enqueued
        wp_localize_script('custom-cart', 'wc_cart_params', [
            'wc_ajax_url' => "/?wc-ajax=%%endpoint%%",
            'ajax_url' => admin_url('admin-ajax.php'),
            'update_cart_nonce' => wp_create_nonce('woocommerce-cart')
        ]);
    }
}

add_action('wp_enqueue_scripts', 'enqueue_cart_scripts');

function ccp_enqueue_cart_tracking_script() {
    $script_path = get_template_directory() . '/assets/js/cart-tracking.js';

    wp_enqueue_script(
        'ccp-cart-tracking',
        get_template_directory_uri() . '/assets/js/cart-tracking.js',
        array('jquery'),
        file_exists($script_path) ? filemtime($script_path) : null,
        true
    );

    // Localize script to pass AJAX URL
    wp_localize_script('ccp-cart-tracking', 'ccp_cart_tracking', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'update_cart_nonce' => wp_create_nonce('woocommerce-cart')
    ]);
}

add_action('wp_enqueue_scripts', 'ccp_enqueue_cart_tracking_script');

// Display cart message textarea on the cart page
function custom_cart_message_field() {
    $cart_message = WC()->session->get('cart_message', '');

    echo '<div class="cart-message-box woocommerce">';

    if (!empty($cart_message)) {
        echo '<p><strong>Your notes</strong><br> ' . esc_html($cart_message) . '</p>';
        echo '<button type="button" class="edit-btn"><img src="https://www.capitalcateringplus.ae/app/uploads/2025/03/Vector-36.svg" alt="edit-notes"> Edit</button>';
    } else {
        echo '<textarea name="cart_message" id="cart_message" class="input-text" rows="3" placeholder="' . esc_attr__('Any special instructions?', 'your-textdomain') . '"></textarea>';
        echo '<button type="button" class="cancle-btn"><img src="https://www.capitalcateringplus.ae/app/uploads/2025/03/Vector-34.svg" alt="Cancel"> Cancel</button>';
        echo '<button type="button" class="save-btn ms-3"><img src="https://www.capitalcateringplus.ae/app/uploads/2025/03/Vector-35.svg" alt="edit-Save"> Save</button>';
    }

    echo '</div>';
}

// Save cart message to session via AJAX
add_action('wp_ajax_update_cart_message', 'update_cart_message');
add_action('wp_ajax_nopriv_update_cart_message', 'update_cart_message');

function update_cart_message() {
    if (isset($_POST['cart_message'])) {
        WC()->session->set('cart_message', sanitize_textarea_field($_POST['cart_message']));
    }
    wp_die();
}

// AJAX handler to get cart data for tracking
add_action('wp_ajax_ccp_get_cart_data', 'ccp_get_cart_data');
add_action('wp_ajax_nopriv_ccp_get_cart_data', 'ccp_get_cart_data');

function ccp_get_cart_data() {
    if (!WC()->cart || WC()->cart->is_empty()) {
        wp_send_json_error(['message' => 'Cart is empty']);
        return;
    }

    $cart_items = [];
    // Get cart total - parse from formatted string
    $formatted_total = WC()->cart->get_total('');
    // Remove HTML tags and currency symbols, then parse
    $cart_total = floatval(strip_tags($formatted_total));
    // If parsing failed, calculate from components
    if ($cart_total <= 0) {
        $cart_total = floatval(WC()->cart->get_cart_contents_total()) + floatval(WC()->cart->get_total_tax());
    }

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $product = $cart_item['data'];
        $product_id = $cart_item['product_id'];
        $variation_id = isset($cart_item['variation_id']) ? $cart_item['variation_id'] : 0;
        
        // Get product name
        $product_name = $product->get_name();
        
        // Get product categories
        $categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'names'));
        $category = !empty($categories) ? $categories[0] : '';
        
        // Get variation name if it's a variable product
        $variant = '';
        if ($variation_id > 0) {
            $variation = wc_get_product($variation_id);
            if ($variation) {
                $variant = $variation->get_name();
            }
        }
        
        // Get price
        $price = floatval($product->get_price());
        
        // Get quantity
        $quantity = intval($cart_item['quantity']);
        
        $cart_items[] = [
            'id' => strval($product_id),
            'name' => $product_name,
            'category' => $category,
            'variant' => $variant,
            'price' => $price,
            'quantity' => $quantity
        ];
    }

    wp_send_json_success([
        'total' => $cart_total,
        'items' => $cart_items
    ]);
}

// Ensure latest cart message appears on checkout page
add_action('woocommerce_after_order_notes', 'display_cart_message_on_checkout');

function display_cart_message_on_checkout() {
    $cart_message = WC()->session->get('cart_message', '');
    if (!empty($cart_message)) {
        echo '<p><strong>' . esc_html__('Order Notes:', 'your-textdomain') . '</strong> ' . esc_html($cart_message) . '</p>';
    }
}

// Save cart message to order meta
add_action('woocommerce_checkout_update_order_meta', 'save_cart_message_to_order');

function save_cart_message_to_order($order_id) {
    $cart_message = WC()->session->get('cart_message');
    if (!empty($cart_message)) {
        update_post_meta($order_id, '_cart_message', $cart_message);
    }
}

// Display order notes in admin panel
add_action('woocommerce_admin_order_data_after_order_details', 'display_cart_message_in_admin');

function display_cart_message_in_admin($order) {
    $cart_message = get_post_meta($order->get_id(), '_cart_message', true);
    if (!empty($cart_message)) {
        echo '<p><strong>' . esc_html__('Order Notes:', 'your-textdomain') . '</strong><br>' . esc_html($cart_message) . '</p>';
    }
}

// Display cart message on order detail page (frontend)
add_action('woocommerce_order_details_after_order_table', 'display_cart_message_on_order_details', 10, 1);

function display_cart_message_on_order_details($order) {
    $cart_message = $order->get_meta('_cart_message');
    if (!empty($cart_message)) {
        echo '<div class="woocommerce-order-overview__notes notes" >';
        echo '<h3>' . esc_html__('Your Notes', 'your-textdomain') . '</h3>';
        echo '<p>' . esc_html($cart_message) . '</p>';
        echo '</div>';
    }
}

// Update the admin display function to show in order notes section
add_action('woocommerce_admin_order_data_after_billing_address', 'display_cart_message_in_admin_order_notes', 10, 1);

function display_cart_message_in_admin_order_notes($order) {
    $cart_message = $order->get_meta('_cart_message');
    if (!empty($cart_message)) {
        echo '<p style="margin:top:20px;"><strong>' . esc_html__('Customer Notes:', 'your-textdomain') . '</strong><br>';
        echo esc_html($cart_message) . '</p>';
    }
}

// Clear cart message after the order is placed
add_action('woocommerce_thankyou', 'clear_cart_message_after_order');

function clear_cart_message_after_order() {
    WC()->session->__unset('cart_message');
}

// Enqueue JS and localize AJAX
add_action('wp_enqueue_scripts', 'enqueue_cart_message_script');

function enqueue_cart_message_script() {
    wp_localize_script('custom-cart', 'cartMessageAjax', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
    ));
}

add_action('woocommerce_checkout_update_order_meta', function ($order_id) {
    if (!empty($_POST['event_type'])) {
        update_post_meta($order_id, '_event_type', sanitize_text_field($_POST['event_type']));
    }
});

add_action('woocommerce_admin_order_data_after_billing_address', function ($order) {
    $event_type = get_post_meta($order->get_id(), '_event_type', true);
    if ($event_type) {
        echo '<p><strong>Event Type:</strong> ' . esc_html(ucwords(str_replace('-', ' ', $event_type))) . '</p>';
    }
});

function enqueue_masonry_script() {
    wp_enqueue_script('masonry');
}

add_action('wp_enqueue_scripts', 'enqueue_masonry_script');

add_filter('woocommerce_checkout_update_customer_data', '__return_true');

/**
 * Change the default state and country on the checkout page
 */
add_filter('default_checkout_billing_country', 'change_default_checkout_country', 10, 1);
add_filter('default_checkout_shipping_country', 'change_default_checkout_country', 10, 1);

function change_default_checkout_country() {
    return 'AE'; // country code
}

function find_cart_item_key($product_id) {
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        if ($cart_item['product_id'] === $product_id) {
            return $cart_item_key;
        }
    }
    return false;
}

add_action('wp_ajax_empty_cart', 'clear_cart_function');
add_action('wp_ajax_nopriv_empty_cart', 'clear_cart_function');

function clear_cart_function() {
    WC()->cart->empty_cart(); // Clear WooCommerce cart
    wc_clear_notices(); // Clear any notices
    WC()->session->set('cart', []); // Ensure the session is reset
    WC()->cart->set_session(); // Save the empty state

    wp_send_json_success();
}

function ts_checkout_fields_billing($fields) {
    $fields['billing']['billing_country'] = array(
        'type' => 'select',
        'label' => __('Country', 'woocommerce'),
        'placeholder' => __('Country', 'woocommerce'),
        'default' => 'AE',
        'options' => array(
            'AE' => 'United Arab Emirates',
            'AF' => 'Afghanistan',
            'AL' => 'Albania',
            'DZ' => 'Algeria',
            'AS' => 'American Samoa',
            'AD' => 'Andorra',
            'AO' => 'Angola',
            'AI' => 'Anguilla',
            'AQ' => 'Antarctica',
            'AG' => 'Antigua and Barbuda',
            'AR' => 'Argentina',
            'AM' => 'Armenia',
            'AW' => 'Aruba',
            'AU' => 'Australia',
            'AT' => 'Austria',
            'AZ' => 'Azerbaijan',
            'BS' => 'Bahamas',
            'BH' => 'Bahrain',
            'BD' => 'Bangladesh',
            'BB' => 'Barbados',
            'BY' => 'Belarus',
            'BE' => 'Belgium',
            'BZ' => 'Belize',
            'BJ' => 'Benin',
            'BM' => 'Bermuda',
            'BT' => 'Bhutan',
            'BO' => 'Bolivia',
            'BQ' => 'Bonaire, Sint Eustatius and Saba',
            'BA' => 'Bosnia and Herzegovina',
            'BW' => 'Botswana',
            'BV' => 'Bouvet Island',
            'BR' => 'Brazil',
            'IO' => 'British Indian Ocean Territory',
            'BN' => 'Brunei Darussalam',
            'BG' => 'Bulgaria',
            'BF' => 'Burkina Faso',
            'BI' => 'Burundi',
            'CV' => 'Cabo Verde',
            'KH' => 'Cambodia',
            'CM' => 'Cameroon',
            'CA' => 'Canada',
            'KY' => 'Cayman Islands',
            'CF' => 'Central African Republic',
            'TD' => 'Chad',
            'CL' => 'Chile',
            'CN' => 'China',
            'CX' => 'Christmas Island',
            'CC' => 'Cocos (Keeling) Islands',
            'CO' => 'Colombia',
            'KM' => 'Comoros',
            'CG' => 'Congo',
            'CD' => 'Congo, Democratic Republic of the',
            'CK' => 'Cook Islands',
            'CR' => 'Costa Rica',
            'HR' => 'Croatia',
            'CU' => 'Cuba',
            'CW' => 'Curaçao',
            'CY' => 'Cyprus',
            'CZ' => 'Czech Republic',
            'DK' => 'Denmark',
            'DJ' => 'Djibouti',
            'DM' => 'Dominica',
            'DO' => 'Dominican Republic',
            'EC' => 'Ecuador',
            'EG' => 'Egypt',
            'SV' => 'El Salvador',
            'GQ' => 'Equatorial Guinea',
            'ER' => 'Eritrea',
            'EE' => 'Estonia',
            'SZ' => 'Eswatini',
            'ET' => 'Ethiopia',
            'FK' => 'Falkland Islands (Malvinas)',
            'FO' => 'Faroe Islands',
            'FJ' => 'Fiji',
            'FI' => 'Finland',
            'FR' => 'France',
            'GF' => 'French Guiana',
            'PF' => 'French Polynesia',
            'TF' => 'French Southern Territories',
            'GA' => 'Gabon',
            'GM' => 'Gambia',
            'GE' => 'Georgia',
            'DE' => 'Germany',
            'GH' => 'Ghana',
            'GI' => 'Gibraltar',
            'GR' => 'Greece',
            'GL' => 'Greenland',
            'GD' => 'Grenada',
            'GP' => 'Guadeloupe',
            'GU' => 'Guam',
            'GT' => 'Guatemala',
            'GG' => 'Guernsey',
            'GN' => 'Guinea',
            'GW' => 'Guinea-Bissau',
            'GY' => 'Guyana',
            'HT' => 'Haiti',
            'HM' => 'Heard Island and McDonald Islands',
            'VA' => 'Holy See (Vatican City State)',
            'HN' => 'Honduras',
            'HK' => 'Hong Kong',
            'HU' => 'Hungary',
            'IS' => 'Iceland',
            'IN' => 'India',
            'ID' => 'Indonesia',
            'IR' => 'Iran, Islamic Republic of',
            'IQ' => 'Iraq',
            'IE' => 'Ireland',
            'IM' => 'Isle of Man',
            'IL' => 'Israel',
            'IT' => 'Italy',
            'JM' => 'Jamaica',
            'JP' => 'Japan',
            'JE' => 'Jersey',
            'JO' => 'Jordan',
            'KZ' => 'Kazakhstan',
            'KE' => 'Kenya',
            'KI' => 'Kiribati',
            'KP' => 'Korea, Democratic People\'s Republic of',
            'KR' => 'Korea, Republic of',
            'KW' => 'Kuwait',
            'KG' => 'Kyrgyzstan',
            'LA' => 'Lao People\'s Democratic Republic',
            'LV' => 'Latvia',
            'LB' => 'Lebanon',
            'LS' => 'Lesotho',
            'LR' => 'Liberia',
            'LY' => 'Libya',
            'LI' => 'Liechtenstein',
            'LT' => 'Lithuania',
            'LU' => 'Luxembourg',
            'MO' => 'Macao',
            'MG' => 'Madagascar',
            'MW' => 'Malawi',
            'MY' => 'Malaysia',
            'MV' => 'Maldives',
            'ML' => 'Mali',
            'MT' => 'Malta',
            'MH' => 'Marshall Islands',
            'MQ' => 'Martinique',
            'MR' => 'Mauritania',
            'MU' => 'Mauritius',
            'YT' => 'Mayotte',
            'MX' => 'Mexico',
            'FM' => 'Micronesia, Federated States of',
            'MD' => 'Moldova, Republic of',
            'MC' => 'Monaco',
            'MN' => 'Mongolia',
            'ME' => 'Montenegro',
            'MS' => 'Montserrat',
            'MA' => 'Morocco',
            'MZ' => 'Mozambique',
            'MM' => 'Myanmar',
            'NA' => 'Namibia',
            'NR' => 'Nauru',
            'NP' => 'Nepal',
            'NL' => 'Netherlands',
            'NC' => 'New Caledonia',
            'NZ' => 'New Zealand',
            'NI' => 'Nicaragua',
            'NE' => 'Niger',
            'NG' => 'Nigeria',
            'NU' => 'Niue',
            'NF' => 'Norfolk Island',
            'MP' => 'Northern Mariana Islands',
            'NO' => 'Norway',
            'OM' => 'Oman',
            'PK' => 'Pakistan',
            'PW' => 'Palau',
            'PS' => 'Palestine, State of',
            'PA' => 'Panama',
            'PG' => 'Papua New Guinea',
            'PY' => 'Paraguay',
            'PE' => 'Peru',
            'PH' => 'Philippines',
            'PN' => 'Pitcairn',
            'PL' => 'Poland',
            'PT' => 'Portugal',
            'PR' => 'Puerto Rico',
            'QA' => 'Qatar',
            'RE' => 'Réunion',
            'RO' => 'Romania',
            'RU' => 'Russian Federation',
            'RW' => 'Rwanda',
            'BL' => 'Saint Barthélemy',
            'SH' => 'Saint Helena, Ascension and Tristan da Cunha',
            'KN' => 'Saint Kitts and Nevis',
            'LC' => 'Saint Lucia',
            'MF' => 'Saint Martin (French part)',
            'PM' => 'Saint Pierre and Miquelon',
            'VC' => 'Saint Vincent and the Grenadines',
            'WS' => 'Samoa',
            'SM' => 'San Marino',
            'ST' => 'Sao Tome and Principe',
            'SA' => 'Saudi Arabia',
            'SN' => 'Senegal',
            'RS' => 'Serbia',
            'SC' => 'Seychelles',
            'SL' => 'Sierra Leone',
            'SG' => 'Singapore',
            'SX' => 'Sint Maarten (Dutch part)',
            'SK' => 'Slovakia',
            'SI' => 'Slovenia',
            'SB' => 'Solomon Islands',
            'SO' => 'Somalia',
            'ZA' => 'South Africa',
            'GS' => 'South Georgia and the South Sandwich Islands',
            'SS' => 'South Sudan',
            'ES' => 'Spain',
            'LK' => 'Sri Lanka',
            'SD' => 'Sudan',
            'SR' => 'Suriname',
            'SJ' => 'Svalbard and Jan Mayen',
            'SE' => 'Sweden',
            'CH' => 'Switzerland',
            'SY' => 'Syrian Arab Republic',
            'TW' => 'Taiwan, Province of China',
            'TJ' => 'Tajikistan',
            'TZ' => 'Tanzania, United Republic of',
            'TH' => 'Thailand',
            'TL' => 'Timor-Leste',
            'TG' => 'Togo',
            'TK' => 'Tokelau',
            'TO' => 'Tonga',
            'TT' => 'Trinidad and Tobago',
            'TN' => 'Tunisia',
            'TR' => 'Turkey',
            'TM' => 'Turkmenistan',
            'TC' => 'Turks and Caicos Islands',
            'TV' => 'Tuvalu',
            'UG' => 'Uganda',
            'UA' => 'Ukraine',
            'GB' => 'United Kingdom',
            'US' => 'United States',
            'UM' => 'United States Minor Outlying Islands',
            'UY' => 'Uruguay',
            'UZ' => 'Uzbekistan',
            'VU' => 'Vanuatu',
            'VE' => 'Venezuela, Bolivarian Republic of',
            'VN' => 'Viet Nam',
            'VG' => 'Virgin Islands, British',
            'VI' => 'Virgin Islands, U.S.',
            'WF' => 'Wallis and Futuna',
            'EH' => 'Western Sahara',
            'YE' => 'Yemen',
            'ZM' => 'Zambia',
            'ZW' => 'Zimbabwe'
        ),
        'class' => array('wc-enhanced-select', 'form-row-wide', 'address-field'),
    );

    $fields['shipping']['shipping_country'] = array(
        'type' => 'select',
        'label' => __('Country', 'woocommerce'),
        'placeholder' => __('Country', 'woocommerce'),
        'default' => 'AE',
        'options' => array('AE' => 'United Arab Emirates'),
        'class' => array('wc-enhanced-select', 'form-row-wide', 'address-field'),
    );

    $fields['billing']['billing_city']['required'] = true;
    $fields['shipping']['shipping_city']['required'] = false;
    $fields['shipping']['shipping_postcode']['required'] = false;
    $fields['billing']['billing_postcode']['required'] = false;
    // $fields['billing']['billing_state']['required'] = false;

    return $fields;
}

add_filter('woocommerce_checkout_fields', 'ts_checkout_fields_billing');

function remove_prefilled_checkout_values_for_admin($value, $input) {
    if (current_user_can('manage_options')) {
        return ''; // Remove the prefilled value for admins
    }
    return $value;
}

add_filter('woocommerce_checkout_get_value', 'remove_prefilled_checkout_values_for_admin', 10, 2);

function restrict_checkout_if_cart_total_is_low() {
    if ( WC()->cart && ! WC()->cart->is_empty() ) {
        $minimum_amount = 999; // Minimum order amount in AED
        $currency = get_woocommerce_currency();
        $subtotal = WC()->cart->get_subtotal();

        if ($subtotal < $minimum_amount && $currency === 'AED') {
            wc_add_notice(__('Your order total must be at least 1,000.00 AED to proceed with checkout.', 'woocommerce'), 'error');
        }
    }
}

add_action('woocommerce_checkout_process', 'restrict_checkout_if_cart_total_is_low');

function disable_checkout_button_for_low_cart_total() {
    if (is_cart() || is_checkout()) {
        ?>
        <script>
            document.addEventListener("DOMContentLoaded", function () {
                function parseAmount(el) {
                    if (!el)
                        return 0;
                    return parseFloat(el.innerText.replace(/[^\d.]/g, '')) || 0;
                }

                function checkTotal() {
                    const minimumAmount = 999;
                    const orderTotalElement = document.querySelector('.cart-subtotal .amount');
                    const errorMsg = document.querySelector('.order-total-error');
                    const checkoutButton = document.querySelector('.wc-proceed-to-checkout a');

                    const total = parseAmount(orderTotalElement);
                    console.log("Detected total: ", total);

                    if (errorMsg) {
                        errorMsg.style.display = (total < minimumAmount) ? 'table-row' : 'none';
                    }

                    if (checkoutButton) {
                        if (total < minimumAmount) {
                            checkoutButton.style.pointerEvents = "none";
                            checkoutButton.style.opacity = "0.5";
                            checkoutButton.style.cursor = "not-allowed";
                            checkoutButton.setAttribute("aria-disabled", "true");
                        } else {
                            checkoutButton.style.pointerEvents = "auto";
                            checkoutButton.style.opacity = "1";
                            checkoutButton.style.cursor = "pointer";
                            checkoutButton.removeAttribute("aria-disabled");
                        }
                    }
                }

                // Initial check
                checkTotal();

                // Recheck on WooCommerce AJAX events with slight delay
                jQuery(document.body).on('updated_wc_div updated_cart_totals updated_checkout', function () {
                    setTimeout(checkTotal, 300); // Wait for DOM update
                });
            });
        </script>
        <?php
    }
}

add_action('wp_footer', 'disable_checkout_button_for_low_cart_total');

function cart_total_updates_with_warning_and_button_control() {
    ?>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            function checkCartTotal() {
                let cartTotalElement = document.querySelector('.cart-total-amount');
                let cartContainer = document.querySelector('#cartBarMessage'); // Use correct container
                let checkoutButton = document.querySelector('.checkout-btn');

                if (cartTotalElement && cartContainer && checkoutButton) {
                    let cartTotalText = cartTotalElement.innerText.replace(/[^\d.]/g, ''); // Extract numeric value
                    let cartTotal = parseFloat(cartTotalText);

                    let warningDiv = document.getElementById('cartWarningMessage');

                    // 🚀 Disable Checkout Button & Show Warning if Total < 1000
                    if (cartTotal < 999) {
                        checkoutButton.classList.add("disable");
                        checkoutButton.style.pointerEvents = "none"; // Make it unclickable
                        checkoutButton.style.opacity = "0.5"; // Reduce visibility

                        if (!warningDiv) {
                            warningDiv = document.createElement('div');
                            warningDiv.id = 'cartWarningMessage';
                            warningDiv.style.cssText = "display:none; align-items: center; gap: 10px;  margin-top: 10px;";
                            warningDiv.innerHTML = `<img src="https://www.capitalcateringplus.ae/app/uploads/2025/03/Vector-14.svg" alt="info-icon" style="width: 20px; height: 20px;">
                                <p>You’ll need a minimum order of: AED 1,000.00</p>`;

                            cartContainer.parentNode.insertBefore(warningDiv, cartContainer.nextSibling);
                        } else {
                            warningDiv.style.display = "flex"; // Show if already exists
                        }
                    } else {
                        // ✅ Enable Checkout Button & Remove Warning if Total >= 1000
                        //                        checkoutButton.classList.remove("disable");
                        //                        checkoutButton.style.pointerEvents = "auto"; // Make it clickable
                        //                        checkoutButton.style.opacity = "1"; // Restore visibility

                        if (warningDiv) {
                            warningDiv.style.display = "none"; // Hide instead of removing
                        }
                    }
                }
            }

            // Run on page load
            checkCartTotal();



            // 🔥 Observe changes in cart total (Real-time updates)
            let cartObserver = new MutationObserver(checkCartTotal);
            let targetElement = document.querySelector('.cart-total-amount');

            if (targetElement) {
                cartObserver.observe(targetElement, {childList: true, subtree: true});
            }
        });
    </script>
    <?php
}

add_action('wp_footer', 'cart_total_updates_with_warning_and_button_control');

add_filter('woocommerce_coupon_error', function ($err_msg, $err_code, $coupon) {
    if ($err_code === 111) {
        return '';
    }

    if ($err_code === 105) {
        return 'Oops! That coupon code isn’t valid. Please check the code and try again.';
    }

    return $err_msg;
}, 10, 3);

add_filter('woocommerce_states', 'fs_add_uae_emirates');

function fs_add_uae_emirates($states) {
    $states['AE'] = array(
        'AZ' => __('Abu Dhabi', 'woocommerce'),
        'AJ' => __('Ajman', 'woocommerce'),
        'AA' => __('Al Ain', 'woocommerce'),
        'FU' => __('Fujairah', 'woocommerce'),
        'SH' => __('Sharjah', 'woocommerce'),
        'DU' => __('Dubai', 'woocommerce'),
        'RK' => __('Ras Al Khaimah', 'woocommerce'),
        'UQ' => __('Umm Al Quwain', 'woocommerce'),
    );
    return $states;
}

function alter_faq_posts_query($query) {
    global $wp_query;

    $query_vars = $query->query_vars;
    $search_term = isset($_GET['s']) ? $_GET['s'] : '';
    if (isset($query_vars['post_type']) && $query_vars['post_type'] == 'faq' && !empty($search_term)) {
        $query->set('s', $search_term);
        // echo "<pre>";
        // print_r($query);
        // echo "</pre>";
    }
}

add_action('pre_get_posts', 'alter_faq_posts_query');
add_action('wp_ajax_seaso_faqs', 'search_sort_faqs');
add_action('wp_ajax_nopriv_seaso_faqs', 'search_sort_faqs');

function search_sort_faqs() {
    $search_term = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';

    $terms = getTaxonomies('faq_category');
    $terms_html = '<ul class="faqcatgroup">';
    $posts_html = '';
    $posts_count = 0;

    if ($terms) {
        $active = false;

        foreach ($terms as $termKey => $term) {
            $class = 'tab-link';
            if (!$active) {
                $class .= ' active';
            }

            $faq_posts = get_posts(array(
                'post_type' => 'faq',
                'posts_per_page' => -1,
                'order' => 'DESC',
                's' => $search_term,
                'tax_query' => array(array(
                        'taxonomy' => 'faq_category',
                        'field' => 'slug',
                        'terms' => $term->slug
                    ))
            ));

            if (!empty($faq_posts)) {
                $terms_html .= '<li' . ($term->parent ? ' class="childterm"' : '') . '>
                                    <a class="' . esc_attr($class) . '" data-toggle="tab" href="#' . esc_attr($term->slug) . '">' . esc_html($term->name) . '</a>
                                </li>';

                $posts_html .= '<div class="tab-pane fade' . (!$active ? ' active show' : '') . '" id="' . esc_attr($term->slug) . '">
                                    <h3 class="title_text mb-50">' . esc_html($term->name) . '</h3>
                                    <div id="accordion-' . esc_attr($termKey) . '" class="faq_accordion">';

                foreach ($faq_posts as $key => $post) {
                    $accordion_id = 'collapse-' . $term->term_id . '-' . $key;
                    $heading_id = 'heading-' . $term->term_id . '-' . $key;

                    $posts_html .= '<div class="accordion-item" data-post-id="' . esc_attr($post->ID) . '">';
                    $posts_html .= '<h2 class="accordion-header" id="' . esc_attr($heading_id) . '">';
                    $posts_html .= '<button class="accordion-button ' . ($key !== 0 ? 'collapsed' : '') . '" type="button" data-bs-toggle="collapse" data-bs-target="#' . esc_attr($accordion_id) . '" aria-expanded="' . ($key === 0 ? 'true' : 'false') . '" aria-controls="' . esc_attr($accordion_id) . '">';
                    $posts_html .= esc_html($post->post_title);
                    $posts_html .= '</button>';
                    $posts_html .= '</h2>';
                    $posts_html .= '<div id="' . esc_attr($accordion_id) . '" class="accordion-collapse collapse' . ($key === 0 ? ' show' : '') . '" aria-labelledby="' . esc_attr($heading_id) . '" data-bs-parent="#accordion-' . esc_attr($termKey) . '">';
                    $posts_html .= '<div class="accordion-body">' . wp_kses_post(wpautop($post->post_content)) . '</div>';
                    $posts_html .= '</div>';
                    $posts_html .= '</div>';
                }


                $posts_html .= '</div>
                                </div>';
                $posts_count++;
                $active = true;
            }
        }
    }

    $terms_html .= '</ul>';

    wp_send_json(array(
        'search' => $search_term,
        'items_count' => $posts_count,
        'terms_html' => $terms_html,
        'posts_html' => $posts_html
    ));
}

function getTaxonomies($taxonomy, $term_id = 0, $depth = 0, $max_depth = 10) {
    if ($depth > $max_depth)
        return [];

    $terms = [];

    $args = [
        'taxonomy' => $taxonomy,
        'parent' => $term_id,
        'hide_empty' => false,
    ];

    $categories = get_terms($args);

    if (!empty($categories) && !is_wp_error($categories)) {
        foreach ($categories as $category) {
            $terms[] = $category;

            $childTerms = getTaxonomies($taxonomy, $category->term_id, $depth + 1, $max_depth);
            $terms = array_merge($terms, $childTerms);
        }
    }

    return $terms;
}

add_filter('woocommerce_my_account_my_address_formatted_address', 'custom_display_company_vat_in_address', 10, 3);

function custom_display_company_vat_in_address($address, $customer_id, $address_type) {
    if ($address_type === 'billing') {
        $vat = get_user_meta($customer_id, 'billing_vat', true);
        $company = get_user_meta($customer_id, 'billing_company', true);

        if (!empty($company)) {
            $address['company'] = $company; // This may already exist
        }

        if (!empty($vat)) {
            $address['vat'] = 'VAT: ' . $vat;
        }
    }

    return $address;
}

add_action('woocommerce_admin_order_data_after_billing_address', 'display_custom_billing_fields_admin', 10, 1);

function display_custom_billing_fields_admin($order) {
    $user_id = $order->get_user_id();

    // Get values from user meta OR order meta fallback
    //$vat     = get_user_meta($user_id, 'billing_vat', true);
    //$company = get_user_meta($user_id, 'billing_company', true);

    $vat = $order->get_meta('_billing_vat');
    $company = $order->get_billing_company();

    // Fallback if user meta doesn't exist (e.g. guest order)
    if (!$vat) {
        $vat = $order->get_meta('_billing_vat');
    }

    if (!$company) {
        $company = $order->get_billing_company();
    }

    if (!empty($company)) {
        echo '<p><strong>' . __('Company') . ':</strong> ' . esc_html($company) . '</p>';
    }

    if (!empty($vat)) {
        echo '<p><strong>' . __('VAT Number') . ':</strong> ' . esc_html($vat) . '</p>';
    }
}

add_action('woocommerce_checkout_update_order_meta', 'save_billing_vat_to_order');

function save_billing_vat_to_order($order_id) {
    if (isset($_POST['billing_vat'])) {
        update_post_meta($order_id, '_billing_vat', sanitize_text_field($_POST['billing_vat']));
    }
}

/* add_action('woocommerce_customer_save_address', 'save_custom_billing_fields', 10, 2);

  function save_custom_billing_fields($user_id, $load_address) {
  if ($load_address === 'billing') {
  if (isset($_POST['billing_vat'])) {
  update_user_meta($user_id, 'billing_vat', sanitize_text_field($_POST['billing_vat']));
  }

  if (isset($_POST['billing_company'])) {
  update_user_meta($user_id, 'billing_company', sanitize_text_field($_POST['billing_company']));
  }
  }
  } */

// Make zip/postcode field optional
add_filter('woocommerce_default_address_fields', 'QuadLayers_optional_postcode_checkout');

function QuadLayers_optional_postcode_checkout($p_fields) {
    $p_fields['postcode']['required'] = false;
    return $p_fields;
}

add_filter('woocommerce_shipping_package_name', 'custom_shipping_section_title', 10, 3);

function custom_shipping_section_title($package_name, $i, $package) {
    return 'Delivery fees'; // <-- change this to your preferred text
}

add_filter('woocommerce_cart_shipping_method_full_label', 'remove_flat_rate_text', 10, 2);

function remove_flat_rate_text($label, $method) {
    if ($method->method_id === 'flat_rate') {
        // Remove method title, keep only price
        $label_parts = explode(':', $label);
        if (isset($label_parts[1])) {
            $label = trim($label_parts[1]); // just the price
        }
    }
    return $label;
}

add_action('wp_ajax_save_delivery_method', 'save_delivery_method_in_session');
add_action('wp_ajax_nopriv_save_delivery_method', 'save_delivery_method_in_session');

function save_delivery_method_in_session() {

    check_ajax_referer('update-order-review', 'security');

    if (!isset($_POST['delivery_method'])) {
        wp_send_json_error(['message' => 'No delivery method provided.']);
        wp_die();
    }

    $delivery_method = sanitize_text_field($_POST['delivery_method']);
    if (!in_array($delivery_method, ['deliver', 'pickup'])) {
        wp_send_json_error(['message' => 'Invalid delivery method.']);
        wp_die();
    }

    WC()->session->set('custom_delivery_method', $delivery_method);
    wp_send_json_success(['message' => "Delivery method saved: $delivery_method"]);
    wp_die();
}

add_action('woocommerce_checkout_create_order', 'add_custom_delivery_method_to_order', 10, 2);

function add_custom_delivery_method_to_order($order, $data) {
    $delivery_method = WC()->session->get('custom_delivery_method');

    if ($delivery_method) {
        $order->update_meta_data('_custom_delivery_method', $delivery_method);
    }
}

add_action('woocommerce_thankyou', 'clear_custom_delivery_method_session', 20);

function clear_custom_delivery_method_session($order_id) {
    if (WC()->session) {
        WC()->session->__unset('custom_delivery_method');
    }
}

add_filter('woocommerce_checkout_fields', 'conditionally_remove_shipping_validation');

function conditionally_remove_shipping_validation($fields) {
    if (WC()->session && WC()->session->get('custom_delivery_method') === 'pickup') {
        if (isset($fields['shipping']) && is_array($fields['shipping'])) {
            foreach ($fields['shipping'] as $key => &$field) {
                $field['required'] = false;
            }
        }
    }
    return $fields;
}

// Ensure delivery method is updated during checkout
add_action('woocommerce_checkout_update_order_review', 'update_delivery_method_on_checkout');

function update_delivery_method_on_checkout($posted_data) {
    parse_str($posted_data, $posted);
    if (isset($posted['delivery_method'])) {
        $delivery_method = sanitize_text_field($posted['delivery_method']);
        if (in_array($delivery_method, ['deliver', 'pickup'])) {
            WC()->session->set('custom_delivery_method', $delivery_method);
        }
    }
}

add_filter('woocommerce_checkout_fields', 'conditionally_require_password_field');

function conditionally_require_password_field($fields) {
    // By default, make the password field not required
    $fields['account']['account_password']['required'] = false;

    // If 'Create an account' is checked during the checkout form submission, make password required
    if (isset($_POST['createaccount']) && $_POST['createaccount'] == '1') {
        $fields['account']['account_password']['required'] = true;
    }

    return $fields;
}

add_filter('gform_phone_formats', 'custom_phone_format');

function custom_phone_format($phone_formats) {
    $phone_formats['uae_simple'] = array(
        'label' => 'UAE Simple',
        'mask' => false,
        'regex' => '/^\d{9}$/',
        'instruction' => false,
    );
    return $phone_formats;
}

add_filter('gform_pre_validation', function ($form) {
    foreach ($form['fields'] as &$field) {
        if ($field->type === 'phone' && $field->phoneFormat === 'uae_simple') {
            $input_id = 'input_' . $field->id;

            if (isset($_POST[$input_id])) {
                $digits = preg_replace('/\D/', '', $_POST[$input_id]);
                $_POST[$input_id] = $digits;
            }
        }
    }
    return $form;
});

/* add_filter( 'gform_pre_submission_filter', function ( $form ) {
  foreach ( $form['fields'] as &$field ) {
  if ( $field->type === 'phone' && $field->phoneFormat === 'uae_simple' ) {
  $input_id = 'input_' . $field->id;

  if ( isset( $_POST[ $input_id ] ) ) {
  $digits = preg_replace('/\D/', '', $_POST[ $input_id ]);

  if ( strlen($digits) === 9 ) {
  $formatted = preg_replace('/(\d{2})(\d{3})(\d{4})/', '$1 $2 $3', $digits);
  $_POST[ $input_id ] = '+971 ' . $formatted;
  }
  }
  }
  }
  return $form;
  }); */

add_filter('gform_input_mask_script_output', '__return_empty_string');

add_filter('woocommerce_account_menu_items', 'custom_account_menu_items');

function custom_account_menu_items($items) {
    return [
        'orders' => 'Order history',
        'edit-address' => 'Addresses',
        'payment-methods' => 'Payment methods',
        'edit-account' => 'Account details',
        'customer-logout' => 'Logout',
    ];
}

add_action('template_redirect', 'handle_custom_address_deletion');

function handle_custom_address_deletion() {
    if (is_account_page() && isset($_GET['delete_address']) && is_user_logged_in()) {
        $address_type = sanitize_text_field($_GET['delete_address']);
        $allowed = ['billing', 'shipping'];

        if (in_array($address_type, $allowed)) {
            $user_id = get_current_user_id();
            $fields = [
                'first_name',
                'last_name',
                'company',
                'address_1',
                'address_2',
                'city',
                'state',
                'postcode',
                'country',
                'email',
                'vat',
            ];

            foreach ($fields as $field) {
                    delete_user_meta($user_id, "{$address_type}_{$field}");
            }

            wc_add_notice(ucfirst($address_type) . ' address deleted.', 'success');
            wp_redirect(wc_get_account_endpoint_url('edit-address'));
            exit;
        }
    }
}

add_action('woocommerce_save_account_details', 'custom_save_account_phone_number', 12, 1);

function custom_save_account_phone_number($user_id) {
    if (isset($_POST['account_phone'])) {

        $phone = trim($_POST['account_phone']); // Preserve spaces

        if (!empty($_POST['billing_dial_code'])) {
            $dial_code = trim($_POST['billing_dial_code']);
        } else {
            $dial_code = ''; // Fallback if not provided
        }

        if (!empty($dial_code)) {
            $merged_phone = $dial_code .' '. $phone;
        } else {
            $merged_phone = $phone; // Save plain phone if no dial code
        }

        update_user_meta($user_id, 'billing_phone', $merged_phone);
    }
}

// Handle account deletion
add_action('wp_ajax_delete_user_account', 'handle_account_deletion');
add_action('wp_ajax_nopriv_delete_user_account', 'handle_account_deletion');

function handle_account_deletion() {
    check_ajax_referer('delete-account', 'security');

    if (!is_user_logged_in()) {
        wp_send_json_error(__('You must be logged in to delete your account.', 'woocommerce'));
        return;
    }

    $user_id = get_current_user_id();

    // Prevent admin deletion
    if (user_can($user_id, 'manage_options')) {
        wp_send_json_error(__('Administrators cannot delete their accounts this way.', 'woocommerce'));
        return;
    }

    require_once(ABSPATH . 'wp-admin/includes/user.php');

    // Reassign posts and orders to admin (ID 1) or delete them
    $reassign_id = 1; // Default admin user ID, adjust if needed
    if (!get_user_by('id', $reassign_id)) {
        $reassign_id = null; // Delete content if no reassign user exists
    }

    // Delete user and all associated data
    $deleted = wp_delete_user($user_id, $reassign_id);

    if ($deleted) {
        // Clear any remaining user meta
        global $wpdb;
        $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d", $user_id));

        // Clear WooCommerce-specific data (e.g., sessions)
        $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->woocommerce_sessions WHERE session_key = %s", $user_id));

        wp_send_json_success(array(
            'message' => __('Your account has been successfully deleted. You will be redirected to the home page.', 'woocommerce')
        ));
    } else {
        wp_send_json_error(__('Failed to delete account. Please try again.', 'woocommerce'));
    }
}

// Update custom meta during order creation
/* function update_order_custom_meta_on_creation( $order, $data ) {
  // Loop through cart items
  foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
  // Check if the cart item has 'included_options'
  if ( isset( $cart_item['included_options'] ) && is_array( $cart_item['included_options'] ) ) {
  // Add custom meta to the order item for included options
  $order_item = $order->get_item( $cart_item_key );
  $order_item->add_meta_data( 'included_options', implode( ', ', $cart_item['included_options'] ) );
  }
  }
  }
  add_action( 'woocommerce_checkout_create_order', 'update_order_custom_meta_on_creation', 10, 2 ); */

// Change "State" or "County" label to "Emirate" everywhere in WooCommerce
add_filter('woocommerce_default_address_fields', function ($fields) {
    if (isset($fields['state'])) {
        $fields['state']['label'] = __('Emirate', 'woocommerce');
        $fields['state']['placeholder'] = __('Emirate', 'woocommerce');
    }
    return $fields;
});

/* add_filter( 'woocommerce_shipping_address_map_fields', function( $fields ) {
  if ( isset( $fields['state'] ) ) {
  // $fields['state'] = 'emirate';
  $fields['state'] = $address['state'];
  }
  return $fields;
  } ); */

/* add_filter( 'woocommerce_localisation_address_formats', function( $formats ) {
  foreach ( $formats as $country => $format ) {
  $formats[$country] = str_replace('{state}', '{emirate}', $format);
  }
  return $formats;
  } ); */



// When order is created, transfer included_options from cart to order
add_action('woocommerce_checkout_create_order_line_item', function ($item, $cart_item_key, $values, $order) {
    if (isset($values['included_options'])) {
        $item->update_meta_data('Included Options', $values['included_options']);
    }
}, 20, 4);

// Change "Processing" to "Order Confirmed" everywhere.
add_filter('wc_order_statuses', function ($order_statuses) {
    if (isset($order_statuses['wc-processing'])) {
        $order_statuses['wc-processing'] = _x('Confirmed', 'Order status', 'woocommerce');
    }
    return $order_statuses;
});

// Change "Processing" to "Order Confirmed" in backend dropdowns.
add_filter('register_post_status', function ($args, $post_status) {
    if ('wc-processing' === $post_status) {
        $args['label'] = _x('Confirmed', 'Order status', 'woocommerce');
        $args['label_count'] = _n_noop('Confirmed (%s)', 'Confirmed (%s)', 'woocommerce');
    }
    return $args;
}, 20, 2);

add_action('wp_footer', function () {
    if (is_checkout()) {
        ?>
        <script>
            (function ($) {
                function updateShippingMessage() {
                    var shippingMessage = document.querySelector('.woocommerce-shipping-may-be-available-html');
                    if (shippingMessage) {
                        shippingMessage.textContent = 'Enter address for fees';
                    }
                }

                // Run when page loads
                $(document).ready(function () {
                    updateShippingMessage();
                });

                // Run every time checkout updates
                $('body').on('updated_checkout', function () {
                    updateShippingMessage();
                });

            })(jQuery);
        </script>
        <?php
    }
});

// Register custom order statuses
add_action('init', function () {
    register_post_status('wc-ready-for-pickup', array(
        'label' => _x('Ready for Pickup', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Ready for Pickup (%s)', 'Ready for Pickup (%s)', 'woocommerce'),
    ));

    register_post_status('wc-picked-up', array(
        'label' => _x('Picked Up', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Picked Up (%s)', 'Picked Up (%s)', 'woocommerce'),
    ));

    register_post_status('wc-pickup-missed', array(
        'label' => _x('Pickup missed', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Pickup missed (%s)', 'Pickup missed (%s)', 'woocommerce'),
    ));

    register_post_status('wc-disposed', array(
        'label' => _x('Disposed/Not collected', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Disposed/Not collected (%s)', 'Disposed/Not collected (%s)', 'woocommerce'),
    ));

    register_post_status('wc-out-for-delivery', array(
        'label' => _x('Out for Delivery', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Out for Delivery (%s)', 'Out for Delivery (%s)', 'woocommerce'),
    ));

    register_post_status('wc-delivery-failed', array(
        'label' => _x('Delivery attempt failed', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Delivery attempt failed (%s)', 'Delivery attempt failed (%s)', 'woocommerce'),
    ));

    register_post_status('wc-retry-delivery', array(
        'label' => _x('Reattempting delivery', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Reattempting delivery (%s)', 'Reattempting delivery (%s)', 'woocommerce'),
    ));

    register_post_status('wc-delivered', array(
        'label' => _x('Delivered', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Delivered (%s)', 'Delivered (%s)', 'woocommerce'),
    ));

    register_post_status('wc-on-way-venue', array(
        'label' => _x('On the way to venue', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('On the way to venue (%s)', 'On the way to venue (%s)', 'woocommerce'),
    ));

    register_post_status('wc-event-in-progress', array(
        'label' => _x('Event in progress', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Event in progress (%s)', 'Event in progress (%s)', 'woocommerce'),
    ));

    register_post_status('wc-preparing', array(
        'label' => _x('Preparing', 'Order status', 'woocommerce'),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Preparing (%s)', 'Preparing (%s)', 'woocommerce'),
    ));
});

// Add custom statuses to WooCommerce list
add_filter('wc_order_statuses', function ($order_statuses) {
    $new_order_statuses = $order_statuses;

    $new_order_statuses['wc-ready-for-pickup'] = _x('Ready for Pickup', 'Order status', 'woocommerce');
    $new_order_statuses['wc-picked-up'] = _x('Picked Up', 'Order status', 'woocommerce');
    $new_order_statuses['wc-pickup-missed'] = _x('Pickup Missed', 'Order status', 'woocommerce');
    $new_order_statuses['wc-disposed'] = _x('Disposed/Not Collected', 'Order status', 'woocommerce');
    $new_order_statuses['wc-out-for-delivery'] = _x('Out for Delivery', 'Order status', 'woocommerce');
    $new_order_statuses['wc-delivery-failed'] = _x('Delivery Attempt Failed', 'Order status', 'woocommerce');
    $new_order_statuses['wc-retry-delivery'] = _x('Reattempting Delivery', 'Order status', 'woocommerce');
    $new_order_statuses['wc-delivered'] = _x('Delivered', 'Order status', 'woocommerce');
    $new_order_statuses['wc-on-way-venue'] = _x('On the Way to Venue', 'Order status', 'woocommerce');
    $new_order_statuses['wc-event-in-progress'] = _x('Event in Progress', 'Order status', 'woocommerce');
    $new_order_statuses['wc-preparing'] = _x('Preparing', 'Order status', 'woocommerce');

    return $new_order_statuses;
});

// Clear checkout session data on checkout page load
add_action('wp', 'clear_checkout_session_data');

function clear_checkout_session_data() {
    if (is_checkout() && !is_order_received_page()) {
        // Clear checkout fields session data
        WC()->session->set('checkout_fields', []);
        // Optionally clear other session data
        WC()->session->set('chosen_shipping_methods', []);
        WC()->session->set('chosen_payment_method', '');
    }
}

// Prevent WooCommerce from pre-filling fields for logged-in users
add_filter('woocommerce_checkout_get_value', function ($value, $input) {
    // Return empty value for all fields on checkout page load
    return '';
}, 10, 2);

add_filter('gettext', function ($translated_text, $text, $domain) {
    if ('Enter your address to view shipping options.' === $text && 'woocommerce' === $domain) {
        $translated_text = 'Enter address for fees';
    }
    return $translated_text;
}, 20, 3);
add_filter('woocommerce_cart_shipping_method_full_label', 'custom_change_shipping_label', 10, 2);

function custom_change_shipping_label($label, $method) {
    // Check if the shipping method is 'free_shipping'
    if ($method->id === 'free_shipping:15') {
        $label = 'Enter address for fees';
    }
    return $label;
}

add_filter('woocommerce_cart_no_shipping_available_html', function () {
    return 'We are currently unable to deliver to your address. Please check your details.';
});

add_filter('woocommerce_no_shipping_available_html', function () {
    return 'We are currently unable to deliver to your address. Please check your details.';
});

/* add_action('woocommerce_checkout_process', function () {
  if (!empty($_POST['billing_phone'])) {
  $phone = preg_replace('/\D/', '', $_POST['billing_phone']);
  if (strlen($phone) !== 9) {
  wc_add_notice(__('Please enter a valid 9-digit UAE phone number.'), 'error');
  }
  }
  }); */

function disable_shipping_calc_on_cart($show_shipping) {
    if (is_cart()) {
        return false;
    }
    return $show_shipping;
}

add_filter('woocommerce_cart_ready_to_calc_shipping', 'disable_shipping_calc_on_cart', 99);

// add_action('woocommerce_checkout_create_order', 'add_full_phone_number_to_order', 20, 2);
function add_full_phone_number_to_order($order, $data) {
    $full_number = ''; 
    if (isset($_POST['billing_phone']) && !empty($_POST['billing_phone'])) {
        $raw_phone = preg_replace('/\D+/', '', $_POST['billing_phone']);

        $dial_code = '';
        if (!empty($_POST['billing_dial_code'])) {
            $dial_code = preg_replace('/\D+/', '', $_POST['billing_dial_code']);
        } elseif (!empty($_POST['country_code'])) {
            $dial_code = preg_replace('/\D+/', '', $_POST['country_code']);
        }

        if ($dial_code && $raw_phone) {
            $full_number = '+' . $dial_code . ' ' . $raw_phone;
            $order->set_billing_phone($full_number);
        }
    }

    $user_id = $order->get_user_id();
    if ($user_id) {
        update_user_meta($user_id, 'address_verified_by_google', '1');
    }
}




/* * ********** */
add_filter('site_transient_update_plugins', 'disable_plugin_updates_for_customized_plugin');

function disable_plugin_updates_for_customized_plugin($value) {
    if (isset($value) && is_object($value)) {
        $plugin_file = 'international-telephone-input-with-flags-and-dial-codes/international-telephone-input-with-flags-and-dial-codes.php';

        if (isset($value->response[$plugin_file])) {
            unset($value->response[$plugin_file]);
        }
    }
    return $value;
}

function disable_woocommerce_password_strength_meter() {
    if (is_account_page()) {
        wp_dequeue_script('wc-password-strength-meter');
    }
}

add_action('wp_print_scripts', 'disable_woocommerce_password_strength_meter', 100);

add_filter('gform_field_validation', 'custom_email_domain_validation', 10, 4);

function custom_email_domain_validation($result, $value, $form, $field) {
    if ($field->type == 'email') {
        if (is_email($value)) {
            if (preg_match('/@[^@]+\.[a-zA-Z]{2,}$/', $value) === 0) {
                $result['is_valid'] = false;
                $result['message'] = 'Please enter a valid email address.';
            }
        } else {
            $result['is_valid'] = false;
            $result['message'] = 'Please enter a valid email address.';
        }
    }
    return $result;
}

add_filter('woocommerce_login_redirect', 'custom_login_redirect_to_orders', 10, 2);

function custom_login_redirect_to_orders($redirect, $user) {
    // Redirect to the Orders page
    $redirect = wc_get_account_endpoint_url('orders');
    return $redirect;
}

add_action('woocommerce_customer_reset_password', 'custom_redirect_after_password_reset');

function custom_redirect_after_password_reset($user) {
    // Redirect to Orders tab of My Account after password reset
    wp_safe_redirect(wc_get_account_endpoint_url('orders'));
    exit;
}

add_action('wp_logout', 'custom_logout_redirect_to_homepage', 10);

function custom_logout_redirect_to_homepage() {
    wp_redirect(home_url());
    exit();
}

// add_action('template_redirect', function () {
//     if (is_user_logged_in() && is_account_page() && !is_wc_endpoint_url()) {
//         wp_redirect(wc_get_account_endpoint_url('orders'));
//         exit;
//     }
// });

add_action('template_redirect', 'force_checkout_redirect_for_logged_in_users');

function force_checkout_redirect_for_logged_in_users() {
    // Redirect only if user is logged in and on login page with page ID 888
    if (is_user_logged_in() && is_page(888)) {
        wp_redirect(wc_get_checkout_url());
        exit;
    }
}

add_filter('gform_login_redirect', 'custom_gf_user_login_redirect', 10, 3);

add_filter('gform_user_registration_login_redirect_url', 'custom_gf_user_login_redirect', 10, 2);

function custom_gf_user_login_redirect($login_redirect, $sign_on) {
    // Check current page ID
    $current_page_id = get_queried_object_id();

    if ($current_page_id == 888) {
        return wc_get_checkout_url(); // Redirect to checkout
    }

    return wc_get_account_endpoint_url('orders'); // Redirect to My Account > Orders by default
}


add_filter('woocommerce_cart_calculate_shipping_address', function ($address, $cart) {
    if (!empty($cart->get_customer()->get_shipping_address_1())) {
        return $cart->get_customer()->get_shipping_address();
    }
    return $address;
}, 10, 2);

add_filter('wpo_wcpdf_myaccount_actions', 'custom_rename_invoice_label', 10, 2);

function custom_rename_invoice_label($actions, $order) {
    if (isset($actions['invoice'])) {
        $actions['invoice']['name'] = 'Download invoice';
    }
    return $actions;
}

/* * *********************************** */

// Add blocked dates field to product category
add_action('product_cat_add_form_fields', 'add_blocked_dates_field');
add_action('product_cat_edit_form_fields', 'edit_blocked_dates_field', 10, 2);

function add_blocked_dates_field() {
    ?>
    <div class="form-field term-blocked-dates-wrap">
        <label for="blocked_dates"><?php _e('Blocked Dates (YYYY-MM-DD, comma-separated)', 'woocommerce'); ?></label>
        <textarea name="blocked_dates" id="blocked_dates" rows="3"></textarea>
    </div>
    <?php
}

function edit_blocked_dates_field($term) {
    $blocked_dates = get_term_meta($term->term_id, 'blocked_dates', true);
    ?>
    <tr class="form-field term-blocked-dates-wrap">
        <th scope="row"><label for="blocked_dates"><?php _e('Blocked Dates (YYYY-MM-DD, comma-separated)', 'woocommerce'); ?></label></th>
        <td>
            <textarea name="blocked_dates" id="blocked_dates" rows="3"><?php echo esc_textarea($blocked_dates); ?></textarea>
        </td>
    </tr>
    <?php
}

// Save blocked dates for product category
add_action('created_product_cat', 'save_blocked_dates_field');
add_action('edited_product_cat', 'save_blocked_dates_field');

function save_blocked_dates_field($term_id) {
    if (isset($_POST['blocked_dates'])) {
        update_term_meta($term_id, 'blocked_dates', sanitize_textarea_field($_POST['blocked_dates']));
    }
}

// Add blocked dates field to Package Menu product edit page
add_action('woocommerce_product_options_general_product_data', 'add_blocked_dates_product_field');

function add_blocked_dates_product_field() {
    global $post;

    // Check if this is the specific Package Menu product (replace with actual ID or slug)
    if ($post->ID == 463 || $post->post_name == 'packages-vip') {
        woocommerce_wp_textarea_input([
            'id' => 'package_blocked_dates',
            'label' => __('Blocked Dates (YYYY-MM-DD, comma-separated)', 'woocommerce'),
            'description' => __('Enter dates to block for this package.', 'woocommerce'),
        ]);
    }
}

// Save blocked dates for Package Menu product
add_action('woocommerce_process_product_meta', 'save_blocked_dates_product_field');

function save_blocked_dates_product_field($post_id) {
    if (isset($_POST['package_blocked_dates'])) {
        update_post_meta($post_id, 'package_blocked_dates', sanitize_textarea_field($_POST['package_blocked_dates']));
    }
}

// Register AJAX handler
add_action('wp_ajax_get_blocked_dates', 'fetch_blocked_dates');
add_action('wp_ajax_nopriv_get_blocked_dates', 'fetch_blocked_dates');

function fetch_blocked_dates() {
    $blocked_dates = [];

    // Fetch blocked dates for Itemized Menu (Category)
    if ($_POST['page_type'] === 'itemized') {
        $term = get_term_by('slug', 'itemized-menu', 'product_cat');
        if ($term) {
            $category_dates = get_term_meta($term->term_id, 'blocked_dates', true);
            if (!empty($category_dates)) {
                $blocked_dates = array_map('trim', explode(',', $category_dates));
            }
        }
    }
    // Fetch blocked dates for Package Menu (Product)
    elseif ($_POST['page_type'] === 'package') {
        $product_id = 463; // Replace with actual Package Menu product ID
        $product_dates = get_post_meta($product_id, 'package_blocked_dates', true);
        if (!empty($product_dates)) {
            $blocked_dates = array_map('trim', explode(',', $product_dates));
        }
    }

    wp_send_json($blocked_dates);
}

/** Custom email triggers * */
// Register custom email classes
add_filter('woocommerce_email_classes', function ($emails) {
    $custom_emails = [
        'WC_Email_Ready_For_Pickup',
        'WC_Email_Picked_Up',
        'WC_Email_Pickup_Missed',
        'WC_Email_Disposed',
        'WC_Email_Out_For_Delivery',
        'WC_Email_Delivery_Failed',
        'WC_Email_Retry_Delivery',
        'WC_Email_Delivered',
        'WC_Email_On_Way_Venue',
        'WC_Email_Preparing'
    ];

    foreach ($custom_emails as $email_class) {
        require_once get_template_directory() . '/woocommerce/emails/' . $email_class . '.php';
        $emails[$email_class] = new $email_class();
    }

    return $emails;
});

// Trigger the emails on order status change
add_action('woocommerce_order_status_changed', function ($order_id, $old_status, $new_status) {
    $status_to_email = [
        'ready-for-pickup' => 'WC_Email_Ready_For_Pickup',
        'picked-up' => 'WC_Email_Picked_Up',
        'pickup-missed' => 'WC_Email_Pickup_Missed',
        'disposed' => 'WC_Email_Disposed',
        'out-for-delivery' => 'WC_Email_Out_For_Delivery',
        'delivery-failed' => 'WC_Email_Delivery_Failed',
        'retry-delivery' => 'WC_Email_Retry_Delivery',
        'delivered' => 'WC_Email_Delivered',
        'on-way-venue' => 'WC_Email_On_Way_Venue',
        'preparing' => 'WC_Email_Preparing'
    ];

    if (isset($status_to_email[$new_status])) {
        $email_class = $status_to_email[$new_status];
        $mailer = WC()->mailer();
        if (isset($mailer->emails[$email_class])) {
            $mailer->emails[$email_class]->trigger($order_id);
        }
    }
}, 10, 3);
// Save the Ready for Pickup timestamp
add_action('woocommerce_order_status_ready-for-pickup', function ($order_id) {
    update_post_meta($order_id, '_ready_for_pickup_time', current_time('timestamp'));
});

/* * Elementor working new  header* */

function custom_header_shortcode() {
    ob_start();
    ?>
    <header id="header" class="custom-header">
        <div class="container d-flex align-items-center justify-content-between">
            <div class="logo">
                <a href="<?php echo esc_url(home_url()); ?>">
                    <img src="/app/uploads/2025/03/CC-Logo.svg" alt="Logo">
                </a>
            </div>

            <?php if (!wp_is_mobile()) : ?>
                <?php echo do_shortcode('[mega_menu]'); ?>

                <nav class="main-nav d-none">
                    <?php
                    wp_nav_menu(array(
                        'theme_location' => 'header_menu',
                        'container' => false,
                        'menu_class' => 'nav-menu',
                    ));
                    ?>
                </nav>
            <?php endif; ?>

            <div class="icon-hamburger-wrapper">
                <div class="header-right">
                    <div class="cart-icon-wrapper mobile-header-icon-wrapper">
                        <a href="<?php echo esc_url(wc_get_cart_url()); ?>" class="cart-icon">
                            <span class="cart-icon-image">
                                <img src="/app/uploads/2025/04/Vector-1.svg" alt="cart-icon">
                            </span>
                            <?php
                            $count = WC()->cart->get_cart_contents_count();
                            $class = ($count == 0) ? "d-none" : "";
                            ?>
                            <span class="cart-count <?php echo esc_attr($class); ?>"><?php echo esc_html($count); ?></span>      
                        </a>
                    </div>

                    <!-- <a class="mobile-header-acount mobile-header-icon-wrapper" href="/my-account/orders/"> -->
<?php $login_url = (is_user_logged_in()) ? '/my-account/orders/' : '/login/'; ?>
                    <a class="mobile-header-acount mobile-header-icon-wrapper" href="<?php echo esc_url( home_url($login_url) ); ?>">
                        <?php
                        if (is_user_logged_in()) :
                            $current_user = wp_get_current_user();
                            $name_parts = explode(' ', trim($current_user->display_name));
                            $initials = '';
                            foreach ($name_parts as $part) {
                                $initials .= strtoupper($part[0]);
                            }
                            $initials = substr($initials, 0, 2);
                            ?>
                            <div class="user-initials-icon"><?php echo esc_html($initials); ?></div>
                        <?php else : ?>
                            <!-- Guest user icon SVG -->
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
                            <path d="M21.6484 19.875C20.2206 17.4065 18.0203 15.6365 15.4525 14.7975C16.7226 14.0414 17.7094 12.8892 18.2614 11.5179C18.8134 10.1467 18.8999 8.63211 18.5078 7.20688C18.1157 5.78165 17.2666 4.52454 16.0909 3.6286C14.9151 2.73266 13.4778 2.24744 11.9996 2.24744C10.5215 2.24744 9.08414 2.73266 7.90842 3.6286C6.73269 4.52454 5.88358 5.78165 5.49146 7.20688C5.09935 8.63211 5.18592 10.1467 5.73788 11.5179C6.28984 12.8892 7.27668 14.0414 8.54683 14.7975C5.97902 15.6356 3.77871 17.4056 2.35089 19.875C2.29853 19.9604 2.2638 20.0554 2.24875 20.1544C2.2337 20.2534 2.23863 20.3544 2.26326 20.4515C2.28789 20.5486 2.33171 20.6397 2.39214 20.7196C2.45257 20.7995 2.52838 20.8664 2.6151 20.9165C2.70183 20.9666 2.79771 20.9988 2.89709 21.0113C2.99647 21.0237 3.09733 21.0161 3.19373 20.989C3.29012 20.9618 3.3801 20.9156 3.45835 20.8531C3.5366 20.7906 3.60154 20.713 3.64933 20.625C5.41558 17.5725 8.53746 15.75 11.9996 15.75C15.4618 15.75 18.5837 17.5725 20.35 20.625C20.3977 20.713 20.4627 20.7906 20.5409 20.8531C20.6192 20.9156 20.7092 20.9618 20.8056 20.989C20.902 21.0161 21.0028 21.0237 21.1022 21.0113C21.2016 20.9988 21.2975 20.9666 21.3842 20.9165C21.4709 20.8664 21.5467 20.7995 21.6072 20.7196C21.6676 20.6397 21.7114 20.5486 21.736 20.4515C21.7607 20.3544 21.7656 20.2534 21.7505 20.1544C21.7355 20.0554 21.7008 19.9604 21.6484 19.875ZM6.74964 8.99999C6.74964 7.96164 7.05755 6.9466 7.63443 6.08324C8.21131 5.21989 9.03124 4.54698 9.99056 4.14962C10.9499 3.75226 12.0055 3.64829 13.0239 3.85086C14.0423 4.05344 14.9777 4.55345 15.712 5.28768C16.4462 6.0219 16.9462 6.95736 17.1488 7.97576C17.3513 8.99416 17.2474 10.0498 16.85 11.0091C16.4527 11.9684 15.7797 12.7883 14.9164 13.3652C14.053 13.9421 13.038 14.25 11.9996 14.25C10.6077 14.2485 9.27322 13.6949 8.28898 12.7107C7.30473 11.7264 6.75113 10.3919 6.74964 8.99999Z" fill="#1C2327"></path>
                            </svg>
                        <?php endif; ?>
                    </a>

                    <a class="order-online-btn d-none d-lg-block" href="/all-menus-and-packages/">Order online</a>
                </div>

                <div class="menu-button d-xl-none text-center mobile-header-icon-wrapper mobile-hamburger-icon">
                    <img src="/app/uploads/2025/04/Vector-2.svg" alt="hamburger-icon">
                </div>
            </div>

            <div class="menu-wrap d-block d-xl-none">
                <a href="<?php echo esc_url(home_url()); ?>">
                    <img src="/app/uploads/2025/03/CC-Logo.svg" alt="Logo">
                </a>
                <div class="mobile-menu-close"></div>
                <div class="menu-full-wrapper">
                    <div class="menu-full-wrapper-inner">
                    <div class="menu-sidebar">
                        <?php
                        wp_nav_menu(array(
                            'menu' => 'main-menu',
                            'theme_location' => '__no_such_location',
                            'menu_id' => 'top-nav',
                            'menu_class' => 'menu-bar-wrapper',
                            'container' => '',
                            'fallback_cb' => false
                        ));
                        ?>
                    </div>
                    <a class="order-online-btn" href="/all-menus-and-packages/">Order online</a>
                    </div>

                    <?php if (is_user_logged_in()) : ?>
                        <a class="mobile-logout-wrapper" href="<?php echo wp_logout_url(home_url()); ?>"><img src="/app/uploads/2025/05/SignOut.svg"> <div>Logout</div></a>
                    <?php endif; ?>

                </div>
            </div>
        </div>
    </header>
    <?php
    return ob_get_clean();
}

add_shortcode('custom_header', 'custom_header_shortcode');

// Register custom email class
add_filter('woocommerce_email_classes', function ($emails) {
    require_once get_template_directory() . '/woocommerce/emails/class-wc-email-customer-cancelled-order.php';
    $emails['WC_Email_Customer_Cancelled_Order'] = new WC_Email_Customer_Cancelled_Order_Customized();
    return $emails;
});
// Trigger custom email on order status change to 'cancelled'
/* add_action( 'woocommerce_order_status_cancelled', function( $order_id ) {
  $mailer = WC()->mailer();
  $email = $mailer->emails['WC_Email_Customer_Cancelled_Order'];
  if ( $email ) {
  $email->trigger( $order_id );
  }
  }); */

// add_action('gform_after_submission_2', 'send_custom_woocommerce_email', 10, 2);

function send_custom_woocommerce_email($entry, $form) {
    $first_name = rgar($entry, '9');
    $last_name = rgar($entry, '10');
    $email = rgar($entry, '5');

    $username = sanitize_user(strtolower($first_name . '.' . $last_name));
    $full_name = ucwords(strtolower($first_name . ' ' . $last_name));

    ob_start();
    wc_get_template('emails/customer-new-account.php', array(
        'user_login' => $username,
        'user_email' => $email,
        'full_name' => $full_name,
    ));
    $message = ob_get_clean();

    $email_styles = apply_filters('woocommerce_email_styles', '');

    $styled_message = '<style>' . $email_styles . '</style>' . $message;

    $headers = array('Content-Type: text/html; charset=UTF-8');

    wp_mail($email, 'Welcome to Capital Catering Plus', $styled_message, $headers);
}

/* add_action( 'user_register', 'send_admin_new_user_email_on_register', 10, 1 );
  function send_admin_new_user_email_on_register( $user_id ) {
  $user_info   = get_userdata( $user_id );
  $first_name  = get_user_meta( $user_id, 'first_name', true );
  $last_name   = get_user_meta( $user_id, 'last_name', true );
  $email       = $user_info->user_email;

  $admin_email = get_option( 'admin_email' );

  ob_start();
  wc_get_template( 'emails/admin-custom-new-user.php', array(
  'first_name' => $first_name,
  'last_name'  => $last_name,
  'email'      => $email,
  ) );
  $message = ob_get_clean();

  $email_styles    = apply_filters( 'woocommerce_email_styles', '' );
  $styled_message  = '<style>' . $email_styles . '</style>' . $message;
  $headers         = array( 'Content-Type: text/html; charset=UTF-8' );

  wp_mail( $admin_email, 'New customer registered on Capital Catering Plus', $styled_message, $headers );
  } */

add_action('gform_after_submission_2', 'handle_gravity_form_user_registration', 20, 2);

function handle_gravity_form_user_registration($entry, $form) {
    $first_name = rgar($entry, '9');
    $last_name = rgar($entry, '10');
    $email = rgar($entry, '5');

    $user = get_user_by('email', $email);
    if ($user) {
        update_user_meta($user->ID, 'first_name', $first_name);
        update_user_meta($user->ID, 'last_name', $last_name);
    }
}

add_action('user_register', 'send_admin_new_user_notification_from_wp', 10, 1);

function send_admin_new_user_notification_from_wp($user_id) {
    $user = get_userdata($user_id);

    $first_name = get_user_meta($user_id, 'first_name', true);
    $last_name = get_user_meta($user_id, 'last_name', true);

    $full_name = trim($first_name . ' ' . $last_name);
    if (empty($full_name)) {
        $full_name = $user->display_name;
    }

    send_custom_admin_user_email($full_name, $user->user_email);
}

function send_custom_admin_user_email($name, $email) {
    $admin_email = get_option('admin_email');

    ob_start();
    wc_get_template('emails/admin-custom-new-user.php', array(
        'name' => $name,
        'email' => $email,
    ));
    $message = ob_get_clean();

    $email_styles = apply_filters('woocommerce_email_styles', '');
    $styled_message = '<style>' . $email_styles . '</style>' . $message;

    $headers = array('Content-Type: text/html; charset=UTF-8');

    wp_mail($admin_email, 'New customer registered on Capital Catering Plus', $styled_message, $headers);
}

add_filter('wp_send_new_user_notification_to_admin', '__return_false');

add_action('woocommerce_email_footer', 'capital_catering_remove_get_the_app_ad', 8);

function capital_catering_remove_get_the_app_ad() {
    $mailer = WC()->mailer()->get_emails();
    $object = $mailer['WC_Email_New_Order'];
    remove_action('woocommerce_email_footer', array($object, 'mobile_messaging'), 9);
}

add_action('phpmailer_init', 'custom_smtp_setup');

function custom_smtp_setup($phpmailer) {
    $phpmailer->isSMTP();
    $phpmailer->Host = 'smtp.office365.com';
    $phpmailer->SMTPAuth = true;
    $phpmailer->Port = 587;
    $phpmailer->Username = 'noreply@capitalcateringplus.ae';
    $phpmailer->Password = 'Windowsupdate@2025';
    $phpmailer->SMTPSecure = 'tls';
    $phpmailer->From = 'noreply@capitalcateringplus.ae';
    $phpmailer->FromName = 'Capital Catering +';

    $phpmailer->SMTPDebug = 2; // Show debug info
    $phpmailer->Debugoutput = function ($str, $level) {
        error_log("SMTP DEBUG: $str");
    };
}

add_action('woocommerce_checkout_update_user_meta', 'save_full_phone_number_to_user_meta', 20, 2);

function save_full_phone_number_to_user_meta($customer_id, $posted) {

    if (!empty($_POST['billing_phone'])) {
        // Sanitize phone
        $raw_phone = preg_replace('/\D+/', '', $_POST['billing_phone']);

        // Check dial code or fallback to country_code
        $dial_code = '';
        if (!empty($_POST['billing_dial_code'])) {
            $dial_code = preg_replace('/\D+/', '', $_POST['billing_dial_code']); // Remove '+' if present
        } elseif (!empty($_POST['country_code'])) {
            $dial_code = preg_replace('/\D+/', '', $_POST['country_code']);
        }

        // Save only if both exist
        if ($dial_code && $raw_phone) {
            $full_number = '+' . $dial_code . ' ' . $raw_phone;
            update_user_meta($customer_id, 'billing_phone', $full_number);
        }
    }
}


function enqueue_cart_intercept_script() {
    if ( is_page(['itemized-menu-new', 'packages-vip']) ) {
        wp_enqueue_script('custom-cart-guard', get_template_directory_uri() . '/assets/js/cart-guard.js', ['jquery'], null, true);
        wp_localize_script('custom-cart-guard', 'cartGuardData', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'cart_has_items' => WC()->cart->get_cart_contents_count() > 0,
        ]);
    }
}
add_action('wp_enqueue_scripts', 'enqueue_cart_intercept_script');
add_action('wp_ajax_clear_cart_on_popup_confirm', 'clear_cart_on_popup_confirm');
add_action('wp_ajax_nopriv_clear_cart_on_popup_confirm', 'clear_cart_on_popup_confirm');

function clear_cart_on_popup_confirm() {
    WC()->cart->empty_cart();
    wp_send_json_success();
}

/** Save order details in CSV for SAP **/
add_action('woocommerce_thankyou', 'export_order_to_sap_csv', 20, 1);

function export_order_to_sap_csv($order_id) {
    if (!$order_id) return;

    $order = wc_get_order($order_id);
    if (!$order) return;

    $csv_file = ABSPATH . 'sap-export.csv';
    $is_new_file = !file_exists($csv_file);

    $adyen_data = $order->get_meta('_adyen_notifications');
    $adyen_additional = isset($adyen_data['additionalData']) ? $adyen_data['additionalData'] : [];

    $invoice_meta = $order->get_meta('_wcpdf_invoice_number_data');
    $invoice_number = is_array($invoice_meta) && isset($invoice_meta['formatted_number']) ? $invoice_meta['formatted_number'] : '';

    $masked_card = isset($adyen_additional['paymentMethod']) && isset($adyen_additional['cardSummary']) 
        ? $adyen_additional['paymentMethod'] . ' •••• ' . $adyen_additional['cardSummary'] 
        : '';
	$payment_method = $adyen_additional['paymentMethod'];
    $subtotal = $order->get_subtotal();
    $tax_total = $order->get_total_tax();
    $tax_rate = '5%';
	$order_status = $order->get_status();
	$payment_status = $order_status === 'processing' ? 'Confirmed' : ucfirst($order_status);

    $row = [
        $order->get_id(), // Order Id
        $invoice_number, // Invoice Number
        $order->get_formatted_billing_full_name(), // Customer Name
        $order->get_billing_phone(), // Customer Contact
        $order->get_billing_email(), // Customer Email
        $order->get_customer_id(), // Customer Numeric Code
        $adyen_data['pspReference'] ?? '', // PSP Reference
        $adyen_additional['acquirerReference'] ?? '', // ARN
        $order->get_date_created()->format('F j, Y'), // Date
        $order->get_date_created()->format('g:i A'), // Time
        $order->get_currency(), // Currency
        $payment_method, // Payment Method
        $subtotal, // Tax Base Amount
        '', // VAT Code
        $tax_rate, // Tax Rate
        $tax_total, // Output Tax
        $order->get_total(), // Total Amount
        '', '', '', // Markup, Scheme Fees, Interchange
        $payment_status, // Payment Status
        '', // Payment Fees
        '', // VAT Details (if any)
        $order->get_discount_total(), // Discount
        'Abu Dhabi', // Business Place
        '', // Masked Card Info
    ];

    $file = fopen($csv_file, 'a');

    if ($is_new_file) {
        fputcsv($file, [
            'Order Id', 'Invoice Number', 'Customer Name', 'Customer Contact', 'Customer Email',
            'Customer Numeric Code Generated by Woocommerce', 'PSP Reference Number', 'ARN (Acquirer Reference Number)',
            'Date', 'Time', 'Currency Code', 'Payment Method', 'Tax Base Amount', 'Tax/ Vat Code',
            'Tax Rate', 'Output Tax', 'Total Amount', 'Markup (NC)', 'Scheme Fees (NC)', 'Interchange (NC)',
            'Payment Status', 'Payment Fees (NC)', 'Customer VAT Details (If applicable)',
            'Discount If Applicable', 'Business Place', 'Customer Payment Method info (Masked)'
        ]);
    }

    fputcsv($file, $row);
    fclose($file);
}
add_filter('woocommerce_address_to_edit', function ($address, $load_address) {
    if ($load_address === 'billing') {
        $address['billing_company'] = array(
            'label'    => __('Company name', 'woocommerce'),
            'required' => 0,
            'type'     => 'text',
            'class'    => array('form-row-wide'),
        );
        $address['billing_vat'] = array(
            'label'    => __('VAT', 'woocommerce'),
            'required' => 0,
            'type'     => 'text',
            'class'    => array('form-row-wide'),
        );
    }
    return $address;
}, 10, 2);


add_action('woocommerce_customer_save_address', function ($user_id, $load_address) {
    if ($load_address === 'billing') {

        // Save billing_company
        if (isset($_POST['billing_company'])) {
            update_user_meta($user_id, 'billing_company', sanitize_text_field($_POST['billing_company']));
        }
        // Save billing_vat
        if (isset($_POST['billing_vat'])) {
            update_user_meta($user_id, 'billing_vat', sanitize_text_field($_POST['billing_vat']));
        }

        if (isset($_POST['billing_dial_code']) && isset($_POST['billing_phone'])) {
            $dial_code = sanitize_text_field($_POST['billing_dial_code']);
            $phone = sanitize_text_field($_POST['billing_phone']);
            
            $full_phone = $dial_code . ' ' . $phone; 
        
            update_user_meta($user_id, 'billing_phone', $full_phone);
        }
        
    }
}, 10, 2);


function my_new_customer_username( $username, $email, $new_user_args, $suffix ) {
    return $email;
}
add_filter( 'woocommerce_new_customer_username', 'my_new_customer_username', 10, 4 );


// Remove version meta tags from <head>
remove_action('wp_head', 'wp_generator');
add_filter('woocommerce_generator_tag', '__return_empty_string');

/**
 * Restrict REST API access for non-admins and lock WooCommerce endpoints.
 */

// Global authentication filter
add_filter( 'rest_authentication_errors', function( $result ) {
    // Respect existing errors
    if ( true === $result || is_wp_error( $result ) ) {
        return $result;
    }

    // Block all REST access for unauthenticated users
    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'rest_forbidden',
            __( 'You do not have sufficient permission to access this endpoint.', 'capital-catering' ),
            [ 'status' => 403 ]
        );
    }

    // Get current REST route
    $route = untrailingslashit( $_SERVER['REQUEST_URI'] ); // normalize trailing slash

    // Match both /users and /users/{id}
    if ( preg_match( '#/wp-json/wp/v2/users(?:/[\d]+)?#', $route ) ) {
        // Only allow administrators
        if ( ! current_user_can( 'manage_options' ) ) {
            return new WP_Error(
                'rest_cannot_access',
                __( 'You do not have sufficient permission to access this endpoint.', 'your-text-domain' ),
                [ 'status' => 403 ]
            );
        }
    }

    /**
     * Restrict WooCommerce v1/v2 endpoints
     * (does not affect /wc/store/ endpoints used by cart/checkout)
     */
    if ( preg_match( '#/wp-json/wc/(v1|v2)#', $route ) ) {
        if ( ! current_user_can( 'manage_options' ) ) {
            return new WP_Error(
                'rest_forbidden',
                __( 'You do not have sufficient permission to access this endpoint.', 'capital-catering' ),
                [ 'status' => rest_authorization_required_code() ]
            );
        }
    }

    // We return null here so WordPress continues the request normally
    return null;
});

function remove_wp_update_notice() {
    if (is_admin()) {
        remove_action('admin_notices', 'update_nag', 3);
    }
}
add_action('admin_head', 'remove_wp_update_notice');

function remove_company_from_both_address($address, $order) {
    if (isset($address['company'])) {
        unset($address['company']);
    }
    return $address;
}
add_filter('woocommerce_order_formatted_billing_address', 'remove_company_from_both_address', 10, 2);
add_filter('woocommerce_order_formatted_shipping_address', 'remove_company_from_both_address', 10, 2);

function custom_pdf_billing_address_format($address_html, $document) {
    $order = $document->order;

    $country_code = $order->get_billing_country();
    $state_code = $order->get_billing_state();

    $countries = WC()->countries->get_countries();
    $country_name = isset($countries[$country_code]) ? $countries[$country_code] : $country_code;

    $states = WC()->countries->get_states($country_code);
    $state_name = isset($states[$state_code]) ? $states[$state_code] : $state_code;

    // You can rebuild the address manually like this:
    $custom_address = array_filter([
        $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
        $order->get_billing_phone(),
        $order->get_billing_email(),
        $order->get_billing_address_1(),
        $order->get_billing_address_2(),
        $order->get_billing_city() . ', ' . $order->get_billing_postcode(),
        $state_name,
        $country_name,
    ]);

    // Convert array to <br> separated string
    $address_html = implode('<br>', array_map('esc_html', $custom_address));

    return $address_html;
}
add_filter('wpo_wcpdf_billing_address', 'custom_pdf_billing_address_format', 10, 2);


add_action('gform_after_submission', 'handle_newsletter_subscription_dynamic', 10, 2);
function handle_newsletter_subscription_dynamic($entry, $form) {

    global $wpdb;

    $forms_config = [
        6 => [ // Main form ID
            'subscribe_field' => '8.1',
            'email_field'     => '5',
            'newsletter_form' => 5,
            'newsletter_email_field' => '1',
        ],
        7 => [ // Another main form
            'subscribe_field' => '8.1',
            'email_field'     => '5',
            'newsletter_form' => 5,
            'newsletter_email_field' => '1',
        ],
        3 => [ // Another main form
            'subscribe_field' => '8.1',
            'email_field'     => '5',
            'newsletter_form' => 5,
            'newsletter_email_field' => '1',
        ],
    ];

    $form_id = $form['id'];

    // Skip if not a subscribed form
    if (!isset($forms_config[$form_id])) {
        return;
    }

    $config = $forms_config[$form_id];
    $subscribe = rgar($entry, $config['subscribe_field']);

    if ($subscribe === 'Subscribe to newsletter') {
        $email = rgar($entry, $config['email_field']);

        // Create Gravity Form newsletter entry
        $result = GFAPI::add_entry([
            'form_id' => $config['newsletter_form'],
            $config['newsletter_email_field'] => $email,
        ]);

        // If success, insert to custom DB table
        if (!is_wp_error($result)) {
            $table_name = $wpdb->prefix . 'cc_newsletter_subscribers';
            $wpdb->insert(
                $table_name,
                [
                    'email' => $email,
                    'date_subscribed' => current_time('mysql'),
                ]
            );
        }
    }
}

/**
 * Custom shipping rate adjustments based on coupon type.
 * This function handles the scenario:
 * - Hides Flat Rate if any "free shipping" coupon is applied.
 *
 * @param array $rates Shipping rates for the package.
 * @param array $package The package information.
 * @return array Modified shipping rates.
 */
add_filter('woocommerce_package_rates', 'custom_shipping_coupon_logic', 10, 2);
function custom_shipping_coupon_logic($rates, $package) {
    // Check if a free shipping coupon is applied
    $has_free_shipping_coupon = false;

    if ( WC()->cart && WC()->cart->get_applied_coupons() ) {
        foreach ( WC()->cart->get_applied_coupons() as $coupon_code ) {
            $coupon = new WC_Coupon($coupon_code);
            if ( $coupon->get_free_shipping() ) {
                $has_free_shipping_coupon = true;
                break;
            }
        }
    }

    // If free shipping is active, hide all flat rate options and set free shipping cost to 0
    if ( $has_free_shipping_coupon ) {
        foreach ( $rates as $rate_id => $rate ) {
            if ( strpos( $rate->method_id, 'flat_rate' ) !== false ) {
                unset( $rates[ $rate_id ] );
            }
            if ( 'free_shipping' === $rate->method_id ) {
                $rates[ $rate_id ]->label = wc_price(0);
                $rates[ $rate_id ]->cost = 0;
            }
        }
    }

    return $rates;
}

add_action('woocommerce_customer_save_address', 'block_address_save_if_not_google_verified', 10, 3);
function block_address_save_if_not_google_verified($user_id, $load_address) {
    if (!in_array($load_address, ['shipping'])) return;

    update_user_meta($user_id, 'address_verified_by_google', '1');
    
}

add_action('admin_head', function() {
    ?>
    <style>
    .components-notices__snackbar {
        display: none !important;
    }
    th#taxonomy-allergens
    {
        width: 4.5em;
    }
    </style>
    <?php
});

/**
 * Check if a free shipping coupon is applied to an order and return the coupon code or false.
 * @param WC_Order $order
 * @return string|false
 */
function order_has_free_shipping_coupon($order) {
    if (!$order || !is_a($order, 'WC_Order')) {
        return false;
    }
    foreach ($order->get_coupon_codes() as $coupon_code) {
        $coupon = new WC_Coupon($coupon_code);
        if ($coupon->get_free_shipping()) {
            return $coupon_code;
        }
    }
    return false;
}

/**
 * Check if the given order contains a package menu product.
 *
 * @param WC_Order $order
 * @return bool
 */
function order_has_package_menu($order) {
    if (!$order || !is_a($order, 'WC_Order')) {
        return false;
    }
    $package_menu_products = array(463); // Add more product IDs as needed
    foreach ($order->get_items() as $item) {
        $product_id = $item->get_product_id();
        if (in_array($product_id, $package_menu_products)) {
            return true;
        }
    }
    return false;
}

add_filter('woocommerce_country_locale_field_selectors', function($fields) {
    if (isset($fields['postcode']) || isset($fields['state'])) {
        unset($fields['address_1']);        
        unset($fields['address_2']);
        unset($fields['state']);
        unset($fields['postcode']);
    }
    return $fields;
});

add_action('wp_ajax_check_email_exists', 'check_email_exists_callback');
add_action('wp_ajax_nopriv_check_email_exists', 'check_email_exists_callback');

function check_email_exists_callback() {
    
    if (is_user_logged_in()) {
        wp_send_json([
            'exists' => false
        ]);
    }
    $email = sanitize_email($_POST['email']);
    $user = get_user_by('email', $email);

    wp_send_json([
        'exists' => $user ? true : false
    ]);
}

add_filter('gform_replace_merge_tags', function($text, $form, $entry) {
    $text = str_replace('{site_name}', get_bloginfo('name'), $text);
    $text = str_replace('{site_url}', get_bloginfo('url'), $text);
    return $text;
}, 10, 3);

add_filter('gform_confirmation_2', function ($confirmation, $form, $entry) {
    $email_field_id = 5;
    $email = rgar($entry, $email_field_id);
    if ($email) {
        $encoded = base64_encode($email);
        return [
            'redirect' => get_site_url() . '/verify-your-email/?e=' . urlencode($encoded)
        ];
    }
    return $confirmation;
}, 10, 3);


/**
 * Shortcode to display the resend activation Gravity Form pre-filled with the user's email address from the URL.
 *
 * @return string Gravity Form shortcode output or error message HTML.
 */
add_shortcode('resend_activation_wrapper', function () {
    $encoded = $_GET['e'] ?? '';
    $email = base64_decode($encoded, true);

    if ($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return do_shortcode('[gravityform id="8" title="false" description="false" ajax="true" field_values="user_email=' . esc_attr($email) . '"]');
    } else {
        return '<p class="invalid-entry">Invalid or missing email address. Please check your link or try registering again.</p>';
    }
});

/**
 * Resend activation email after Gravity Form 8 submission for users with pending activation
 *
 * @param array $entry The entry object from the form submission.
 * @param array $form  The form object.
 */
add_action( 'gform_after_submission_8', function( $entry, $form ) {
    $email = rgar( $entry, '1' );
    
    $gf_user_registration = gf_user_registration();

    // Check if a pending activation exists for the given email
    $is_pending = $gf_user_registration->pending_activation_exists( 'user_email', $email );

    if ( $is_pending ) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'signups';

        // Get the pending signup data from the signups table
        $signup = $wpdb->get_row( $wpdb->prepare( 
            "SELECT * FROM {$table_name} WHERE user_email = %s AND active = 0 ORDER BY registered DESC LIMIT 1", 
            $email 
        ) );

        if ( $signup ) {
            // Get the activation key from the signup
            $activation_key = $signup->activation_key;

            // Get the signup meta to find the entry ID
            $meta = maybe_unserialize( $signup->meta );
            $entry_id = rgar( $meta, 'lead_id' );
            
            if ( $entry_id ) {
                // Get the entry and form data
                $entry_data = GFAPI::get_entry( $entry_id );
                $form_data = GFAPI::get_form( $entry_data['form_id'] );

                if ( $entry_data && $form_data ) {
                    // Get the feed configuration
                    $feed = $gf_user_registration->get_filtered_single_submission_feed( $entry_data, $form_data );
                    
                    if ( $feed ) {
                        // Send the activation email using the signup data
                        require_once( $gf_user_registration->get_base_path() . '/includes/signups.php' );
                        GFUserSignups::prep_signups_functionality();
                        
                        // Create a signup object and send the notification
                        $signup_obj = new GFSignup( $signup );
                        
                        // Send the activation notification
                        GFAPI::send_notifications( $form_data, $entry_data, 'gfur_user_activation' );
                    }
                }
            }
        }
    }
}, 10, 2 );

/**
 * Helper: Get parent grouped IDs
 */
function wc_get_product_grouped_parent_ids($product_id) {
    global $wpdb;
    $parent_ids = $wpdb->get_col($wpdb->prepare(
        "
        SELECT p.ID
        FROM {$wpdb->posts} p
        LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE pm.meta_key = '_children'
        AND pm.meta_value LIKE %s
        ",
        '%' . $wpdb->esc_like($product_id) . '%'
    ));
    return $parent_ids;
}

/**
 * Add Pickup Instructions Field to WooCommerce Store Address
 */

 add_filter( 'woocommerce_general_settings', 'add_pickup_instructions_field' );
 function add_pickup_instructions_field( $settings ) {
 
    // New custom field for pickup instructions
    $new_field = array(
        'title'    => __( 'Pickup Instructions', 'woocommerce' ),
        'desc'     => __( "Enter a short instruction for local pickup, e.g., 'Collect from front desk'.", 'woocommerce' ),
        'id'       => 'woocommerce_store_pickup_instructions',
        'type'     => 'text',
        'desc_tip' => true,
    );

    // Ploting the new field after 'Postcode/ZIP'
    $position_key = 'woocommerce_store_postcode';
    $new_settings = array();
    
    foreach ( $settings as $key => $setting ) {
        $new_settings[] = $setting;
        if ( isset( $setting['id'] ) && $setting['id'] === $position_key ) {
            $new_settings[] = $new_field;
        }
    }

    // Fallback: If the postcode field wasn't found, adding the field to the end.
    if ( count( $new_settings ) === count( $settings ) ) {
        $new_settings[] = $new_field;
    }

    return $new_settings;
}

// Ensure cookies are set with secure attributes
add_filter('woocommerce_set_cookie_options', function ($options) {
    $options['secure'] = true;
    $options['httponly'] = true;
    $options['samesite'] = 'Strict';
    return $options;
});

/**
 * Add dataLayer purchase event script on order-received (thank you) page
 */
add_action('wp_footer', 'add_purchase_datalayer_script');

function add_purchase_datalayer_script() {
    // Only on order-received page
    if (!is_order_received_page()) {
        return;
    }

    // Get order ID from URL
    $order_id = absint(get_query_var('order-received'));
    if (!$order_id) {
        // Fallback: Try to get from global $wp
        global $wp;
        if (isset($wp->query_vars['order-received'])) {
            $order_id = absint($wp->query_vars['order-received']);
        }
    }
    
    if (!$order_id) {
        return;
    }

    // Get order object
    $order = wc_get_order($order_id);
    if (!$order) {
        return;
    }

    // Verify order key from URL for security
    $order_key = isset($_GET['key']) ? sanitize_text_field($_GET['key']) : '';
    if ($order_key && $order->get_order_key() !== $order_key) {
        return;
    }

    // Only track if payment is completed/processing
    if (!$order->is_paid()) {
        return;
    }

    // Get order items
    $items = array();
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        if (!$product) {
            continue;
        }

        // Get product category
        $categories = wp_get_post_terms($product->get_id(), 'product_cat');
        $category = !empty($categories) ? $categories[0]->name : '';

        // Get variant if it's a variable product
        $variant = '';
        if ($item->get_variation_id()) {
            $variation = wc_get_product($item->get_variation_id());
            if ($variation) {
                $variation_attributes = $variation->get_variation_attributes();
                if (!empty($variation_attributes)) {
                    $variant = implode(', ', array_values($variation_attributes));
                }
            }
        }

        $items[] = array(
            'item_id' => (string) $product->get_id(),
            'item_name' => $item->get_name(),
            'item_brand' => 'Capital Catering Plus',
            'item_category' => $category,
            'item_variant' => $variant,
            'price' => (float) $item->get_subtotal() / $item->get_quantity(), // Price per unit
            'quantity' => (int) $item->get_quantity()
        );
    }

    // Get delivery/shipping fee (check for custom delivery_fee meta first, then shipping total)
    $delivery_fee = (float) $order->get_meta('_delivery_fee');
    if ($delivery_fee <= 0) {
        $delivery_fee = (float) $order->get_shipping_total();
    }

    // Get coupon code
    $coupon_codes = $order->get_coupon_codes();
    $coupon_code = !empty($coupon_codes) ? implode(', ', $coupon_codes) : '';

    // Build dataLayer script
    ?>
    <script>
        window.dataLayer = window.dataLayer || [];
        dataLayer.push({
            event: "purchase",
            ecommerce: {
                transaction_id: "<?php echo esc_js($order->get_id()); ?>",
                affiliation: "Capital Catering Plus Website",
                currency: "<?php echo esc_js($order->get_currency()); ?>",
                value: <?php echo number_format((float) $order->get_total(), 2, '.', ''); ?>,
                tax: <?php echo number_format((float) $order->get_total_tax(), 2, '.', ''); ?>,
                shipping: <?php echo number_format($delivery_fee, 2, '.', ''); ?>,
                coupon: "<?php echo esc_js($coupon_code); ?>",
                items: <?php echo json_encode($items); ?>
            }
        });
    </script>
    <?php
}

add_action('wp_ajax_ccp_get_cart_details', 'ccp_get_cart_details');
add_action('wp_ajax_nopriv_ccp_get_cart_details', 'ccp_get_cart_details');

function ccp_get_cart_details() {
    // Ensure cart is loaded
    if (null === WC()->cart) {
        wc_load_cart();
    }

    $cart = WC()->cart;
    $cart_items = [];

    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        $product = $cart_item['data'];       
        
        // Get product category
        $categories = wp_get_post_terms($product->get_id(), 'product_cat');
        $category = !empty($categories) ? $categories[0]->name : '';

        $cart_items[] = array(
            'id' => (string) $product->get_id(),
            'name' => $product->get_name(),
            'category' => $category,
            'variant' => $cart_item['variation_name'] ?? '',
            'price' => (float) $cart_item['line_subtotal'] / $cart_item['quantity'],
            'quantity' => $cart_item['quantity']
        );
    }

    wp_send_json([
        'cart_total'         => $cart->get_total('edit'),
        'items'              => $cart_items
    ]);
}

Youez - 2016 - github.com/yon3zu
LinuXploit