<?php
if (!defined('ABSPATH'))
    exit;
class ShippingGuard_Frontend
{
    public function init()
    {
        add_action('woocommerce_review_order_before_submit', array($this, 'display_checkout_option'));
        add_action('woocommerce_cart_totals_after_shipping', array($this, 'display_checkout_option'));
        add_action('woocommerce_cart_calculate_fees', array($this, 'add_fee'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));

        // Package Splitting
        add_filter('woocommerce_cart_shipping_packages', array($this, 'split_packages_logic'));
        
        // Global Bar rendering
        add_action('wp_footer', array($this, 'render_global_mount'));
        
        // Delivery Date Selection
        add_action('woocommerce_review_order_before_submit', array($this, 'display_delivery_date_picker'));
        add_action('woocommerce_checkout_process', array($this, 'validate_delivery_date'));
        add_action('woocommerce_checkout_update_order_meta', array($this, 'save_delivery_date'));
        add_action('woocommerce_admin_order_data_after_shipping_address', array($this, 'display_delivery_date_in_admin'));

        // Service Levels
        add_filter('woocommerce_package_rates', array($this, 'add_service_level_rates'), 10, 2);

        // Estimated Delivery Date (EDD)
        add_action('woocommerce_single_product_summary', array($this, 'display_edd'), 25);
        add_action('woocommerce_review_order_after_shipping', array($this, 'display_edd_checkout'));

        // Classic checkout hook (before save)
        add_action('woocommerce_checkout_create_order', array($this, 'save_order_meta'), 20, 2);

        // Blocks checkout / alternative hook (after create)
        add_action('woocommerce_checkout_order_created', array($this, 'save_order_meta_after'), 20, 1);
        add_action('woocommerce_store_api_checkout_order_processed', array($this, 'save_order_meta_after'), 20, 1);

        // AJAX for classic cart page instant price update
        add_action('wp_ajax_shippingguard_classic_toggle', array($this, 'ajax_classic_toggle'));
        add_action('wp_ajax_nopriv_shippingguard_classic_toggle', array($this, 'ajax_classic_toggle'));
        
        // Eco Toggle AJAX
        add_action('wp_ajax_shippingguard_eco_toggle', array($this, 'ajax_eco_toggle'));
        add_action('wp_ajax_nopriv_shippingguard_eco_toggle', array($this, 'ajax_eco_toggle'));

        // Weight / Volumetric / Table Rates Registration
        add_filter( 'woocommerce_package_rates', array($this, 'apply_advanced_logic'), 10, 2 );
    }

    public function enqueue_scripts()
    {
        if (is_checkout() || is_cart()) {
            wp_enqueue_style(
                'shippingguard-frontend',
                SHIPPINGGUARD_URL . 'assets/style.css',
                array(),
                SHIPPINGGUARD_VERSION
            );
            wp_enqueue_script(
                'shippingguard-checkout',
                SHIPPINGGUARD_URL . 'assets/checkout.js',
                array('jquery'),
                SHIPPINGGUARD_VERSION,
                true
            );

            wp_localize_script('shippingguard-checkout', 'sg_params', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('shippingguard_nonce'),
                'update_ship_nonce' => wp_create_nonce('update-shipping-method'),
            ));
        }

