<?php

namespace GriffinForms\Includes\Payments;

/**
 * Helper to build deterministic hashes for carts.
 */
class CartHasher
{
    use \GriffinForms\Traits\Singleton;

    /**
     * Compute cart and amount hashes for a normalized cart.
     *
     * @param array  $cart     Normalized cart from CartBuilder.
     * @param string $gateway  Gateway identifier.
     * @return array{cart_hash:string, amount_hash:string}
     */
    public function compute(array $cart, string $gateway): array
    {
        $items = [];
        if (!empty($cart['items']) && is_array($cart['items'])) {
            foreach ($cart['items'] as $entry) {
                $items[] = array(
                    'field_id'   => isset($entry['field_id']) ? (int) $entry['field_id'] : 0,
                    'product_id' => isset($entry['product_id']) ? sanitize_text_field($entry['product_id']) : '',
                    'qty'        => isset($entry['quantity']) ? (int) $entry['quantity'] : 0,
                    'unit_price' => isset($entry['unit_price']) ? (float) $entry['unit_price'] : 0.0,
                    'subtotal'   => isset($entry['subtotal']) ? (float) $entry['subtotal'] : 0.0,
                    'currency'   => isset($entry['currency']) ? sanitize_text_field($entry['currency']) : '',
                );
            }
        }

        // Sort items deterministically.
        usort($items, function ($a, $b) {
            return [$a['field_id'], $a['product_id']] <=> [$b['field_id'], $b['product_id']];
        });

        $base = array(
            'gateway'   => sanitize_key($gateway),
            'items'     => $items,
            'subtotal'  => isset($cart['subtotal']) ? (float) $cart['subtotal'] : 0.0,
            'tax_total' => isset($cart['tax_total']) ? (float) $cart['tax_total'] : 0.0,
            'total'     => isset($cart['total']) ? (float) $cart['total'] : 0.0,
            'currency'  => isset($cart['currency']) ? sanitize_text_field($cart['currency']) : '',
        );

        $encoded = wp_json_encode($base);
        $cart_hash = hash('sha256', (string) $encoded);

        $amount_base = array(
            'total'    => $base['total'],
            'currency' => $base['currency'],
            'gateway'  => $base['gateway'],
        );
        $amount_hash = hash('sha256', (string) wp_json_encode($amount_base));

        return [
            'cart_hash'   => $cart_hash,
            'amount_hash' => $amount_hash,
        ];
    }
}
