<?php
/**
 * FoodOrd: Delivery Fee integration with WooCommerce cart totals.
 *
 * Adds a fixed delivery fee to the WooCommerce cart totals when enabled in settings.
 *
 * @package FoodOrd
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Foodord_Delivery_Fee
 *
 * Adds the configured delivery fee to WooCommerce cart totals.
 * Hooked into woocommerce_cart_calculate_fees.
 *
 * @package FoodOrd
 */
class Foodord_Delivery_Fee {
	/**
	 * Initialize hooks for delivery fee.
	 *
	 * @return void
	 */
	public function init(): void {
		add_action( 'woocommerce_cart_calculate_fees', array( $this, 'maybe_add_delivery_fee' ) );
	}

	/**
	 * Add delivery fee to cart totals if enabled.
	 *
	 * @param WC_Cart $cart WooCommerce cart instance.
	 */
	public function maybe_add_delivery_fee( $cart ): void {
		// No admin/REST bail: allow in all contexts where cart exists.
		if ( ! $cart || ! method_exists( $cart, 'get_cart_contents_count' ) ) {
			return;
		}

		// Do not add fee when cart is empty.
		if ( 0 === (int) $cart->get_cart_contents_count() ) {
			return;
		}

		$fee_type  = get_option( 'foodord_delivery_fee_type', 'fixed' );
		$fee_fixed = (float) get_option( 'foodord_delivery_fee_fixed', '0' );

		if ( 'fixed' !== $fee_type ) {
			return;
		}

		// Always add the fee for Fixed type, even if zero (won't change totals but stays consistent).
		$fee_name  = __( 'Delivery fee', 'foodord' );
		$amount    = max( 0, $fee_fixed );
		$taxable   = false; // Adjust if delivery fee should be taxable.
		$tax_class = '';

		if ( function_exists( 'foodord_track_delivery_fee' ) ) {
			foodord_track_delivery_fee( $amount );
		}
		// Avoid duplicate fee when recalculating: WooCommerce handles duplicates by key, but we'll be explicit.
		// There is no direct remove method here; rely on calculate_fees lifecycle to add once per calc.
		$cart->add_fee( $fee_name, $amount, $taxable, $tax_class );
	}
}
