<?php

declare (strict_types=1);
namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Builder;

use WC_Customer;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\State\CheckoutSessionDataRepository;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Violations\Violation;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Violations\Violations;
/**
 * Applies UCP buyer data to WooCommerce customer.
 *
 * @see https://ucp.dev/2026-01-23/schemas/shopping/types/buyer.json
 *
 * @phpstan-import-type Buyer from CheckoutSessionBuilder
 */
final class BuyerApplier
{
    private CheckoutSessionDataRepository $session_data;
    public function __construct(CheckoutSessionDataRepository $session_data)
    {
        $this->session_data = $session_data;
    }
    /**
     * @param Buyer       $buyer    UCP buyer object (consent is an extension field).
     * @param WC_Customer $customer WooCommerce customer.
     */
    public function apply(array $buyer, WC_Customer $customer): Violations
    {
        $violations = Violations::empty();
        $email_raw = \wp_unslash($buyer['email'] ?? '');
        $email = \sanitize_email($email_raw);
        if ('' === $email_raw) {
            // Email not provided.
            $violations = $violations->add(Violation::missing('A valid email address is required for order confirmation', 'buyer.email'));
        } elseif ('' === $email || !\is_email($email)) {
            // Email provided but invalid.
            $violations = $violations->add(Violation::invalid('Please provide a valid email address', 'buyer.email'));
        }
        $customer->set_billing_email($email);
        $first_name = \sanitize_text_field(\wp_unslash($buyer['first_name'] ?? ''));
        if ('' !== $first_name) {
            $customer->set_billing_first_name($first_name);
            $customer->set_shipping_first_name($first_name);
        }
        $last_name = \sanitize_text_field(\wp_unslash($buyer['last_name'] ?? ''));
        if ('' !== $last_name) {
            $customer->set_billing_last_name($last_name);
            $customer->set_shipping_last_name($last_name);
        }
        $phone = \sanitize_text_field(\wp_unslash($buyer['phone_number'] ?? ''));
        if ('' !== $phone) {
            $customer->set_billing_phone($phone);
        }
        $customer->save();
        $consent = $buyer['consent'] ?? null;
        if (\is_array($consent)) {
            $this->session_data->set_buyer_consent(['marketing' => (bool) ($consent['marketing'] ?? \false), 'analytics' => (bool) ($consent['analytics'] ?? \false), 'preferences' => (bool) ($consent['preferences'] ?? \false), 'sale_of_data' => (bool) ($consent['sale_of_data'] ?? \false)]);
        }
        return $violations;
    }
}
