<?php
namespace WTC_CHECKOUT\Core\General;
defined('ABSPATH') || exit;
class ShippingVisibilityService {
    public function __construct() {
        add_filter('woocommerce_package_rates', array($this, 'filter_shipping_methods'), 10, 2);
        add_action('woocommerce_checkout_update_order_review', array($this, 'ensure_checkout_filter'));
        add_action('woocommerce_update_shipping_method', array($this, 'ensure_checkout_filter'));
    }
    public function filter_shipping_methods($rates, $package = null) {
        if (empty($rates)) {
            return $rates;
        }
        $visibility_option = get_option('wtc_shipping_visibility', 'show_all');
        if ($visibility_option === 'show_all') {
            return $rates;
        }
        $free_shipping_available = false;
        foreach ($rates as $rate_id => $rate) {
            if ('free_shipping' === $rate->method_id) {
                $free_shipping_available = true;
                break;
            }
        }
        if (!$free_shipping_available) {
            return $rates;
        }
        switch ($visibility_option) {
            case 'only_free':
                $filtered_rates = array();
                foreach ($rates as $rate_id => $rate) {
                    if ('free_shipping' === $rate->method_id) {
                        $filtered_rates[$rate_id] = $rate;
                    }
                }
                return !empty($filtered_rates) ? $filtered_rates : $rates;
            case 'all_free':
                $filtered_rates = array();
                foreach ($rates as $rate_id => $rate) {
                    if ('free_shipping' === $rate->method_id || $rate->cost == 0) {
                        $filtered_rates[$rate_id] = $rate;
                    }
                }
                return !empty($filtered_rates) ? $filtered_rates : $rates;
            default:
                return $rates;
        }
    }
    public function ensure_checkout_filter() {
        if (function_exists('WC') && WC()->cart) {
            WC()->session->set('shipping_for_package_0', null);
        }
    }
} 