<?php namespace Tussendoor\Reloadify\Helpers;

/**
 * Helper class for WooCommerce High-Performance Order Storage (HPOS) compatibility
 */
class HPOSHelper
{
    /**
     * Check if WooCommerce HPOS is enabled
     *
     * @return bool
     */
    public static function isHPOSEnabled(): bool
    {
        // Check if the WooCommerce class exists
        if (!class_exists('WooCommerce')) {
            return false;
        }

        // Check if the OrderUtil class exists
        if (!class_exists('\Automattic\WooCommerce\Utilities\OrderUtil')) {
            return false;
        }

        // Check if the custom_order_tables feature is enabled
        return \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();
    }

    /**
     * Get order metadata from either HPOS tables or legacy tables
     *
     * @param int $order_id Order ID
     * @param string $key Metadata key
     * @param bool $single Whether to return a single value
     * @return mixed
     */
    public static function getOrderMeta(int $order_id, string $key, bool $single = true)
    {
        // If HPOS is enabled, use the CRUD API
        if (self::isHPOSEnabled()) {
            $order = wc_get_order($order_id);
            if ($order) {
                return $order->get_meta($key, $single);
            }
            return $single ? '' : [];
        }

        // Otherwise, use the legacy get_post_meta function
        return get_post_meta($order_id, $key, $single);
    }

    /**
     * Update order metadata in either HPOS tables or legacy tables
     *
     * @param int $order_id Order ID
     * @param string $key Metadata key
     * @param mixed $value Metadata value
     * @return bool|int
     */
    public static function updateOrderMeta(int $order_id, string $key, $value)
    {
        // If HPOS is enabled, use the CRUD API
        if (self::isHPOSEnabled()) {
            $order = wc_get_order($order_id);
            if ($order) {
                $order->update_meta_data($key, $value);
                $order->save();
                return true;
            }
            return false;
        }

        // Otherwise, use the legacy update_post_meta function
        return update_post_meta($order_id, $key, $value);
    }

    /**
     * Delete order metadata from either HPOS tables or legacy tables
     *
     * @param int $order_id Order ID
     * @param string $key Metadata key
     * @return bool
     */
    public static function deleteOrderMeta(int $order_id, string $key)
    {
        // If HPOS is enabled, use the CRUD API
        if (self::isHPOSEnabled()) {
            $order = wc_get_order($order_id);
            if ($order) {
                $order->delete_meta_data($key);
                $order->save();
                return true;
            }
            return false;
        }

        // Otherwise, use the legacy delete_post_meta function
        return delete_post_meta($order_id, $key);
    }

    /**
     * Log HPOS-related errors
     *
     * @param string $message Error message
     * @return void
     */
    public static function logError(string $message): void
    {
        if (function_exists('wc_get_logger')) {
            $logger = wc_get_logger();
            $logger->error($message, ['source' => 'reloadify-hpos']);
        } else {
            error_log('Reloadify HPOS Error: ' . $message);
        }
    }

    /**
     * Show admin notice for HPOS-related errors
     *
     * @param string $message Error message
     * @param string $type Notice type (error, warning, success, info)
     * @return void
     */
    public static function showAdminNotice(string $message, string $type = 'error'): void
    {
        add_action('admin_notices', function () use ($message, $type) {
            echo '<div class="notice notice-' . esc_attr($type) . ' is-dismissible"><p>' . esc_html($message) . '</p></div>';
        });
    }

}
