<?php

namespace FKWCSQ\Includes\Conversions;

abstract class Conversion {
	protected $meta_token_key = '_square_payment_token';
	protected $meta_customer_key = '_square_customer_id';
	protected $meta_location_key = '_square_location_id';

	public function get_payment_token( $renewal_order, $subscription ) {

		return $this->get_subscription_meta_value( $renewal_order, $subscription, $this->meta_token_key );
	}

	public function get_customer_id( $renewal_order, $subscription ) {
		return $this->get_subscription_meta_value( $renewal_order, $subscription, $this->meta_customer_key );
	}

	public function get_location_id( $renewal_order, $subscription ) {
		return $this->get_subscription_meta_value( $renewal_order, $subscription, $this->meta_location_key );
	}

	protected function get_subscription_meta_value( $renewal_order, $subscription, $meta_key ) {
		// Try renewal order first
		$value = $renewal_order->get_meta( $meta_key );
		if ( ! empty( $value ) ) {
			return $value;
		}

		// Then try subscription if available
		if ( $subscription ) {
			$value = $subscription->get_meta( $meta_key );
			if ( ! empty( $value ) ) {
				return $value;
			}

			// Try parent order if subscription exists
			$parent_order = wc_get_order( $subscription->get_parent_id() );
			if ( $parent_order ) {
				$value = $parent_order->get_meta( $meta_key );
				if ( ! empty( $value ) ) {
					return $value;
				}
			}
		}

		return null;
	}
}
