<?php

use Brick\PhoneNumber\PhoneNumber;

class AP_Quix_Helper {

	public function getArrCart( $order ): array {
		$items = array();
		foreach ( $order->get_items() as $item_id => $item ) {
			$product               = $item->get_product();
			$itemPriceIncludingTax = wc_get_price_including_tax( $product );

			/** @var WC_Order_Item_Product $item */
			$totalItemIncludingTax = (float) $item->get_total() + (float) $item->get_total_tax();
			$itemUnits             = $item->get_quantity();

			if ( $product->get_virtual() ) {
				$item_category = "digital";
			} else {
				$item_category = "physical";
			}

			//			$itemReference = $product->get_sku();
			//			if (!$itemReference){
			//				$itemReference = $product->get_id();
			//			}

			$items[] = [
				'article'              => [
					'category'            => $item_category,
					'name'                => $product->get_name(),
					'reference'           => 'i_' . $item_id,
					'type'                => 'product',
					'unit_price_with_tax' => round( $itemPriceIncludingTax, 2 ),
				],
				'total_price_with_tax' => round( $totalItemIncludingTax, 2 ),
				'units'                => $itemUnits,
				'auto_shipping'        => 'true',
			];

		}
		$shippingTotal = round( $order->get_shipping_total(), 2 );
		$shippingTax   = round( $order->get_shipping_tax(), 2 );
		$shippingTotal += $shippingTax;
		//Adding shipping fee to items
		if ( $shippingTotal > 0 ) {
			$shipping_method  = @array_shift( $order->get_shipping_methods() );
			$methodName       = $shipping_method['name'];
			$methodInstanceId = $shipping_method['instance_id'];

			$items[] = [
				'article'              => [
					'category'            => 'shipping_fee',
					'name'                => $methodName,
					'reference'           => $methodInstanceId,
					'type'                => 'product',
					'unit_price_with_tax' => round( $shippingTotal, 2 ),
				],
				'total_price_with_tax' => round( $shippingTotal, 2 ),
				'units'                => 1,
				'auto_shipping'        => 'true',
			];
		}

		$cart = [
			'currency'             => $order->get_currency(),
			'items'                => $items,
			'reference'            => $order->get_order_key(),
			'total_price_with_tax' => round( $order->get_total(), 2 ),
		];

		return $cart;
	}

	public function getArrBilling( WC_Order $order ): array {
		$countryIso3  = $this->getCountryIso3( $order->get_billing_country() );
		$billingPhone = $this->getCorrectPhone( $order->get_billing_phone(), $order->get_billing_country() );

		$billing_address = [
			'city'             => $order->get_billing_city(),
			'country'          => $countryIso3,
			'postal_code'      => $order->get_billing_postcode(),
			'street_address'   => $order->get_billing_address_1(),
			'street_address_2' => $order->get_billing_address_2(),
		];

		$billing = [
			'address'      => $billing_address,
			'company'      => $order->get_billing_company(),
			'first_name'   => $order->get_billing_first_name(),
			'last_name'    => $order->get_billing_last_name(),
			'phone_number' => $billingPhone,
		];

		return $billing;
	}

	public function truncate_price( $value ): float {
		if ( $value < 0 ) {
			return ceil( (string) ( $value * 100 ) ) / 100;
		} else {
			return ceil( (string) ( $value * 100 ) ) / 100;
		}
	}

	public function getArrShipping( WC_Order $order ): array {

		$shipping_methods = $order->get_shipping_methods();
		$shipping_method  = @array_shift( $shipping_methods );
		$methodName       = ! empty( $shipping_method['name'] ) ?: "-";

		if ( empty( $order->get_formatted_shipping_address() ) ) {
			$shipping         = $this->getArrBilling( $order );
			$shipping['name'] = $methodName;

			return $shipping;
		}

		$countryIso3   = $this->getCountryIso3( $order->get_shipping_country() );
		$shippingPhone = $this->getShippingPhone( $order );
		$shippingPhone = $this->getCorrectPhone( $shippingPhone, $order->get_shipping_country() );

		$shipping_address = [
			'city'             => $order->get_shipping_city(),
			'country'          => $countryIso3,
			'postal_code'      => $order->get_shipping_postcode(),
			'street_address'   => $order->get_shipping_address_1(),
			'street_address_2' => $order->get_shipping_address_2(),
		];

		$shipping = [
			'address'      => $shipping_address,
			'company'      => $order->get_shipping_company(),
			'first_name'   => $order->get_shipping_first_name(),
			'last_name'    => $order->get_shipping_last_name(),
			'phone_number' => $shippingPhone,
			'name'         => $methodName,
		];

		return $shipping;
	}

	/* ****** */

	public function getShippingPhone( WC_Order $order ): string {
		$billingName  = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
		$shippingName = $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name();
		$billingPhone = $order->get_billing_phone();

		if ( method_exists( $order, 'get_shipping_phone' ) ) {
			$shippingPhone = $order->get_shipping_phone();
		} else {
			$shippingPhone = $order->get_billing_phone();
		}

		if ( $billingName === $shippingName && ! $shippingPhone ) {
			$shippingPhone = $billingPhone;
		}

		return $shippingPhone;
	}

	public function getCountryIso3( $isoCode ): string {

		$country_isos = json_decode( file_get_contents( "http://country.io/iso3.json" ), true );

		return $country_isos[ $isoCode ];
	}

	public function getCorrectPhone( $phone, $country ): string {
		$phoneNumber = '';

		if ( ! $country && ! $phone ) {
			return urlencode( '+34600000000' );
		}

		if ( ! $phone ) {
			$phoneNumber = PhoneNumber::parse( '600000000', $country );

			return urlencode( (string) $phoneNumber );
		}

		if ( ! $country ) {
			return urlencode( $phone );
		}

		$phoneNumber = PhoneNumber::parse( $phone, $country );

		return urlencode( (string) $phoneNumber );
	}

}
