<?php

namespace Devurai\AcceptbluePaymentPro\Traits;

use Devurai\AcceptbluePaymentPro\Surcharge\SurchargeSettings;

trait SubscriptionFunctions
{
    protected function is_initial_subscription_order($order_id): bool
    {
        return wcs_order_contains_subscription($order_id) && !wcs_order_contains_renewal($order_id);
    }

    protected function save_surcharge_to_order(\WC_Subscription $subscription, SurchargeSettings $surcharge): void
    {

        $subscription->add_meta_data('_pgabfw_surcharge_settings', $surcharge->to_array());
        $subscription->save();
    }

    protected function get_surcharge_settings_from_order(\WC_Subscription $subscription): SurchargeSettings
    {
        return new SurchargeSettings((array) $subscription->get_meta('_pgabfw_surcharge_settings'));
    }

    protected function get_subscription_from_order($order_id, &$subscription): bool
    {
        $subscriptions = wcs_get_subscriptions_for_order($order_id, ['order_type' => 'renewal']);

        if (empty($subscriptions)) {
            $subscriptions = wcs_get_subscriptions_for_order($order_id);
        }

        if (!empty($subscriptions)) {
            $subscription = current($subscriptions);
            return true;
        }

        return false;
    }
}