<?php

use function WcElectronInvoice\Functions\setFormattedInvoiceNumber;

if ( ! function_exists( 'pop_pmpro_get_order_invoice_fields_for_display' ) ) {
    /**
     * Build POP billing fields for PMPro order display.
     *
     * @param \MemberOrder $order
     *
     * @return array
     */
    function pop_pmpro_get_order_invoice_fields_for_display( $order ) {
        $popPmproInvoiceFields = [];
        $isPeppolContext       = \WcElectronInvoice\Integrations::isPeppolContext();
        $fields                = apply_filters( 'wc_el_inv-billing_fields', [] );

        foreach ( $fields as $field_name => $field ) {
            if ( $isPeppolContext && in_array( $field_name, [ 'billing_sdi_type', 'billing_tax_code' ], true ) ) {
                continue;
            }

            if ( 'billing_vat_number' === $field_name ) {
                $popPmproInvoiceFields[] = [
                    'id'      => 'billing_company',
                    'label'   => __( 'Name of the company', WC_EL_INV_TEXTDOMAIN ),
                    'type'    => 'text',
                    'class'   => 'input',
                    'hint'    => '',
                    'default' => '',
                    'value'   => get_pmpro_membership_order_meta( $order->id, 'billing_company', true ),
                ];
            }

            $field['hint']           = $field['description'];
            $field['profile']        = true;
            $field['memberslistcsv'] = true;
            $field['class']          = implode( ' ', array_filter( $field['class'] ) );

            if ( isset( $field['default'] ) ) {
                $field['default'] = apply_filters( "wc_el_inv-{$field_name}_default", $field['default'] );
            }

            $storedValue = get_pmpro_membership_order_meta( $order->id, $field['id'], true );
            if ( 'select' === $field['type'] && isset( $field['options'][ $storedValue ] ) ) {
                $field['value'] = (string) $field['options'][ $storedValue ];
            } else {
                $field['value'] = '' !== (string) $storedValue ? $storedValue : ( $field['default'] ?? '' );
            }

            $popPmproInvoiceFields[] = $field;
        }

        return $popPmproInvoiceFields;
    }
}

if ( ! function_exists( 'pop_pmpro_get_order_invoice_data_for_display' ) ) {
    /**
     * Build POP invoice data for PMPro order display.
     *
     * @param \MemberOrder $order
     *
     * @return array
     */
    function pop_pmpro_get_order_invoice_data_for_display( $order ) {
        $invoice_number = get_pmpro_membership_order_meta( $order->id, 'order_number_invoice', true );
        $invoice_date   = get_pmpro_membership_order_meta( $order->id, 'order_date_invoice', true );
        $nature_rc      = get_pmpro_membership_order_meta( $order->id, 'nature_rc', true );
        $ref_norm_rc    = get_pmpro_membership_order_meta( $order->id, 'ref_norm_rc', true );

        $displayInvoiceDate = '';
        if ( ! empty( $invoice_date ) ) {
            try {
                $displayInvoiceDate = ( new \DateTime( $invoice_date ) )->format( 'Y-m-d H:i:s' );
            } catch ( \Exception $e ) {
                $displayInvoiceDate = (string) $invoice_date;
            }
        }

        $fields = [
            [
                'label' => __( 'Invoice number', WC_EL_INV_TEXTDOMAIN ),
                'value' => $invoice_number,
            ],
            [
                'label' => __( 'Invoice Date', WC_EL_INV_TEXTDOMAIN ),
                'value' => $displayInvoiceDate,
            ],
            [
                'label' => __( 'Operation\'s Nature', WC_EL_INV_TEXTDOMAIN ),
                'value' => $nature_rc,
            ],
        ];

        if ( \WcElectronInvoice\WooCommerce\Fields\ReverseChargeSettings::shouldDisplayRefNormRc() ) {
            $fields[] = [
                'label' => __( 'Tax rule reference', WC_EL_INV_TEXTDOMAIN ),
                'value' => $ref_norm_rc,
            ];
        }

        return $fields;
    }
}

