<?php
/**
 * Matches an order for a customer who has no account.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wc;

use WC_Order;

/**
 * Both the order number and the billing email must match. There is no search by
 * email alone: it would be expensive on a large shop and would hand anyone an
 * order enumerator.
 */
final class GuestAccess
{
    /**
     * @return WC_Order|null
     */
    public static function match(string $reference, string $email)
    {
        $orderId = (int) preg_replace('/[^0-9]/', '', $reference);
        $email   = strtolower(trim($email));

        if ($orderId <= 0 || '' === $email) {
            return null;
        }

        $order = OrderLookup::byId($orderId);

        if (null === $order) {
            return null;
        }

        $billing = strtolower((string) $order->get_billing_email());

        if ('' === $billing || !hash_equals($billing, $email)) {
            return null;
        }

        return $order;
    }
}