        // Always enqueue global for conversion bar
        if (shippingguard_is_pro() && get_option('shippingguard_free_shipping_bar_enabled', 'yes') === 'yes') {
            wp_enqueue_script(
                'shippingguard-global',
                SHIPPINGGUARD_URL . 'assets/global.js',
                array('wp-element'),
                SHIPPINGGUARD_VERSION,
                true
            );
            wp_localize_script('shippingguard-global', 'sgGlobalData', array(
                'threshold' => floatval(get_option('shippingguard_free_shipping_threshold', '100.00')),
                'barColor' => get_option('shippingguard_free_shipping_bar_color', '#2563eb'),
                'subtotal' => (WC()->cart) ? WC()->cart->get_subtotal() : 0,
                'currencySymbol' => get_woocommerce_currency_symbol(),
                'position' => get_option('shippingguard_free_shipping_bar_position', 'top'),
                'isAdminBar' => is_admin_bar_showing(),
            ));
        }
    }

    public function add_service_level_rates($rates, $package) {
        if (!shippingguard_is_pro()) return $rates;
        if (get_option('shippingguard_service_standard_enabled', 'yes') === 'yes') {
            $standard_fee = floatval(get_option('shippingguard_service_standard_fee', '0'));
            $rates['shippingguard_standard'] = new WC_Shipping_Rate(
                'shippingguard_standard',
                'Standard Delivery',
                $standard_fee,
                array(),
                'shippingguard_standard'
            );
        }

        if (get_option('shippingguard_service_express_enabled', 'no') === 'yes') {
            $surcharge = floatval(get_option('shippingguard_service_express_surcharge', '20'));
            $standard_fee = floatval(get_option('shippingguard_service_standard_fee', '0'));
            $express_fee = $standard_fee + $surcharge;
            
            $rates['shippingguard_express'] = new WC_Shipping_Rate(
                'shippingguard_express',
                'Express Delivery',
                $express_fee,
                array(),
                'shippingguard_express'
            );
        }

        return $rates;
    }

    public function render_global_mount() {
        if (get_option('shippingguard_free_shipping_bar_enabled', 'yes') === 'yes') {
            echo '<div id="shippingguard-global-root"></div>';
        }
    }

    public function ajax_classic_toggle()
    {
        check_ajax_referer('shippingguard_nonce', 'security');
        $enabled = (isset($_POST['enabled']) && 'true' === $_POST['enabled']) ? 'yes' : 'no';
        if (isset(WC()->session)) {
            WC()->session->set('shippingguard_fee_enabled', $enabled);
        }
        wp_send_json_success();
    }

    public function ajax_eco_toggle()
    {
        check_ajax_referer('shippingguard_nonce', 'security');
        $enabled = (isset($_POST['enabled']) && 'true' === $_POST['enabled']) ? 'yes' : 'no';
        if (isset(WC()->session)) {
            WC()->session->set('shippingguard_eco_enabled', $enabled);
        }
        wp_send_json_success();
    }

    public function apply_advanced_logic( $rates, $package ) {
        if ( get_option('shippingguard_module_weight_shipping', 'yes') !== 'yes' ) return $rates;
        
        $is_pro = shippingguard_is_pro();
        $total_weight = 0;
        $total_vol_weight = 0;
        $product_fixed_fees = 0;
        $is_free_override = false;
        $vol_enabled = $is_pro && (get_option('shippingguard_volumetric_enabled', 'no') === 'yes');
        $divisor = floatval(get_option('shippingguard_volumetric_divisor', '139'));

        foreach( $package['contents'] as $item ) {
            $product = $item['data'];
            $product_id = $product->get_parent_id() ? $product->get_parent_id() : $product->get_id();
            
            // 1. Weight Calculation
            $custom_weight = get_post_meta($product_id, '_shippingguard_custom_weight', true);
            $item_weight = 0;
            if ( $custom_weight !== '' && is_numeric($custom_weight) ) {
                $item_weight = (float) $custom_weight;
            } elseif ( $product->has_weight() ) {
                $item_weight = (float) $product->get_weight();
            }
            $total_weight += $item_weight * $item['quantity'];

            // 2. Volumetric Calculation
            if ($vol_enabled && $product->has_dimensions()) {
                $l = floatval($product->get_length() ?: 0);
                $w = floatval($product->get_width() ?: 0);
                $h = floatval($product->get_height() ?: 0);
                if ($l > 0 && $w > 0 && $h > 0) {
                    $vol_w = ($l * $w * $h) / $divisor;
                    $total_vol_weight += $vol_w * $item['quantity'];
                }
            }

            // 3. Product Fixed Fee Surcharge
            $fixed_fee = get_post_meta($product_id, '_shippingguard_fixed_fee', true);
            if ( $fixed_fee !== '' && is_numeric($fixed_fee) ) {
                $product_fixed_fees += (float) $fixed_fee * $item['quantity'];
            }

            // 4. Free Shipping Override
            if ( get_post_meta($product_id, '_shippingguard_is_free', true) === 'yes' ) {
                $is_free_override = true;
            }
        }
        
        // Use the greater of the two
        $final_weight = max($total_weight, $total_vol_weight);
        
        $rate_per_kg = floatval(get_option('shippingguard_weight_shipping_rate_per_kg', '5.00'));
        $base_fee    = floatval(get_option('shippingguard_weight_shipping_base_fee', '2.00'));
        $threshold   = floatval(get_option('shippingguard_weight_threshold', '0'));
        $charge_mode = $is_pro ? get_option('shippingguard_weight_charge_mode', 'extra') : 'extra'; // 'extra' is default for free

        $billable_weight = 0;
        if ($final_weight > $threshold) {
             if ($charge_mode === 'full') {
                 $billable_weight = $final_weight;
             } else {
                 $billable_weight = $final_weight - $threshold;
             }
        }
        
        $calculated_cost = $base_fee + ($billable_weight * $rate_per_kg) + $product_fixed_fees;
        if ( $is_free_override ) {
            $calculated_cost = 0;
        }

        // 3. Condition Engine Override
        if ($is_pro) {
            $rules = get_option('shippingguard_table_rate_rules', array());
            $current_user = wp_get_current_user();
            $subtotal = WC()->cart ? WC()->cart->get_subtotal() : 0;

            foreach ($rules as $rule) {
                $match = false;
                if ($rule['condition'] === 'subtotal' && $subtotal >= floatval($rule['value'])) {
                    $match = true;
                } elseif ($rule['condition'] === 'role' && in_array($rule['value'], (array) $current_user->roles)) {
                    $match = true;
                }

                if ($match) {
                    // If a rule matches, override the cost (simple implementation: first match wins)
                    $calculated_cost = floatval($rule['fee']);
                    break;
                }
            }
        }

        $rate_id = 'shippingguard_weight_shipping';
        $rates[$rate_id] = new WC_Shipping_Rate(
            $rate_id,
            'Advanced Guard Delivery',
            $calculated_cost,
            array(),
            'shippingguard_advanced'
        );
        return $rates;
    }

    private function product_belongs_to_categories($product_id, $category_ids)
    {
        if (empty($category_ids) || !is_array($category_ids)) {
            return false;
        }

        $term_ids = wc_get_product_term_ids($product_id, 'product_cat');
        if (empty($term_ids)) {
            return false;
        }

        // 1. Direct match check
        if (!empty(array_intersect($category_ids, $term_ids))) {
            return true;
        }

        // 2. Hierarchy check: if any of the product's categories have an ancestor in our list
        foreach ($term_ids as $term_id) {
            $ancestors = get_ancestors($term_id, 'product_cat');
            if (!empty(array_intersect($category_ids, $ancestors))) {
                return true;
            }
        }

        return false;
    }

    private function passes_smart_rules($cart)
    {
        // 1. Check Global Exclusions first
        if ($this->has_excluded_items($cart)) {
            return false;
        }

        $smart_enabled = get_option('shippingguard_smart_rules_enabled', 'no');
        if ('yes' !== $smart_enabled) {
            return true;
        }

        $cart_total = $cart->get_cart_contents_total();

        // Rule 1: Minimum order amount
        $min_order = get_option('shippingguard_smart_min_order', '');
        if ($min_order !== '' && floatval($min_order) > 0) {
            if ($cart_total < floatval($min_order)) {
                return false;
            }
        }

        return true;
    }

    private function has_eco_disabled_items($cart)
    {
        foreach ($cart->get_cart() as $item) {
            $product = $item['data'];
            $product_id = $product->get_parent_id() ? $product->get_parent_id() : $product->get_id();
            if ('yes' === get_post_meta($product_id, '_shippingguard_disable_eco', true)) {
                return true;
            }
        }
        return false;
    }

    private function has_excluded_items($cart)
    {
        $exclude_digital = get_option('shippingguard_exclude_digital', 'yes');
        $exclude_products = get_option('shippingguard_exclude_products', array());
        $exclude_categories = get_option('shippingguard_exclude_categories', array());

        foreach ($cart->get_cart() as $item) {
            $product_id = $item['product_id'];
            $variation_id = $item['variation_id'];
            $product = $item['data'];

            // 1. Digital product exclusion
            if ('yes' === $exclude_digital && ($product->is_virtual() || $product->is_downloadable())) {
                return true;
            }

            // 2. Specific product ID exclusion
            if (!empty($exclude_products) && is_array($exclude_products)) {
                if (in_array($product_id, $exclude_products) || ($variation_id && in_array($variation_id, $exclude_products))) {
                    return true;
                }
            }

            // 3. Specific category exclusion (Hide if matches)
            if ($this->product_belongs_to_categories($product_id, $exclude_categories)) {
                return true;
            }
        }

        return false;
    }

    private function calculate_fee($cart_total)
    {
        $pricing_method = get_option('shippingguard_pricing_method', 'fixed');
        $fee_amount = 0;

        if (!is_numeric($cart_total)) {
            $cart_total = 0;
        }

        if ('fixed' === $pricing_method) {
            $fee_amount = floatval(get_option('shippingguard_fixed_fee', '2.99'));
        } elseif ('percentage' === $pricing_method) {
            $percentage = floatval(get_option('shippingguard_percentage_fee', '2'));
            $fee_amount = ($cart_total * $percentage) / 100;
            $max_cap = floatval(get_option('shippingguard_max_cap', '5'));
            if ($max_cap > 0 && $fee_amount > $max_cap) {
                $fee_amount = $max_cap;
            }
        } elseif ('tier' === $pricing_method) {
            $tier_rules = get_option('shippingguard_tier_rules', array(
                array('min' => 0, 'max' => 50, 'fee' => 1),
                array('min' => 50, 'max' => 100, 'fee' => 2),
                array('min' => 100, 'max' => '', 'fee' => 3),
            ));
            if (is_array($tier_rules)) {
                foreach ($tier_rules as $rule) {
                    $min = floatval($rule['min']);
                    $max = ($rule['max'] === '' || !is_numeric($rule['max'])) ? 999999999 : floatval($rule['max']);
                    if ($cart_total >= $min && $cart_total <= $max) {
                        $fee_amount = floatval($rule['fee']);
                        break;
                    }
                }
            }
        }

        return floatval($fee_amount);
    }

    public function display_checkout_option()
    {
        $is_enabled = get_option('shippingguard_is_enabled', 'yes');
        if ('yes' !== $is_enabled) {
            return;
        }

        // Check page-specific visibility settings
        $show_on_cart = get_option('shippingguard_show_on_cart', 'yes');
        $show_on_checkout = get_option('shippingguard_show_on_checkout', 'yes');

        if (is_cart() && 'yes' !== $show_on_cart) {
            return;
        }
        if (is_checkout() && 'yes' !== $show_on_checkout) {
            return;
        }

        if (get_option('shippingguard_module_protection', 'yes') !== 'yes') {
            return;
        }

        if (!WC()->cart || !WC()->session || !$this->passes_smart_rules(WC()->cart)) {
            if (WC()->session) {
                WC()->session->set('shippingguard_fee_enabled', 'no');
            }
            return;
        }

        $cart_total = WC()->cart->get_cart_contents_total();
        $fee_amount = $this->calculate_fee($cart_total);

        $session_fee_enabled = (WC()->session && WC()->session->get('shippingguard_fee_enabled'))
            ? WC()->session->get('shippingguard_fee_enabled')
            : 'yes';
        $checked = ('yes' === $session_fee_enabled) ? 'checked="checked"' : '';

        // Debug:
        $html_debug = '<!-- SG_SESSION: ' . esc_html($session_fee_enabled) . ' -->';

        $protection_name = get_option('shippingguard_protection_name', 'Shipping Protection');
        $checkout_label = get_option('shippingguard_checkout_label', '');
        $protection_icon = get_option('shippingguard_protection_icon', '');

        // Title is Protection Name, Subtitle is Checkout Label
        $card_title = $protection_name;
        $card_subtitle = $checkout_label;

        // Default Shield Icon SVG
        $default_icon_svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#48bb78" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path><polyline points="9 11 12 14 20 6"></polyline></svg>';

        $html = $html_debug . '<div class="shippingguard-premium-card">';

        // Icon
        $html .= '<div class="sg-icon-container">';
        if ($protection_icon) {
            $html .= '<img src="' . esc_url($protection_icon) . '" alt="Protection">';
        } else {
            $html .= $default_icon_svg;
        }
        $html .= '</div>';

        // Content
        $html .= '<div class="sg-content">';
        $html .= '<div class="sg-title">' . esc_html($card_title) . '</div>';
        $html .= '<div class="sg-price">' . wp_strip_all_tags(wc_price($fee_amount)) . '</div>';
        $html .= '<div class="sg-subtext">' . esc_html($card_subtitle) . '</div>';
        $html .= '<div class="sg-powered">Powered by <a href="https://dominopress.com/plugin/shippingguard" target="_blank">ShippingGuard</a></div>';
        $html .= '</div>';

        // Action (Toggle)
        $html .= '<div class="sg-action">';
        $html .= '<label class="sg-switch">';
        $html .= '<input type="checkbox" id="shippingguard_protection" name="shippingguard_protection" value="1" ' . $checked . '>';
        $html .= '<span class="sg-slider"></span>';
        $html .= '<input type="hidden" name="shippingguard_protection_present" value="1">';
        $html .= '</label>';
        $html .= '</div>';

        if (is_cart()) {
            echo '<tr class="shippingguard-protection-row">';
            echo '<td colspan="2" style="padding: 20px 0; border-top: 1px solid #eee;">';
            echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo '</td>';
            echo '</tr>';
        } else {
            echo '<div class="shippingguard-protection-wrapper" style="margin-bottom: 25px;">';
            echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo '</div>';
        }

        // Eco Delivery Output
        $mod_eco = get_option('shippingguard_module_zero_emission', 'no');
        if (shippingguard_is_pro() && 'yes' === $mod_eco && !$this->has_eco_disabled_items(WC()->cart)) {
            $eco_fee = floatval(get_option('shippingguard_zero_emission_fee', '0.50'));
            $eco_label = get_option('shippingguard_zero_emission_label', 'Green Zero Emission Delivery');
            $session_eco_enabled = (WC()->session && WC()->session->get('shippingguard_eco_enabled')) ? WC()->session->get('shippingguard_eco_enabled') : 'no';
            $eco_checked = ('yes' === $session_eco_enabled) ? 'checked="checked"' : '';

            $eco_html = '<div class="shippingguard-premium-card" style="margin-top: 10px; border-color: #48bb78; background: #f0fff4;">';
            $eco_html .= '<div class="sg-icon-container"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#48bb78" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2.69l5.66 4.2c.8.6 1.34 1.54 1.34 2.56V15c0 3.87-3.13 7-7 7s-7-3.13-7-7V9.45c0-1.02.54-1.96 1.34-2.56L12 2.69z"></path></svg></div>';
            $eco_html .= '<div class="sg-content">';
            $eco_html .= '<div class="sg-title" style="color: #48bb78;">' . esc_html($eco_label) . '</div>';
            $eco_html .= '<div class="sg-price">' . wp_strip_all_tags(wc_price($eco_fee)) . '</div>';
            $eco_html .= '<div class="sg-subtext">Offset the carbon footprint of your delivery.</div>';
            $eco_html .= '</div>';
            $eco_html .= '<div class="sg-action"><label class="sg-switch">';
            $eco_html .= '<input type="checkbox" id="shippingguard_eco" name="shippingguard_eco" class="sg-eco-toggle" value="1" ' . $eco_checked . '>';
            $eco_html .= '<span class="sg-slider" style="background-color: '.($eco_checked ? '#48bb78' : '#e2e8f0').';"></span>';
            $eco_html .= '<input type="hidden" name="shippingguard_eco_present" value="1">';
            $eco_html .= '</label></div></div>';

            if (is_cart()) {
                echo '<tr class="shippingguard-eco-row"><td colspan="2" style="padding: 10px 0;">' . $eco_html . '</td></tr>';
            } else {
                echo '<div class="shippingguard-eco-wrapper" style="margin-bottom: 25px;">' . $eco_html . '</div>';
            }
        }
    }

    public function add_fee($cart)
    {
        if (is_admin() && !defined('DOING_AJAX')) {
            return;
        }

        $is_enabled = get_option('shippingguard_is_enabled', 'yes');
        if ('yes' !== $is_enabled) {
            return;
        }

        // Evaluate smart rules; silently skip fee if not passing
        if (!$cart instanceof WC_Cart || !WC()->session || !$this->passes_smart_rules($cart)) {
            return;
        }

        if (isset($_POST['post_data'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- natively handled by WC
            // We only unslash, we don't sanitize_text_field because that strips &amp; or chars which can break parse_str arrays
            $raw_post_data = wp_unslash($_POST['post_data']); // phpcs:ignore
            parse_str($raw_post_data, $post_data);

            // Only override session if the checkbox/card was actually present in the HTML form snippet submitted!
            if (isset($post_data['shippingguard_protection_present'])) {
                $enable = isset($post_data['shippingguard_protection']) ? 'yes' : 'no';
                if (isset(WC()->session)) {
                    WC()->session->set('shippingguard_fee_enabled', $enable);
                }
            }
        }

        $session_fee_enabled = (WC()->session) ? WC()->session->get('shippingguard_fee_enabled', 'yes') : 'yes';
        if ('yes' === $session_fee_enabled && get_option('shippingguard_module_protection', 'yes') === 'yes') {
            $cart_total = $cart->get_cart_contents_total();
            $fee_amount = $this->calculate_fee($cart_total);
            if (is_numeric($fee_amount) && $fee_amount > 0) {
                $protection_name = get_option('shippingguard_protection_name', 'Shipping Protection');
                $cart->add_fee($protection_name, $fee_amount, true, 'standard');
            }
        }

        // Eco Fee
        $mod_eco = get_option('shippingguard_module_zero_emission', 'no');
        if (shippingguard_is_pro() && 'yes' === $mod_eco && !$this->has_eco_disabled_items($cart)) {
            if (isset($_POST['post_data'])) {
                $raw_post_data = wp_unslash($_POST['post_data']);
                parse_str($raw_post_data, $post_data);
                if (isset($post_data['shippingguard_eco_present'])) {
                    $eco_enable = isset($post_data['shippingguard_eco']) ? 'yes' : 'no';
                    if (isset(WC()->session)) {
                        WC()->session->set('shippingguard_eco_enabled', $eco_enable);
                    }
                }
            }

            $session_eco_enabled = (WC()->session) ? WC()->session->get('shippingguard_eco_enabled', 'no') : 'no';
            if ('yes' === $session_eco_enabled) {
                $eco_fee = floatval(get_option('shippingguard_zero_emission_fee', '0.50'));
                $eco_label = get_option('shippingguard_zero_emission_label', 'Green Zero Emission Delivery');
                $cart->add_fee($eco_label, $eco_fee, true, 'standard');
            }
        }
    }

    public function save_order_meta($order, $data)
    {
        if (!$order instanceof WC_Order) {
            return;
        }
        $protection_name = get_option('shippingguard_protection_name', 'Shipping Protection');
        $is_protected = false;
        $fee_amount = 0;

        // Check if the order has the protection fee item
        foreach ($order->get_items('fee') as $item) {
            // Case-insensitive check just in case, or direct comparison
            if ($item->get_name() === $protection_name || stripos($item->get_name(), 'protection') !== false) {
                $is_protected = true;
                $fee_amount = (float) $item->get_total();
                break;
            }
        }

        // Fallback to session check if item not immediately found (Blocks issue)
        if (!$is_protected) {
            $session_fee_enabled = (WC()->session && WC()->session->get('shippingguard_fee_enabled'))
                ? WC()->session->get('shippingguard_fee_enabled')
                : 'yes';

            if ('yes' === $session_fee_enabled) {
                $is_protected = true;

                // For blocks/REST API, WC()->cart might already be cleared, fallback to order totals
                $base_amount = 0;
                if (WC()->cart && WC()->cart->get_cart_contents_total() > 0) {
                    $base_amount = WC()->cart->get_cart_contents_total();
                } else {
                    $base_amount = $order->get_subtotal();
                }

                $fee_amount = $this->calculate_fee($base_amount);
            }
        }

        if ($is_protected) {
            $order->update_meta_data('_shipping_protection_enabled', 'yes');
            $order->update_meta_data('_shipping_protection_fee', $fee_amount);
            $order->update_meta_data('_shipping_protection_status', 'protected');
        } else {
            $order->update_meta_data('_shipping_protection_enabled', 'no');
            $order->update_meta_data('_shipping_protection_fee', 0);
            $order->update_meta_data('_shipping_protection_status', 'unprotected');
        }

        // Save to separate table - only if we have a valid order ID
        $order_id = $order->get_id();
        if (!$order_id) {
            return;
        }

        global $wpdb;
        $table_orders = esc_sql($wpdb->prefix . 'shippingguard_orders');
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table record for shipping protection.
        $wpdb->replace(
            $table_orders,
            array(
                'order_id' => $order_id,
                'is_protected' => $is_protected ? 1 : 0,
                'fee_amount' => $fee_amount,
                'protection_status' => $is_protected ? 'protected' : 'unprotected',
            ),
            array('%d', '%d', '%f', '%s')
        );
    }

    public function save_order_meta_after($order)
    {
        if (is_numeric($order)) {
            $order = wc_get_order($order);
        }
        if (!$order instanceof WC_Order) {
            return;
        }
        // Redundant check, but useful for Block checkout
        $this->save_order_meta($order, null);
        $order->save_meta_data();
    }

    public function display_edd() {
        if (!shippingguard_is_pro() || get_option('shippingguard_module_edd', 'yes') !== 'yes') return;
        echo $this->get_edd_html();
    }

    public function display_edd_checkout() {
        if (!shippingguard_is_pro() || get_option('shippingguard_module_edd', 'yes') !== 'yes') return;
        echo '<tr class="sg-edd-checkout-row"><td colspan="2">' . $this->get_edd_html(true) . '</td></tr>';
    }

    private function get_edd_html($is_checkout = false) {
        $min_days = intval(get_option('shippingguard_edd_min_days', '3'));
        $max_days = intval(get_option('shippingguard_edd_max_days', '5'));

        // Adjust for selected shipping method if on checkout
        if ($is_checkout && WC()->session) {
            $chosen_methods = WC()->session->get('chosen_shipping_methods');
            if (!empty($chosen_methods)) {
                $method = $chosen_methods[0];
                if ($method === 'shippingguard_standard') {
                    $min_days = intval(get_option('shippingguard_service_standard_min', '3'));
                    $max_days = intval(get_option('shippingguard_service_standard_max', '5'));
                } elseif ($method === 'shippingguard_express') {
                    $min_days = intval(get_option('shippingguard_service_express_min', '1'));
                    $max_days = intval(get_option('shippingguard_service_express_max', '2'));
                }
            }
        }
        
        // Find highest lead time in cart
        $extra_lead = 0;
        if (WC()->cart) {
            foreach (WC()->cart->get_cart() as $item) {
                $lead = intval(get_post_meta($item['product_id'], '_shippingguard_lead_time', true));
                if ($lead > $extra_lead) $extra_lead = $lead;
            }
        }

        $delivery_range = $this->calculate_delivery_range($min_days + $extra_lead, $max_days + $extra_lead);
        
        $style = $is_checkout ? 'margin: 10px 0; font-size: 13px;' : 'margin: 15px 0; border: 1px solid #e2e8f0; padding: 12px; border-radius: 10px; background: #f8fafc;';
        
        return "<div class='shippingguard-edd' style='$style'>
            <strong>Estimated Delivery:</strong><br/>
            $delivery_range
        </div>";
    }

    public function display_delivery_date_picker() {
        if (!shippingguard_is_pro() || get_option('shippingguard_edd_selection_enabled', 'no') !== 'yes') return;
        
        $min_days = intval(get_option('shippingguard_edd_min_days', '3'));
        $max_future = intval(get_option('shippingguard_edd_max_future_days', '14'));
        
        $min_date = $this->add_business_days(date('Y-m-d'), $min_days);
        $max_date = date('Y-m-d', strtotime("+$max_future days"));

        echo '<div id="shippingguard_delivery_date_wrapper" style="margin-bottom: 20px; padding: 15px; border: 1px solid #e2e8f0; border-radius: 10px; background: #f9fafb;">';
        echo '<strong>' . __('Select Delivery Date', 'shippingguard') . '</strong>';
        echo '<p style="font-size: 12px; color: #64748b; margin: 4px 0 10px;">' . __('When would you like to receive your items?', 'shippingguard') . '</p>';
        echo '<input type="date" id="shippingguard_delivery_date" name="shippingguard_delivery_date" 
                min="' . $min_date . '" 
                max="' . $max_date . '" 
                style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #d1d5db;" 
                required>';
        echo '</div>';
    }

    public function validate_delivery_date() {
        if (get_option('shippingguard_edd_selection_enabled', 'no') !== 'yes') return;
        
        if (empty($_POST['shippingguard_delivery_date'])) {
            wc_add_notice(__('Please select a delivery date.', 'shippingguard'), 'error');
        }
    }

    public function save_delivery_date($order_id) {
        if (!empty($_POST['shippingguard_delivery_date'])) {
            update_post_meta($order_id, '_shippingguard_delivery_date', sanitize_text_field($_POST['shippingguard_delivery_date']));
        }
    }

    public function display_delivery_date_in_admin($order) {
        $date = $order->get_meta('_shippingguard_delivery_date');
        if ($date) {
            echo '<p><strong>' . __('Requested Delivery Date', 'shippingguard') . ':</strong> ' . date_i18n(get_option('date_format'), strtotime($date)) . '</p>';
        }
    }

    private function calculate_delivery_range($min, $max) {
        $working_days = get_option('shippingguard_edd_working_days', array('Mon', 'Tue', 'Wed', 'Thu', 'Fri'));
        $cutoff = get_option('shippingguard_edd_cutoff_time', '15:00');
        
        $current_time = current_time('H:i');
        $start_timestamp = current_time('timestamp');
        
        // If past cutoff, starts next day
        if ($current_time > $cutoff) {
            $start_timestamp = strtotime('+1 day', $start_timestamp);
        }
        
        $min_date = $this->add_business_days($start_timestamp, $min, $working_days);
        $max_date = $this->add_business_days($start_timestamp, $max, $working_days);
        
        $min_str = date_i18n('M j', $min_date);
        $max_str = date_i18n('M j', $max_date);
        
        return $min_str . ' — ' . $max_str;
    }

    private function add_business_days($start, $days, $working_days) {
        $date = $start;
        $added = 0;
        while ($added < $days) {
            $date = strtotime('+1 day', $date);
            if (in_array(date('D', $date), $working_days)) {
                $added++;
            }
        }
        return $date;
    }

    public function split_packages_logic($packages) {
        if (!shippingguard_is_pro() || get_option('shippingguard_package_splitting_enabled', 'no') !== 'yes') return $packages;

        $new_packages = array();
        $split_items = array();
        $normal_items = array();

        foreach ($packages as $i => $package) {
            foreach ($package['contents'] as $key => $item) {
                $product_id = $item['product_id'];
                $is_split = get_post_meta($product_id, '_shippingguard_split_shipment', true);
                
                if ('yes' === $is_split) {
                    $split_items[$key] = $item;
                } else {
                    $normal_items[$key] = $item;
                }
            }
        }

        if (empty($split_items)) return $packages;

        // Create package 1 (Normal)
        if (!empty($normal_items)) {
            $new_packages[] = array(
                'contents' => $normal_items,
                'contents_cost' => array_sum(wp_list_pluck($normal_items, 'line_total')),
                'applied_coupons' => WC()->cart->get_applied_coupons(),
                'user' => $packages[0]['user'],
                'destination' => $packages[0]['destination'],
            );
        }

        // Create package 2 (Split Handling)
        if (!empty($split_items)) {
            $new_packages[] = array(
                'contents' => $split_items,
                'contents_cost' => array_sum(wp_list_pluck($split_items, 'line_total')),
                'applied_coupons' => WC()->cart->get_applied_coupons(),
                'user' => $packages[0]['user'],
                'destination' => $packages[0]['destination'],
                'shippingguard_split' => true 
            );
        }

        return $new_packages;
    }
}