add_action('pmpro_after_order_settings_table', function ($order) {
    /* @var \MemberOrder $order */
    $pop_pmproInvoiceFields = pop_pmpro_get_order_invoice_fields_for_display( $order );
    ?>
    <!-- Invoice fields -->
    <div class="pmpro_section" data-visibility="shown" data-activated="true">
        <div class="pmpro_section_toggle">
            <button class="pmpro_section-toggle-button" type="button" aria-expanded="true">
                <span class="dashicons dashicons-arrow-up-alt2"></span>
                <?php esc_html_e('Invoice Fields', WC_EL_INV_TEXTDOMAIN); ?>
            </button>
        </div>
        <div class="pmpro_section_inside">
            <p><?php esc_html_e('These fields are used by POP to collect billing information for the user\'s invoices.',
                    WC_EL_INV_TEXTDOMAIN); ?></p>
            <table class="form-table">
                <tbody>
                <tr>
                    <?php foreach ($pop_pmproInvoiceFields

                    as $field) : ?>
                    <th scope="row" valign="top"><label
                                for="<?php esc_attr_e($field['id']) ?>"><?php esc_html_e($field['label']) ?></label>
                    </th>
                    <td>
                        <?php if ($field['type'] === 'select') : ?>
                            <select id="<?php esc_attr_e($field['id']) ?>" name="<?php esc_attr_e($field['id']) ?>"
                                    class="<?php esc_attr_e($field['class']) ?>">
                                <?php foreach ($field['options'] as $key => $value) : ?>
                                    <option value="<?php esc_attr_e($key) ?>" <?php selected($key,
                                        get_pmpro_membership_order_meta($order->id, $field['id'],
                                            true)) ?>><?php esc_html_e($value) ?></option>
                                <?php endforeach; ?>
                            </select>
                        <?php elseif ($field['type'] === 'text') : ?>
                            <input type="text" size="30" id="<?php esc_attr_e($field['id']) ?>"
                                   name="<?php esc_attr_e($field['id']) ?>" class="<?php esc_attr_e($field['class']) ?>"
                                   value="<?php esc_attr_e(get_pmpro_membership_order_meta($order->id, $field['id'],
                                       true)) ?>">
                        <?php endif; ?>
                        <p class="description"><?php esc_html_e($field['hint']) ?></p>
                    </td>
                </tr>
                <?php endforeach; ?>
                <tr>
                    <th scope="row" valign="top">
                        <label><?php esc_html_e( 'User Billing Sync', WC_EL_INV_TEXTDOMAIN ); ?></label>
                    </th>
                    <td>
                        <button type="submit"
                                name="pop_pmpro_sync_from_user"
                                value="fill_missing"
                                class="button button-secondary">
							<?php esc_html_e( 'Recover Missing Data From User', WC_EL_INV_TEXTDOMAIN ); ?>
                        </button>
                        <button type="submit"
                                name="pop_pmpro_sync_from_user"
                                value="overwrite"
                                class="button button-secondary">
							<?php esc_html_e( 'Overwrite From User', WC_EL_INV_TEXTDOMAIN ); ?>
                        </button>
                        <p class="description">
							<?php esc_html_e( 'Use these actions to sync POP billing fields from the linked user profile.', WC_EL_INV_TEXTDOMAIN ); ?>
                        </p>
                    </td>
                </tr>
                </tbody>
            </table>
        </div> <!-- end pmpro_section_inside -->
    </div> <!-- end pmpro_section -->

    <?php
    $invoice_number = get_pmpro_membership_order_meta($order->id, 'order_number_invoice', true);
    $invoice_date   = get_pmpro_membership_order_meta($order->id, 'order_date_invoice', true);
    $nature_rc      = get_pmpro_membership_order_meta($order->id, 'nature_rc', true);
    $ref_norm_rc    = get_pmpro_membership_order_meta($order->id, 'ref_norm_rc', true);

    $defaultTimestamp = method_exists($order, 'getTimestamp')
        ? $order->getTimestamp()
        : (isset($order->timestamp) ? (int)$order->timestamp : current_time('timestamp'));

    try {
        $invoiceDateObj = new \DateTime($invoice_date ?: date('Y-m-d H:i:s', $defaultTimestamp));
    } catch (\Exception $e) {
        $invoiceDateObj = new \DateTime(date('Y-m-d H:i:s', $defaultTimestamp));
    }

    $order_date_invoice   = $invoiceDateObj->format('Y-m-d');
    $order_hours_invoice  = $invoiceDateObj->format('H');
    $order_minutes_invoice = $invoiceDateObj->format('i');
    ?>
    <!-- Invoice number -->
    <div class="pmpro_section" data-visibility="shown" data-activated="true">
        <div class="pmpro_section_toggle">
            <button class="pmpro_section-toggle-button" type="button" aria-expanded="true">
                <span class="dashicons dashicons-arrow-up-alt2"></span>
                <span class="pmpro_section-header">
                    <span class="pmpro_section-title"><?php esc_html_e('Invoice Data', WC_EL_INV_TEXTDOMAIN); ?></span>
                </span>
            </button>
        </div>
        <div class="pmpro_section_inside">
            <table class="form-table">
                <tbody>
                <tr>
                    <th scope="row">
                        <label for="order_number_invoice"><?php esc_html_e('Invoice number', WC_EL_INV_TEXTDOMAIN); ?></label>
                    </th>
                    <td>
                        <input type="text"
                               name="order_number_invoice"
                               id="order_number_invoice"
                               value="<?php echo esc_attr($invoice_number); ?>"
                               class="regular-text"/>
                        <p class="description"><?php esc_html_e('Progressive number of the electronic invoice associated with this order.', WC_EL_INV_TEXTDOMAIN); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="order_date_invoice"><?php esc_html_e('Invoice Date', WC_EL_INV_TEXTDOMAIN); ?></label>
                    </th>
                    <td>
                        <input type="date"
                               name="order_date_invoice"
                               id="order_date_invoice"
                               value="<?php echo esc_attr($order_date_invoice); ?>"/>
                        <input type="number"
                               min="0"
                               max="23"
                               name="order_hours_invoice"
                               id="order_hours_invoice"
                               value="<?php echo esc_attr($order_hours_invoice); ?>"
                               class="small-text"/>
                        <span class="minutes">:</span>
                        <input type="number"
                               min="0"
                               max="59"
                               name="order_minutes_invoice"
                               id="order_minutes_invoice"
                               value="<?php echo esc_attr($order_minutes_invoice); ?>"
                               class="small-text"/>
                        <p class="description"><?php esc_html_e('Timestamp used as completed date for this order. Automatically set when the order is marked successful.', WC_EL_INV_TEXTDOMAIN); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="nature_rc"><?php esc_html_e('Operation\'s Nature', WC_EL_INV_TEXTDOMAIN); ?></label>
                    </th>
                    <td>
                        <input type="text"
                               name="nature_rc"
                               id="nature_rc"
                               value="<?php echo esc_attr($nature_rc); ?>"
                               class="regular-text"/>
                        <p class="description"><?php esc_html_e('Reverse charge nature used in the invoice XML.', WC_EL_INV_TEXTDOMAIN); ?></p>
                    </td>
                </tr>
                <?php if ( \WcElectronInvoice\WooCommerce\Fields\ReverseChargeSettings::shouldDisplayRefNormRc() ) : ?>
                <tr>
                    <th scope="row">
                        <label for="ref_norm_rc"><?php esc_html_e('Tax rule reference', WC_EL_INV_TEXTDOMAIN); ?></label>
                    </th>
                    <td>
                        <input type="text"
                               name="ref_norm_rc"
                               id="ref_norm_rc"
                               value="<?php echo esc_attr($ref_norm_rc); ?>"
                               class="regular-text"/>
                        <p class="description"><?php esc_html_e('Tax rule reference saved with this order.', WC_EL_INV_TEXTDOMAIN); ?></p>
                    </td>
                </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php
    $enable_tax_calculation = (bool)get_option('pop_pmpro_enable_tax_calculation');
    $taxRegime              = \WcElectronInvoice\WooCommerce\Fields\GeneralFields::getGeneralInvoiceOptionTaxRegime();
    $shopCountry            = \WcElectronInvoice\WooCommerce\Fields\GeneralFields::getGeneralInvoiceOptionCountryState();
    if ( ! \WcElectronInvoice\WooCommerce\Fields\GeneralFields::isItalianShop() ) {
      return;
    }
    if ($enable_tax_calculation) {
        return;
    }
    if (! in_array($taxRegime, ['RF19', 'RF02'], true)) {
        return;
    }
    $stamp_duty_fee_value = get_pmpro_membership_order_meta($order->id, 'stamp_duty_fee_value', true);
    $rivalsa_fee_value    = get_pmpro_membership_order_meta($order->id, 'rivalsa_fee_value', true);
    ?>
    <!-- Bollo e Rivalsa -->
    <div class="pmpro_section" data-visibility="shown" data-activated="true">
        <div class="pmpro_section_toggle">
            <button class="pmpro_section-toggle-button" type="button" aria-expanded="true">
                <span class="pmpro_section-header">
                    <span class="pmpro_section-title"><?php echo __('Stamp Duty and Rivalsa', WC_EL_INV_TEXTDOMAIN); ?></span>
                </span>
            </button>
        </div>
        <div class="pmpro_section_inside">
            <table class="form-table">
                <tbody>
                <tr>
                    <th scope="row">
                        <label for="stamp_duty_fee_value"><?php echo __('Stamp Duty (€)', WC_EL_INV_TEXTDOMAIN); ?></label>
                    </th>
                    <td>
                        <input type="number"
                               step="0.01"
                               name="stamp_duty_fee_value"
                               id="stamp_duty_fee_value"
                               value="<?php echo esc_attr($stamp_duty_fee_value); ?>"
                               class="small-text"
                               readonly="readonly"
                               disabled="disabled"/>
                        <p class="description"><?php echo __('This value is determined at checkout and is shown here for reference only. Editing it after payment could make the document inconsistent with the amount actually paid.', WC_EL_INV_TEXTDOMAIN); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="rivalsa_fee_value"><?php echo __('INPS Withholding (€)', WC_EL_INV_TEXTDOMAIN); ?></label>
                    </th>
                    <td>
                        <input type="number"
                               step="0.01"
                               name="rivalsa_fee_value"
                               id="rivalsa_fee_value"
                               value="<?php echo esc_attr($rivalsa_fee_value); ?>"
                               class="small-text"
                               readonly="readonly"
                               disabled="disabled"/>
                        <p class="description"><?php echo __('This value is determined at checkout and is shown here for reference only. Editing it after payment could make the document inconsistent with the amount actually paid.', WC_EL_INV_TEXTDOMAIN); ?></p>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>

    <?php
});

