<?php

namespace Licenzo\Modules\EDD;

use Licenzo\Model\License;
use Licenzo\Model\Product;
use Licenzo\Services\Integrations\ProviderAliasService;

if (!defined('ABSPATH')) {
    exit;
}

class EddHelper
{
    public static function getCustomerData($order): array
    {
        $email = (string) $order->email;
        $eddCustomer = edd_get_customer_by('email', $email) ?: null;
        $nameParts = $eddCustomer ? explode(' ', (string) $eddCustomer->name, 2) : [];

        return [
            'email'      => $email,
            'first_name' => $nameParts[0] ?? '',
            'last_name'  => $nameParts[1] ?? '',
            'ip'         => (string) $order->ip,
        ];
    }

    public static function getOrderProducts($order): array
    {
        $products = [];
        $items = edd_get_order_items(['order_id' => $order->id, 'number' => 999]);

        foreach ($items as $item) {
            $downloadId = (int) $item->product_id;
            $priceId = $item->price_id !== null ? (int) $item->price_id : null;

            $dbProduct = Product::whereIn('provider', ProviderAliasService::eddAliases())
                ->where('provider_id', (string) $downloadId)
                ->first();

            $productData = [
                'id'         => $downloadId,
                'price_id'   => $priceId,
                'name'       => (string) $item->product_name,
                'price'      => (float) $item->total,
                'quantity'   => (int) $item->quantity,
                'db_product' => $dbProduct,
            ];

            if ($dbProduct) {
                $productData['type'] = $dbProduct->type;
                $productData['provider'] = $dbProduct->provider;
                $productData['product_link'] = $dbProduct->product_link;
            }

            $products[] = $productData;
        }

        return $products;
    }

    /**
     * Retrieve Licenzo licenses linked to an EDD order via stored meta.
     *
     * @return License[]
     */
    public static function getLicensesForOrder(int $orderId): array
    {
        $subscriptionIds = [];

        $subId = edd_get_order_meta($orderId, '_licenzo_subscription_id', true);
        if ($subId) {
            $subscriptionIds[] = (int) $subId;
        }

        $subIds = edd_get_order_meta($orderId, '_licenzo_subscription_ids', true);
        if (is_array($subIds)) {
            $subscriptionIds = array_merge($subscriptionIds, array_map('intval', $subIds));
        }

        $subscriptionIds = array_values(array_unique(array_filter($subscriptionIds)));
        if (empty($subscriptionIds)) {
            return [];
        }

        return License::whereIn('subscription_id', $subscriptionIds)
            ->with('subscription')
            ->get()
            ->all();
    }
}
