<?php

namespace BitApps\PiPro\src\Integrations\StoreEngine;

use BitApps\Pi\Helpers\Utility;
use StoreEngine\Utils\Helper;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}


final class StoreEngineHelper
{
    /**
     * Main entry for formatting purchased product fields.
     *
     * @param mixed $orderId
     * @param mixed $order
     * @param mixed $statusTransition
     * @param mixed $additionalData
     */
    public static function formatOrderData($orderId, $order, $statusTransition = [], $additionalData = [])
    {
        if (!self::isValidOrder($orderId, $order)) {
            return;
        }

        $userId = $order->get_customer_id();
        $items = $order->get_items();

        if (empty($items) || !\is_array($items)) {
            return;
        }

        $productData = array_map(
            function ($item) use ($userId) {
                return self::getProductDataFromItem($item, $userId);
            },
            $items
        );

        $data = array_merge(
            $additionalData,
            [
                'order_id'     => $orderId,
                'order_status' => $order->get_status(),
                'order_total'  => $order->get_total(),
                'currency'     => $order->get_currency(),
                'products'     => $productData,
            ]
        );

        $data['user'] = Utility::getUserInfo($userId);

        if (!empty($statusTransition)) {
            $data['status_transition'] = $statusTransition;
        }

        return $data;
    }

    /**
     * Validate if the order is usable.
     *
     * @param mixed $orderId
     * @param mixed $order
     */
    private static function isValidOrder($orderId, $order): bool
    {
        return !(
            empty($orderId)
            || empty($order)
            || !\is_object($order)
            || !method_exists($order, 'get_items')
            || !method_exists($order, 'get_customer_id')
            || !method_exists($order, 'get_status')
            || !method_exists($order, 'get_total')
            || !method_exists($order, 'get_currency')
        );
    }

    /**
     * Extract product + membership data from a single order item.
     *
     * @param mixed $item
     * @param mixed $userId
     */
    private static function getProductDataFromItem($item, $userId): array
    {
        if (
            !\is_object($item)
            || !method_exists($item, 'get_product_id')
            || !method_exists($item, 'get_price_id')
        ) {
            return [];
        }

        $productId = (int) $item->get_product_id();
        if (!$productId) {
            return [];
        }

        $product = get_post($productId);
        if (!$product) {
            return [];
        }

        return array_merge(
            (array) $product,
            [
                'permalink'         => get_permalink($productId),
                'featured_image_id' => get_post_thumbnail_id($productId) ?: null,
                'custom_metadata'   => self::getCustomMetadata($productId),
                'membership_data'   => self::getMembershipData($item, $userId)
            ]
        );
    }

    /**
     * Get product custom metadata.
     */
    private static function getCustomMetadata(int $productId): array
    {
        $customMeta = [];

        foreach (get_post_meta($productId) as $metaKey => $metaValue) {
            if (
                strpos($metaKey, '_storeengine_') === 0
                && !empty($metaValue[0])
            ) {
                $customMeta[ltrim($metaKey, '_')] = maybe_unserialize($metaValue[0]);
            }
        }

        return $customMeta;
    }

    /**
     * Extract membership plan + user membership data.
     *
     * @param mixed $item
     * @param mixed $userId
     */
    private static function getMembershipData($item, $userId): array
    {
        $result = [];

        if (!class_exists('\StoreEngine\Utils\Helper')) {
            return $result;
        }

        $membership = Helper::get_integration_repository_by_price_id(
            'storeengine/membership-addon',
            $item->get_price_id()
        );

        if (empty($membership->integration)) {
            return $result;
        }

        $membershipPlanId = $membership->integration->get_integration_id();
        $accessGroup = get_post($membershipPlanId);

        if (empty($accessGroup) || $accessGroup->post_type !== 'storeengine_groups') {
            return $result;
        }

        $result = [
            'membership_plan_id'   => $membershipPlanId,
            'membership_plan_name' => $accessGroup->post_title,
            'membership_plan_slug' => $accessGroup->post_name,
            'membership'           => array_filter(
                [
                    'user_roles'       => get_post_meta($membershipPlanId, '_storeengine_membership_user_roles', true),
                    'content_protects' => get_post_meta($membershipPlanId, '_storeengine_membership_content_protect_types', true),
                    'expiration'       => get_post_meta($membershipPlanId, '_storeengine_membership_expiration', true),
                    'priority'         => get_post_meta($membershipPlanId, '_storeengine_membership_priority', true),
                    'excluded_items'   => get_post_meta($membershipPlanId, '_storeengine_membership_content_protect_excluded_items', true),
                ]
            ),
        ];

        // User-specific membership data
        if ($userId) {
            $userMembershipData = get_user_meta($userId, '_storeengine_user_membership_data', true);

            if (!empty($userMembershipData[$membershipPlanId])) {
                $result['user_membership_data'] = $userMembershipData[$membershipPlanId];
            }
        }

        return $result;
    }
}