add_action( 'pmpro_after_order_view_main', function ( $order ) {
    /* @var \MemberOrder $order */
    $invoiceFields = pop_pmpro_get_order_invoice_fields_for_display( $order );
    $invoiceData   = pop_pmpro_get_order_invoice_data_for_display( $order );
    ?>
    <div id="pmpro_order-view-pop-billing" class="pmpro_section" data-visibility="shown" data-activated="true">
        <div class="pmpro_section_toggle">
            <button class="pmpro_section-toggle-button" type="button" aria-expanded="true">
                <span class="dashicons dashicons-arrow-up-alt2"></span>
                <?php esc_html_e( 'Invoice Fields', WC_EL_INV_TEXTDOMAIN ); ?>
            </button>
        </div>
        <div class="pmpro_section_inside">
            <ul class="pmpro_list pmpro_list-plain pmpro_list-with-labels pmpro_cols-2">
                <?php foreach ( $invoiceFields as $field ) : ?>
                    <li class="pmpro_list_item">
                        <span class="pmpro_list_item_label"><?php echo esc_html( $field['label'] ); ?></span>
                        <?php
                        $value = isset( $field['value'] ) ? (string) $field['value'] : '';
                        echo '' !== $value ? esc_html( $value ) : esc_html__( 'N/A', 'paid-memberships-pro' );
                        ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>

    <div id="pmpro_order-view-pop-invoice-data" class="pmpro_section" data-visibility="shown" data-activated="true">
        <div class="pmpro_section_toggle">
            <button class="pmpro_section-toggle-button" type="button" aria-expanded="true">
                <span class="dashicons dashicons-arrow-up-alt2"></span>
                <?php esc_html_e( 'Invoice Data', WC_EL_INV_TEXTDOMAIN ); ?>
            </button>
        </div>
        <div class="pmpro_section_inside">
            <ul class="pmpro_list pmpro_list-plain pmpro_list-with-labels pmpro_cols-2">
                <?php foreach ( $invoiceData as $row ) : ?>
                    <li class="pmpro_list_item">
                        <span class="pmpro_list_item_label"><?php echo esc_html( $row['label'] ); ?></span>
                        <?php
                        $value = isset( $row['value'] ) ? (string) $row['value'] : '';
                        echo '' !== $value ? esc_html( $value ) : esc_html__( 'N/A', 'paid-memberships-pro' );
                        ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>
    <?php
} );

