<?php

namespace BitApps\PiPro\src\Integrations\FluentCart;

use FluentCart\App\Models\Product;
use FluentCart\App\Models\Customer;
use FluentCart\App\Models\ShippingClass;
use BitApps\Pi\Deps\BitApps\WPValidator\Validator;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Response;

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


final class FluentCartHelper
{
    /**
     * Convert an object to array safely.
     *
     * @param array|object|string $data
     *
     * @return array
     */
    public static function prepareData($data)
    {
        return (\is_object($data) && method_exists($data, 'toArray')) ? $data->toArray() : (array) $data;
    }

    /**
     * Parse comma separated values.
     *
     * @param array|string $value
     *
     * @return array
     */
    public static function parseCommaSeparatedValues($value)
    {
        return empty($value) ? [] : array_map('intval', array_map('trim', \is_array($value) ? $value : explode(',', $value)));
    }

    /**
     * Validate class existence.
     *
     * @param array|string $classNames
     * @param null|array $payload
     *
     * @return null|array
     */
    public static function validateClassExistence($classNames, $payload = [])
    {
        if (\is_string($classNames)) {
            $classNames = [$classNames];
        }

        $classPaths = [
            'order'             => 'FluentCart\App\Models\Order',
            'order_transaction' => 'FluentCart\App\Models\OrderTransaction',
            'order_item'        => 'FluentCart\App\Models\OrderItem',
            'customer'          => 'FluentCart\App\Models\Customer',
            'product'           => 'FluentCart\App\Models\Product',
            'product_detail'    => 'FluentCart\App\Models\ProductDetail',
            'product_variation' => 'FluentCart\App\Models\ProductVariation',
            'coupon'            => 'FluentCart\App\Models\Coupon',
            'shipping_class'    => 'FluentCart\App\Models\ShippingClass',
            'license'           => 'FluentCartPro\App\Modules\Licensing\Models\License',
        ];

        foreach ($classNames as $class) {
            if (empty($classPaths[$class]) || !class_exists($classPaths[$class])) {
                return [
                    // translators: %s: Class name
                    'response'    => \sprintf(__('FluentCart class %s is not available.', 'bit-pi'), $class),
                    'payload'     => $payload,
                    'status_code' => 400
                ];
            }
        }
    }

    /**
     * Validate field map.
     *
     * @param array $fieldMappings
     * @param array $rules
     * @param array $payload
     */
    public static function validateFieldMap($fieldMappings, $rules, $payload = null)
    {
        $validator = new Validator();
        $validation = $validator->make($fieldMappings, $rules);

        if ($validation->fails()) {
            return [
                'response'    => $validation->errors(),
                'payload'     => $payload ?? $fieldMappings,
                'status_code' => 400
            ];
        }
    }

    /**
     * Process gallery images.
     *
     * @param array|string $galleryImageIds
     * @param int $productId
     */
    public static function processGalleryImages($galleryImageIds, $productId): void
    {
        if (empty($galleryImageIds)) {
            return;
        }

        $galleryImageIds = \is_array($galleryImageIds)
            ? $galleryImageIds
            : explode(',', $galleryImageIds);

        $galleryImageIds = array_map('intval', array_map('trim', $galleryImageIds));

        $gallery = [];
        foreach ($galleryImageIds as $imageId) {
            if ($imageURL = wp_get_attachment_url($imageId)) {
                $gallery[] = [
                    'id'    => $imageId,
                    'title' => get_the_title($imageId) ?? '',
                    'url'   => $imageURL,
                ];
            }
        }

        if (\count($gallery)) {
            update_post_meta($productId, 'fluent-products-gallery-image', $gallery);
            set_post_thumbnail($productId, reset($gallery)['id']);
        }
    }

    /**
     * Get FluentCart customers.
     */
    public static function getCustomers()
    {
        if ($validationResponse = self::validateClassExistence('customer')) {
            return Response::error($validationResponse);
        }

        $customers = array_map(
            function (array $customer) {
                return [
                    'value' => $customer['id'],
                    'label' => $customer['full_name'] ?? $customer['email'],
                ];
            },
            Customer::all()->toArray() ?? []
        );

        return Response::success($customers);
    }

    /**
     *  Get FluentCart products.
     */
    public static function getProducts()
    {
        if ($validationResponse = self::validateClassExistence('product')) {
            return Response::error($validationResponse);
        }

        $products = array_map(
            function (array $product) {
                return [
                    'value' => $product['ID'],
                    'label' => $product['post_title'],
                ];
            },
            Product::all()->toArray() ?? []
        );

        return Response::success($products);
    }

    /**
     * Get FluentCart product categories.
     */
    public static function getProductCategories()
    {
        $categories = get_terms(
            [
                'taxonomy'   => 'product-categories',
                'hide_empty' => false,
                'orderby'    => 'name',
                'order'      => 'ASC',
            ]
        );

        if (is_wp_error($categories)) {
            return Response::error($categories->get_error_message());
        }

        $data = array_map(
            function ($category) {
                return [
                    'value' => $category->term_id,
                    'label' => $category->name,
                ];
            },
            $categories ?? []
        );

        return Response::success($data);
    }

    /**
     * Get FluentCart product types.
     */
    public static function getProductBrands()
    {
        $brands = get_terms(
            [
                'taxonomy'   => 'product-brands',
                'hide_empty' => false,
                'orderby'    => 'name',
                'order'      => 'ASC',
            ]
        );

        if (is_wp_error($brands)) {
            return Response::error($brands->get_error_message());
        }

        $data = array_map(
            function ($brand) {
                return [
                    'value' => $brand->term_id,
                    'label' => $brand->name,
                ];
            },
            $brands ?? []
        );

        return Response::success($data);
    }

    /**
     * Get FluentCart shipping classes.
     */
    public static function getShippingClass()
    {
        if ($validationResponse = self::validateClassExistence('shipping_class')) {
            return Response::error($validationResponse);
        }

        $shippingClasses = array_map(
            function (array $shippingClass) {
                return [
                    'value' => $shippingClass['id'],
                    'label' => $shippingClass['name'],
                ];
            },
            ShippingClass::all()->toArray() ?? []
        );

        return Response::success($shippingClasses);
    }
}
