<?php

/**
 * Enhances custom checkout fields for package delivery in WooCommerce.
 * This version registers fields for selecting a preferred delivery date and providing additional delivery instructions, such as gate codes or drop-off preferences.
 * It introduces input validation, sanitization, and better error handling.
 * Compatible with WooCommerce version 8.7 and up.
 * Documentation Reference: https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/checkout-block/additional-checkout-fields.md
 *
 * Prefix: cwpai
 * Text Domain: codewp
 */

add_action('woocommerce_blocks_loaded', function () {
    // Register a date picker field for the preferred delivery date
    __experimental_woocommerce_blocks_register_checkout_field([
        'id' => 'cwpai/delivery-date',
        'label' => __('Preferred Delivery Date', 'codewp'),
        'location' => 'address',
        'type' => 'text', // Use 'date' type if supported in future API versions
        'required' => true,
        'attributes' => [
            'pattern' => '\d{4}-\d{2}-\d{2}', // Ensures YYYY-MM-DD format
            'data-attribute' => 'delivery-date',
        ],
    ]);

    // Register a textarea field for additional delivery instructions
    __experimental_woocommerce_blocks_register_checkout_field([
        'id' => 'cwpai/delivery-instructions',
        'label' => __('Delivery Instructions', 'codewp'),
        'location' => 'address',
        'type' => 'text', // Change to 'textarea' if supported in future API versions
        'required' => false,
        'attributes' => [
            'data-attribute' => 'delivery-instructions',
        ],
    ]);
}, 10);

// Sanitization for the custom fields to ensure clean, safe input
add_action('_experimental_woocommerce_blocks_sanitize_additional_field', function ($field_value, $field_key) {
    if (in_array($field_key, ['cwpai/delivery-date', 'cwpai/delivery-instructions'])) {
        // Use WordPress's built-in function for text sanitization
        $field_value = sanitize_text_field($field_value);
    }
    return $field_value;
}, 10, 2);

// Custom validation for the delivery date to ensure it is a future date
add_action('__experimental_woocommerce_blocks_validate_additional_field', function ($errors, $field_key, $field_value) {
    if ('cwpai/delivery-date' === $field_key) {
        // Validate that the selected date is in the future
        if (strtotime($field_value) < time()) {
            $errors->add('invalid_delivery_date', __('Please choose a future date for delivery.', 'codewp'));
        }
    }
    return $errors;
}, 10, 3);