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

/**
 * Mark auction as SOLD after successful payment
 */
add_action('woocommerce_payment_complete', function ($order_id) {

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

    // Only handle auction orders
    $auction_id = $order->get_meta('_stakmv_auction_id');
    if (!$auction_id) {
        return;
    }

    // Only Buy Now orders
    if (!$order->get_meta('_buy_now_used')) {
        return;
    }

    update_post_meta($auction_id, '_stakmv_auction_status', 'sold');
});

/**
 * Apply shipping cost for buy-now-only items added via cart/checkout.
 */
add_action('woocommerce_cart_calculate_fees', function ($cart) {
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }

    if (!$cart) {
        return;
    }

    $live_rates_enabled = stakmv_get_option('live_shipping_enabled', 'no') === 'yes';

    $shipping_total = 0;
    foreach ($cart->get_cart() as $cart_item) {
        if (empty($cart_item['product_id'])) {
            continue;
        }
        $product_id = (int) $cart_item['product_id'];
        $listing_type = get_post_meta($product_id, '_stakmv_auction_listing_type', true);
        if (!in_array($listing_type, array('buy_now_only', 'auction_buy_now'), true)) {
            continue;
        }

        $shipping_mode = function_exists('stakmv_get_listing_shipping_mode')
            ? stakmv_get_listing_shipping_mode($product_id)
            : 'calculated';

        if ($shipping_mode === 'pickup_only') {
            continue;
        }

        // When live rates integration is enabled, shipping is provided by
        // package rates (not cart fees) to avoid duplicate/free-rate conflicts.
        if ($live_rates_enabled) {
            continue;
        }

        $cost = (float) get_post_meta($product_id, '_stakmv_auction_shipping_cost', true);
        if ($cost > 0) {
            $qty = isset($cart_item['quantity']) ? (int) $cart_item['quantity'] : 1;
            $shipping_total += ($cost * max(1, $qty));
        }
    }

    if ($shipping_total > 0) {
        $cart->add_fee('Shipping', $shipping_total, false);
    }
}, 20, 1);

/**
 * For Buy Now–only items that go through the cart, attach auction metadata
 * to the order so the rest of the plugin can track it.
 */
add_action('woocommerce_checkout_create_order', function ($order) {
    if (!$order) {
        return;
    }

    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        if (!$product) {
            continue;
        }

        $product_id   = $product->get_id();
        $listing_type = get_post_meta($product_id, '_stakmv_auction_listing_type', true);

        if (!in_array($listing_type, array('buy_now_only', 'auction_buy_now'), true)) {
            continue;
        }

        $order->update_meta_data('_stakmv_auction_id', $product_id);
        $order->update_meta_data('_buy_now_used', true);

        // Keep auction status consistent for buy now items.
        update_post_meta($product_id, '_stakmv_auction_status', 'pending_payment');
        break; // assume single-item buy now orders
    }
}, 10, 1);

/**
 * Block checkout when listing shipping scope excludes customer destination country.
 */
add_action('woocommerce_check_cart_items', function () {
    if (!function_exists('WC') || !WC()->cart) {
        return;
    }

    $country = '';
    if (WC()->customer) {
        $country = strtoupper(trim((string) WC()->customer->get_shipping_country()));
        if ($country === '') {
            $country = strtoupper(trim((string) WC()->customer->get_billing_country()));
        }
    }
    if ($country === '' && function_exists('wc_get_base_location')) {
        $base = wc_get_base_location();
        if (is_array($base) && !empty($base['country'])) {
            $country = strtoupper(sanitize_text_field((string) $base['country']));
        }
    }
    if ($country === '') {
        return;
    }

    $blocked_titles = array();
    foreach (WC()->cart->get_cart() as $cart_item) {
        $product_id = isset($cart_item['product_id']) ? (int) $cart_item['product_id'] : 0;
        if ($product_id <= 0) {
            continue;
        }
        $listing_type = (string) get_post_meta($product_id, '_stakmv_auction_listing_type', true);
        if ($listing_type === '') {
            continue;
        }
        if (function_exists('stakmv_listing_ships_to_country') && !stakmv_listing_ships_to_country($product_id, $country)) {
            $blocked_titles[] = get_the_title($product_id);
        }
    }

    if (!empty($blocked_titles)) {
        wc_add_notice(
            __('Some listings in your cart do not ship to your destination country. Remove them or update your shipping address.', 'stak-multivendor'),
            'error'
        );
    }
}, 15);
