<?php
/**
 * GurmeCargo diğer ayarlarını yöneten sınıf..
 *
 * @package GurmeHub
 */

/**
 * Order Status Sınıfı.
 */
class GCARGO_Auto_Shipment {

	/**
	 * Zamanlanmış görevin tetiklendiğinde çalışacak olan otomatik gönderi oluşturma fonksiyonu.
	 *
	 * @param string $order_id Sipariş verisi.
	 */
	public function auto_shipment( $order_id ) {
		$account_details = gcargo_api_requests()->get_profile();

		if ( in_array( $account_details['plan']['plan_id'], [ 2, 3, 16, 17, 18 ] ) ) {
			return;
		}

		if ( $order_id ) {
			try {
				$mapper = gcargo_shipment_map_wc_order( $order_id );

				$auto_settings       = gcargo_auto_shipment_settings();
				$fix_address_enabled = $auto_settings->get_setting_by_key( 'fix_address_enabled' );

				$request_data = $mapper->create_request();
				if ( $fix_address_enabled && isset( $request_data['customer'] ) ) {
					$request_data = $this->fix_address_for_shipment( $request_data );
				}

				return gcargo_shipments_resource()->store( $request_data );
			} catch ( Exception $e ) {
				$error_message = $e->getMessage();
				if ( $e instanceof GCARGO_Ajax_Validation_Exception ) {
					$error_message = $e->get_validation_errors()['message'];
				}
				$order = wc_get_order( $order_id );
				if ( $order ) {
					$order->update_meta_data( 'gcargo_shipment_error', 'Otomatik gönderi oluşturulamadı: ' . $error_message );
				}
			}
		}
	}

	/**
	 * Shipment mapper için adres düzenleme fonksiyonu.
	 *
	 * @param array $request_data Shipment request data.
	 */
	private function fix_address_for_shipment( $request_data ) {

		$customer = $request_data['customer'];

		$address_data = array(
			'address'  => $customer['address'] ?? '',
			'district' => $customer['district'] ?? '',
			'city'     => $customer['city'] ?? '',
			'country'  => $customer['country'] ?? '',
		);

		$api_response = gcargo_api_requests()->fix_address( $address_data );

		if ( $api_response && is_array( $api_response ) && isset( $api_response['formattedAddress'] ) ) {
			$fixed_address = $api_response['formattedAddress'];

			$request_data['customer']['address']  = $fixed_address['fullAddress'];
			$request_data['customer']['district'] = $fixed_address['district'];
			$request_data['customer']['city']     = $fixed_address['city'];
			$request_data['customer']['country']  = $fixed_address['country'];
		}

		return $request_data;
	}
}
