<?php

/**
 * WooCommerce Store API integration for subscription cart items.
 *
 * @package ArraySubs\Features\SubscriptionProducts\Services
 */

namespace ArraySubs\Features\SubscriptionProducts\Services;

defined('ABSPATH') || exit;

use Automattic\WooCommerce\StoreApi\Schemas\V1\CartItemSchema;

/**
 * Expose subscription data needed by WooCommerce Blocks.
 */
class StoreApiIntegration
{
    /**
     * Enable auto-loading.
     *
     * @var bool
     */
    public static $loadable = true;

    /**
     * Constructor.
     */
    public function __construct()
    {
        if (did_action('woocommerce_blocks_loaded')) {
            $this->registerCartItemData();
            return;
        }

        add_action('woocommerce_blocks_loaded', [$this, 'registerCartItemData']);
    }

    /**
     * Register subscription cart item extension data.
     *
     * @return void
     */
    public function registerCartItemData(): void
    {
        if (!function_exists('woocommerce_store_api_register_endpoint_data')) {
            return;
        }

        if (!class_exists(CartItemSchema::class)) {
            return;
        }

        woocommerce_store_api_register_endpoint_data(
            [
                'endpoint'        => CartItemSchema::IDENTIFIER,
                'namespace'       => 'arraysubs_subscription',
                'schema_callback' => [$this, 'getCartItemSchema'],
                'data_callback'   => [$this, 'getCartItemData'],
                'schema_type'     => ARRAY_A,
            ]
        );
    }

    /**
     * Get Store API schema additions for subscription cart items.
     *
     * @return array
     */
    public function getCartItemSchema(): array
    {
        return [
            'has_trial'      => [
                'description' => __('Whether the subscription cart item starts with a free trial.', 'arraysubs'),
                'type'        => 'boolean',
                'readonly'    => true,
                'context'     => ['view'],
            ],
            'trial_schedule' => [
                'description' => __('The formatted free-trial duration for the subscription cart item.', 'arraysubs'),
                'type'        => 'string',
                'readonly'    => true,
                'context'     => ['view'],
            ],
        ];
    }

    /**
     * Get subscription extension data for a Store API cart item.
     *
     * @param array $cart_item WooCommerce cart item.
     * @return array
     */
    public function getCartItemData($cart_item): array
    {
        $empty_data = [
            'has_trial'      => false,
            'trial_schedule' => '',
        ];

        if (!is_array($cart_item)) {
            return $empty_data;
        }

        $subscription_data = arraysubs_get_cart_item_subscription_data($cart_item);

        if (!is_array($subscription_data)) {
            return $empty_data;
        }

        $trial_length = (int) ($subscription_data['trial_length'] ?? 0);
        $trial_period = (string) ($subscription_data['trial_period'] ?? '');
        $is_lifetime = ($subscription_data['period'] ?? '') === 'lifetime';

        if ($is_lifetime || $trial_length <= 0 || $trial_period === '') {
            return $empty_data;
        }

        return [
            'has_trial'      => true,
            'trial_schedule' => arraysubs_get_duration_string($trial_length, $trial_period),
        ];
    }
}