if ( ! function_exists( 'pop_pmpro_get_order_refund_data_for_display' ) ) {
    /**
     * Build POP credit note (refund) data for PMPro order display.
     *
     * @param \MemberOrder $order
     *
     * @return array
     */
    function pop_pmpro_get_order_refund_data_for_display( $order ) {
        $orderId              = $order->id;
        $refund_number        = get_pmpro_membership_order_meta( $orderId, "refund_number_invoice-{$orderId}", true );
        $refunded_date       = get_pmpro_membership_order_meta( $orderId, 'refunded_date', true );
        $refund_invoice_sent = get_pmpro_membership_order_meta( $orderId, 'refund_invoice_sent', true );

        $displayRefundDate = '';
        if ( ! empty( $refunded_date ) ) {
            try {
                $displayRefundDate = ( new \DateTime( $refunded_date ) )->format( 'Y-m-d H:i:s' );
            } catch ( \Exception $e ) {
                $displayRefundDate = (string) $refunded_date;
            }
        }

        return [
            [
                'label' => __( 'Credit Note Number', WC_EL_INV_TEXTDOMAIN ),
                'value' => $refund_number,
            ],
            [
                'label' => __( 'Credit Note Date', WC_EL_INV_TEXTDOMAIN ),
                'value' => $displayRefundDate,
            ],
        ];
    }
}

