<?php
/**
 * AFD PCE Address Metadata Template for Customer Address Edit Form
 *
 * @var $block \Afd\Pce\Block\Customer\Address\Metadata
 */

// Only process if metadata is enabled in configuration
if (!$block->isMetadataEnabled()) {
    return;
}

// Get existing metadata for this address (if any)
$metadata = $block->getAddressMetadata();
$metadataJson = $metadata ? $block->getMetadataJson() : '{}';

// Get Precision Delivery config
$precisionDeliveryConfig = $block->getPrecisionDeliveryConfigJson();

// Get Cleanse on Submit config
$cleanseOnSubmitConfig = $block->getCleanseOnSubmitConfigJson();

// Get map data and metadata lat/lng for existing addresses
$isEditingExistingAddress = $block->isEditingExistingAddress();
$mapDataJson = $block->getMapDataJson();
$metadataLatLngJson = $block->getMetadataLatLngJson();
$addressId = $block->getAddressId();
?>

<!-- Address metadata fields -->
<?php
$captureFields = $block->getCaptureFields();
$captureFieldsJson = json_encode(is_array($captureFields) ? $captureFields : []);
?>
<div id="address-metadata-container" data-mage-init='{"addressMetadata": {
    "captureFields": <?= $captureFieldsJson ?>, 
    "precisionDeliveryConfig": <?= $precisionDeliveryConfig ?>,
    "isEditingExistingAddress": <?= $isEditingExistingAddress ? 'true' : 'false' ?>,
    "existingMapData": <?= $mapDataJson ?>,
    "existingMetadataLatLng": <?= $metadataLatLngJson ?>,
    "addressId": <?= $addressId ? $addressId : 'null' ?>
}}'>
    <!-- Hidden fields for metadata -->
    <input type="hidden" 
           id="customer-address-metadata" 
           name="customer-address-metadata" 
           value="<?= $block->escapeHtmlAttr($metadataJson) ?>" />
    
    <!-- Ensure metadata_enabled is always included -->
    <input type="hidden" id="metadata_enabled" name="metadata_enabled" value="1" />
</div>

<?php if ($block->isCleanseOnSubmitEnabled()): ?>
<!-- Cleanse on Submit for Customer Address Forms -->
<script type="text/x-magento-init">
{
    "*": {
        "Afd_Pce/js/customer/address/cleanse-on-submit": {
            "cleanseOnSubmit": <?= $cleanseOnSubmitConfig ?>
        }
    }
}
</script>
<?php endif; ?>
