<?php

namespace EasyShippingRate\Support;

use EasyShippingRate\ShippingMethod;

/**
 * Whether Pro (premium) code is allowed to run on this site.
 *
 * Single gate for every Pro-only feature: it wraps the Freemius license check
 * so the rest of the plugin never calls the SDK directly. Returns false when
 * Freemius is dormant (no dashboard credentials configured yet) or when the
 * customer is on the free plan, so the free build always behaves normally.
 *
 * esraw_fs() stays in the global namespace (Freemius convention), hence the
 * leading backslash.
 *
 * @return bool
 */
function is_premium() {
	return function_exists( 'esraw_fs' ) && \esraw_fs() && \esraw_fs()->can_use_premium_code();
}

function get_user_roles() {
	global $wp_roles;
	$roles               = $wp_roles->get_names();
	$roles ['not_login'] = 'Guest';
	return $roles;
}

function get_cart_volume() {
	// Initializing variables
	$volume = $rate = 0;

	$dimension_unit = get_option( 'woocommerce_dimension_unit' );

	// Calculate the rate to be applied for volume in cm3
	if ( 'mm' === $dimension_unit ) {
		$rate = pow( 10, 3 );
	} elseif ( 'cm' === $dimension_unit ) {
		$rate = 1;
	} elseif ( 'm' === $dimension_unit ) {
		$rate = pow( 10, -6 );
	}

	if ( 0 === $rate ) {
		return false; // Exit
	}

	foreach ( WC()->cart->get_cart() as $cart_item ) {
		$product = $cart_item['data'];
		$qty     = $cart_item['quantity'];

		$length = $product->get_length();
		$width  = $product->get_width();
		$height = $product->get_height();

		$volume += (float) $length * (float) $width * (float) $height * $qty;
	}
	return $volume / $rate;
}

function get_shipping_zones_list_for_import() {
	global $wpdb;
	$results   = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}woocommerce_shipping_zones" );
	$to_return = array();
	if ( is_array( $results ) ) {
		foreach ( $results as $result ) {
			$to_return[ $result->zone_id ] = $result->zone_name;
		}
	}
	return $to_return;
}

function get_shipping_list_for_export() {
	global $wpdb;
	$results = $wpdb->get_results(
		$wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE method_id=%s", ShippingMethod::METHOD_ID )
	);

	$to_return = array();
	if ( is_array( $results ) ) {
		foreach ( $results as $result ) {
			$option = get_option( 'woocommerce_' . ShippingMethod::METHOD_ID . '_' . $result->instance_id . '_settings' );
			if ( is_array( $option ) && isset( $option['method_title'] ) ) {
				$to_return[ $result->instance_id ] = $option['method_title'];
			}
		}
	}
	return $to_return;
}