if ( ! function_exists( 'pop_pmpro_get_cached_document_rows_for_display' ) ) {
    /**
     * Build cached generated file rows for PMPro order display.
     *
     * @param \MemberOrder $order
     *
     * @return array
     */
    function pop_pmpro_get_cached_document_rows_for_display( $order ) {
        $providerOrder = \WcElectronInvoice\Providers\OrderQuery::instance()->getProviderOrder( $order->id, 'pmpro' );
        if ( ! ( $providerOrder instanceof \POPxPMPro\Providers\Order ) ) {
            return [];
        }

        return \WcElectronInvoice\Functions\getCachedDocumentAttachmentDisplayEntries( $providerOrder, true );
    }
}

if ( ! function_exists( 'pop_pmpro_render_cached_document_section' ) ) {
    /**
     * Render PMPro cached generated file section.
     *
     * @param \MemberOrder $order
     *
     * @return void
     */
    function pop_pmpro_render_cached_document_section( $order ) {
        $rows = pop_pmpro_get_cached_document_rows_for_display( $order );
        ?>
        <div class="pmpro_section" data-visibility="shown" data-activated="true">
            <div class="pmpro_section_toggle">
                <button class="pmpro_section-toggle-button" type="button" aria-expanded="true">
                    <span class="dashicons dashicons-arrow-up-alt2"></span>
                    <?php esc_html_e( 'Generated Files Cache', WC_EL_INV_TEXTDOMAIN ); ?>
                </button>
            </div>
            <div class="pmpro_section_inside">
                <p><?php esc_html_e( 'These cached files are cleared automatically when order data changes and are rebuilt on the next document generation.', WC_EL_INV_TEXTDOMAIN ); ?></p>
                <?php if ( empty( $rows ) ) : ?>
                    <p><?php esc_html_e( 'No cached generated files are currently stored for this order.', WC_EL_INV_TEXTDOMAIN ); ?></p>
                <?php else : ?>
                    <ul class="pmpro_list pmpro_list-plain pmpro_list-with-labels">
                        <?php foreach ( $rows as $row ) : ?>
                            <li class="pmpro_list_item">
                                <span class="pmpro_list_item_label"><?php echo esc_html( $row['document_label'] . ' ' . $row['format_label'] ); ?></span>
                                <code><?php echo esc_html( $row['relative_path'] ); ?></code>
                                <br/>
                                <small><?php echo esc_html( $row['exists'] ? __( 'Available on disk', WC_EL_INV_TEXTDOMAIN ) : __( 'Meta present but file missing', WC_EL_INV_TEXTDOMAIN ) ); ?></small>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }
}

