<?php
/**
 * Pro Checkout Address handling for the checkout.
 *
 * @package     EDD\Pro\Checkout
 * @copyright   Copyright (c) 2025, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.6.0
 */

namespace EDD\Pro\Checkout;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

use EDD\Checkout\Address as Base;

/**
 * Address class.
 */
class Address extends Base {

	/**
	 * Set up the customer.
	 *
	 * @since 3.6.0
	 * @return array
	 */
	protected function set_up_customer() {
		$customer = parent::set_up_customer();

		// If the customer data is already set, return it.
		if ( ! empty( $customer['address']['country'] ) ) {
			return $customer;
		}

		// If the IP data is not set, return the customer data.
		$pro_ip_data = EDD()->session->get( 'edd_pro_geoip' );
		if ( empty( $pro_ip_data ) ) {
			return $customer;
		}
		$customer['address']['country'] = $pro_ip_data['country_iso'];
		$customer['address']['state']   = $this->get_state( $pro_ip_data );
		$customer['address']['city']    = sanitize_text_field( $pro_ip_data['city'] ?? '' );

		return $customer;
	}

	/**
	 * Get the state from the IP data.
	 *
	 * @since 3.6.0
	 * @param array $pro_ip_data The IP data.
	 * @return string
	 */
	private function get_state( $pro_ip_data ) {
		$country_iso = sanitize_text_field( $pro_ip_data['country_iso'] );
		$states      = edd_get_shop_states( $country_iso );
		$region_code = sanitize_text_field( $pro_ip_data['region_code'] ?? '' );

		// If the region code is in the states array, it will work for the address selector.
		if ( ! empty( $region_code ) && array_key_exists( $region_code, $states ) ) {
			return sanitize_text_field( $region_code );
		}

		// Japan region codes in EDD are `JP01`, etc.
		if ( 'JP' === $country_iso && ! empty( $region_code ) && array_key_exists( $country_iso . $region_code, $states ) ) {
			return sanitize_text_field( $country_iso . $region_code );
		}

		// For Great Britain, we can try to get the region code from the city.
		if ( 'GB' === $country_iso && ! empty( $pro_ip_data['city'] ) ) {
			$city = sanitize_text_field( $pro_ip_data['city'] );

			return array_search( $city, edd_get_united_kingdom_states_list(), true );
		}

		// Probably this is a state that's not available from a list so return the full region name.
		return sanitize_text_field( $pro_ip_data['region_name'] ?? '' );
	}
}