add_action( 'pmpro_after_order_view_main', function ( $order ) {
    /* @var \MemberOrder $order */
    $refundData    = pop_pmpro_get_order_refund_data_for_display( $order );
    ?>
    <div id="pmpro_order-view-pop-refund-data" class="pmpro_section" data-visibility="shown" data-activated="true">
        <div class="pmpro_section_toggle">
            <button class="pmpro_section-toggle-button" type="button" aria-expanded="true">
                <span class="dashicons dashicons-arrow-up-alt2"></span>
                <?php esc_html_e( 'Credit Note Data', WC_EL_INV_TEXTDOMAIN ); ?>
            </button>
        </div>
        <div class="pmpro_section_inside">
            <ul class="pmpro_list pmpro_list-plain pmpro_list-with-labels pmpro_cols-2">
                <?php foreach ( $refundData as $row ) : ?>
                    <li class="pmpro_list_item">
                        <span class="pmpro_list_item_label"><?php echo esc_html( $row['label'] ); ?></span>
                        <?php
                        $value = isset( $row['value'] ) ? (string) $row['value'] : '';
                        echo '' !== $value ? esc_html( $value ) : esc_html__( 'N/A', 'paid-memberships-pro' );
                        ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>
    <?php
}, 15 );

add_action( 'pmpro_after_order_view_main', function ( $order ) {
    pop_pmpro_render_cached_document_section( $order );
}, 20 );

// Edit section for Credit Note (only if refund number exists)
add_action( 'pmpro_after_order_settings_table', function ( $order ) {
    /* @var \MemberOrder $order */
    $orderId        = $order->id;
    $refund_number  = get_pmpro_membership_order_meta( $orderId, "refund_number_invoice-{$orderId}", true );

    if ( empty( $refund_number ) ) {
        return;
    }

    $refunded_date = get_pmpro_membership_order_meta( $orderId, 'refunded_date', true );

    try {
        $refundDateObj      = new \DateTime( $refunded_date ?: current_time( 'mysql' ) );
        $refund_date_value  = $refundDateObj->format( 'Y-m-d' );
        $refund_hours      = $refundDateObj->format( 'H' );
        $refund_minutes    = $refundDateObj->format( 'i' );
    } catch ( \Exception $e ) {
        $refund_date_value = '';
        $refund_hours     = '';
        $refund_minutes   = '';
    }
    ?>
    <!-- Credit Note Data (edit) -->
    <div class="pmpro_section" data-visibility="shown" data-activated="true">
        <div class="pmpro_section_toggle">
            <button class="pmpro_section-toggle-button" type="button" aria-expanded="true">
                <span class="dashicons dashicons-arrow-up-alt2"></span>
                <span class="pmpro_section-header">
                    <span class="pmpro_section-title"><?php esc_html_e( 'Credit Note Data', WC_EL_INV_TEXTDOMAIN ); ?></span>
                </span>
            </button>
        </div>
        <div class="pmpro_section_inside">
            <table class="form-table">
                <tbody>
                <tr>
                    <th scope="row">
                        <label for="refund_number_invoice"><?php esc_html_e( 'Credit Note Number', WC_EL_INV_TEXTDOMAIN ); ?></label>
                    </th>
                    <td>
                        <input type="text"
                               name="refund_number_invoice"
                               id="refund_number_invoice"
                               value="<?php echo esc_attr( $refund_number ); ?>"
                               class="regular-text"/>
                        <p class="description"><?php esc_html_e( 'Progressive number of the credit note associated with this order.', WC_EL_INV_TEXTDOMAIN ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="refunded_date"><?php esc_html_e( 'Credit Note Date', WC_EL_INV_TEXTDOMAIN ); ?></label>
                    </th>
                    <td>
                        <input type="date"
                               name="refunded_date"
                               id="refunded_date"
                               value="<?php echo esc_attr( $refund_date_value ); ?>"/>
                        <input type="number"
                               min="0"
                               max="23"
                               name="refund_hours"
                               id="refund_hours"
                               value="<?php echo esc_attr( $refund_hours ); ?>"
                               class="small-text"/>
                        <span class="minutes">:</span>
                        <input type="number"
                               min="0"
                               max="59"
                               name="refund_minutes"
                               id="refund_minutes"
                               value="<?php echo esc_attr( $refund_minutes ); ?>"
                               class="small-text"/>
                        <p class="description"><?php esc_html_e( 'Timestamp used as credit note date.', WC_EL_INV_TEXTDOMAIN ); ?></p>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
    <?php
} );

add_action( 'pmpro_after_order_settings_table', function ( $order ) {
    pop_pmpro_render_cached_document_section( $order );
}, 20 );
