<?php
/**
 * NFe Order Meta Box Template
 *
 * @var array $meta
 * @var bool $enable_custom_description
 * @var string $custom_description
 * @var string $auto_description
 */

if (!defined('ABSPATH')) {
    exit;
}

$environment = $meta['environment'] ?? 'sandbox';
$envLabel = \CloudXM\NFe\Config\Configuration::getEnvironmentLabel($environment);
$isNotProduction = $environment !== 'production';
$scheduleFieldConfigured = $meta['schedule_field_configured'] ?? false;
$displayState = $meta['display_state'] ?? 'no_invoice';
$isScheduled = $displayState === 'scheduled'; // For backward compatibility
$emissionStatus = $meta['emission_status'] ?? ''; // For backward compatibility

// Extract scheduled date info for easier access
$scheduledAtFormatted = $meta['scheduled_at_formatted'] ?? '';
$scheduledTimezone = $meta['scheduled_timezone'] ?? '';
$timeUntilSchedule = $meta['time_until_schedule'] ?? '';
?>
<div class="cloudxm-nfe-meta-box">
    <div id="cloudxm-nfe-error-display" class="notice notice-error" style="display:none; padding: 8px 12px; margin: 0 0 12px 0;"></div>
    <?php if ($isNotProduction): ?>
    <div class="notice notice-warning cloudxm-nfe-env-notice" style="padding: 8px 12px; margin: 0 0 12px 0;">
        <p style="margin: 0;">
            <strong><?php echo esc_html(sprintf(__('NFe Environment: %s', 'woocommerce-cloudxm-nfe'), $envLabel)); ?></strong>
            <?php esc_html_e('— Invoices will be issued to the', 'woocommerce-cloudxm-nfe'); ?>
            <strong><?php echo esc_html($envLabel); ?></strong>
            <?php esc_html_e('environment.', 'woocommerce-cloudxm-nfe'); ?>
        </p>
    </div>
    <?php endif; ?>

    <?php /* ========================================
         DISPLAY STATE SWITCH - Single source of truth for UI
         ======================================== */ ?>
    <?php if ($meta['schedule_field_changed'] && $displayState === 'scheduled'): ?>
    <div class="notice notice-warning inline" style="margin: 0 0 12px 0;">
        <p>
            <strong><?php esc_html_e('Scheduled date has changed:', 'woocommerce-cloudxm-nfe'); ?></strong>
        </p>
        <p style="margin: 4px 0;">
            <?php esc_html_e('Previously:', 'woocommerce-cloudxm-nfe'); ?> <?php echo esc_html($meta['scheduled_at_formatted']); ?><?php if (!empty($scheduledTimezone)): ?> (<?php echo esc_html($scheduledTimezone); ?>)<?php endif; ?>
            <br>
            <?php esc_html_e('New value:', 'woocommerce-cloudxm-nfe'); ?> <strong><?php echo esc_html($meta['new_scheduled_at']); ?></strong>
        </p>
        <p>
            <button type="button" class="button button-small cloudxm-nfe-reschedule" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                <?php esc_html_e('Reschedule to New Date', 'woocommerce-cloudxm-nfe'); ?>
            </button>
        </p>
    </div>
    <?php endif; ?>

    <?php /* ========================================
         DISPLAY STATE SWITCH - Single source of truth for UI
         ======================================== */ ?>

    <?php if ($displayState === 'cancelled'): ?>
        <?php /* ========== CANCELLED STATE ==========
             Two sub-cases:
             A) Current emission was issued then cancelled → access_key is set on $meta.
                Show details and downloads from the current emission.
             B) Current emission was a cancelled schedule (no access_key), but a previous
                invoice was issued then cancelled → data lives in cancelled_invoice_history.
                Fall back to that history for details and downloads.
        */ ?>
        <?php
        $hist = $meta['cancelled_invoice_history'] ?? [];
        $histHasDoc = !empty($hist['access_key']);
        $useHistory = empty($meta['access_key']) && $histHasDoc;
        // Resolve display values: prefer current emission, fall back to history
        $displayInvoiceId      = !empty($meta['invoice_id'])          ? $meta['invoice_id']          : ($hist['invoice_id'] ?? '');
        $displayAccessKey      = !empty($meta['access_key'])           ? $meta['access_key']           : ($hist['access_key'] ?? '');
        $displayNfeNumber      = !empty($meta['nfe_number'])           ? $meta['nfe_number']           : ($hist['nfe_number'] ?? '');
        $displayNfseSeries     = $meta['nfse_series'] ?? '';
        $displayProtocol       = $meta['protocol_number'] ?? '';
        $displayIssuanceDate   = !empty($meta['issuance_date_formatted']) ? $meta['issuance_date_formatted'] : ($hist['issuance_date_formatted'] ?? '');
        $displayCancelDate     = !empty($meta['access_key'])
                                    ? ($meta['cancellation_date_formatted'] ?? '')
                                    : ($hist['cancellation_date_formatted'] ?? '');
        $displayCancelReason   = !empty($meta['access_key'])
                                    ? ($meta['cancellation_reason'] ?? '')
                                    : ($hist['cancellation_reason'] ?? '');
        ?>
        <div class="cloudxm-nfe-info">
            <p style="margin: 0 0 8px 0;">
                <strong><?php esc_html_e('Status:', 'woocommerce-cloudxm-nfe'); ?></strong>
                <span class="status-<?php echo esc_attr((string) ($meta['status'] ?? '')); ?>" style="margin-left: 8px;">
                    <?php echo esc_html((string) ($meta['status_label'] ?? '')); ?>
                </span>
            </p>

            <?php if (!empty($displayIssuanceDate) && (!empty($displayNfeNumber) || !empty($displayAccessKey))): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('Data de Emissão:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <?php echo esc_html($displayIssuanceDate); ?>
                </p>
            <?php endif; ?>

            <?php if (!empty($displayCancelDate)): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('Data de Cancelamento:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <?php echo esc_html($displayCancelDate); ?>
                </p>
            <?php endif; ?>

            <?php if (!empty($displayCancelReason)): ?>
                <p style="margin: 0 0 12px 0;">
                    <strong><?php esc_html_e('Motivo do Cancelamento:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <?php echo esc_html($displayCancelReason); ?>
                </p>
            <?php endif; ?>

            <?php if (!empty($displayNfseSeries)): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('NFSe:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <code><?php echo esc_html($displayNfseSeries . '-' . (!empty($meta['dps_number']) ? $meta['dps_number'] : $displayNfeNumber)); ?></code>
                </p>
            <?php elseif (!empty($displayNfeNumber)): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('NFSe:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <code><?php echo esc_html($displayNfeNumber); ?></code>
                </p>
            <?php endif; ?>

            <?php if (!empty($displayProtocol)): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('Protocolo:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <code><?php echo esc_html($displayProtocol); ?></code>
                </p>
            <?php endif; ?>

            <?php if (!empty($displayAccessKey)): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('Chave de Acesso:', 'woocommerce-cloudxm-nfe'); ?></strong><br>
                    <code class="cloudxm-nfe-code-break" style="font-size: 11px; color: #666;"><?php echo esc_html($displayAccessKey); ?></code>
                </p>
            <?php endif; ?>

            <div class="cloudxm-nfe-actions">
                <?php if (!empty($displayInvoiceId) && !empty($displayAccessKey)): ?>
                <?php
                $pdfUrl = rest_url('cloudxm/v1/invoice/' . $displayInvoiceId . '/pdf');
                $xmlUrl = rest_url('cloudxm/v1/invoice/' . $displayInvoiceId . '/xml');
                ?>
                <a href="<?php echo esc_url($pdfUrl); ?>" class="button button-small cloudxm-nfe-download-pdf" target="_blank">
                    <?php esc_html_e('Baixar PDF', 'woocommerce-cloudxm-nfe'); ?>
                </a>
                <a href="<?php echo esc_url($xmlUrl); ?>" class="button button-small cloudxm-nfe-download-xml" target="_blank">
                    <?php esc_html_e('Baixar XML', 'woocommerce-cloudxm-nfe'); ?>
                </a>
                <?php endif; ?>
                <?php if (!empty($meta['can_reissue'])): ?>
                    <?php if ($scheduleFieldConfigured): ?>
                        <button type="button" class="button button-small cloudxm-nfe-schedule" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>" data-has-cancelled-history="1">
                            <?php esc_html_e('Agendar Nova NFe', 'woocommerce-cloudxm-nfe'); ?>
                        </button>
                    <?php endif; ?>
                    <button type="button" class="button button-small cloudxm-nfe-issue" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                        <?php esc_html_e('Re-emitir NFe', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                <?php endif; ?>
                <?php if (!empty($meta['can_force_unlock'])): ?>
                    <button type="button" class="button button-small button-small-danger cloudxm-nfe-force-unlock" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>" title="<?php esc_attr_e('Clear NFe data without cancelling on server (use only if server lost the record)', 'woocommerce-cloudxm-nfe'); ?>">
                        <?php esc_html_e('Forçar Desbloqueio', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                <?php endif; ?>
                <button type="button" class="button button-small cloudxm-nfe-recover-dps" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                    <?php esc_html_e('Recuperar NFSe por DPS', 'woocommerce-cloudxm-nfe'); ?>
                </button>
            </div>
        </div>

    <?php elseif ($displayState === 'scheduled'): ?>
        <?php /* ========== SCHEDULED STATE (scheduled or async_pending) ========== */ ?>
        <div class="cloudxm-nfe-scheduled-info" style="background: #fff3cd; padding: 12px; margin: 8px 0; border-left: 4px solid #ffc107;">
            <?php if (!empty($meta['emission_id'])): ?>
                <p style="margin: 0 0 4px 0;">
                    <strong><?php esc_html_e('Emission ID:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <code><?php echo esc_html((string) $meta['emission_id']); ?></code>
                </p>
            <?php endif; ?>
            <p style="margin: 0 0 4px 0;">
                <strong>⏰ <?php esc_html_e('Agendado para:', 'woocommerce-cloudxm-nfe'); ?></strong>
                <?php echo esc_html($scheduledAtFormatted); ?><?php if (!empty($scheduledTimezone)): ?><span style="color:#666;"> (<?php echo esc_html($scheduledTimezone); ?>)</span><?php endif; ?>
            </p>
            <?php if (!empty($timeUntilSchedule)): ?>
                <p style="margin: 0; font-size: 13px;">
                    <?php echo esc_html($timeUntilSchedule); ?>
                </p>
            <?php endif; ?>
            <?php if (!empty($meta['can_reschedule'])): ?>
                <p style="margin: 8px 0 0 0;">
                    <button type="button" class="button button-small cloudxm-nfe-reschedule" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                        <?php esc_html_e('Reagendar', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                    <button type="button" class="button button-small button-small-danger cloudxm-nfe-cancel-schedule" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                        <?php esc_html_e('Cancelar Agendamento', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                    <button type="button" class="button button-small button-primary cloudxm-nfe-issue-now" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                        <?php esc_html_e('Emitir Agora', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                </p>
            <?php endif; ?>
        </div>

    <?php elseif ($displayState === 'issued'): ?>
        <?php /* ========== ISSUED STATE ========== */ ?>
        <div class="cloudxm-nfe-info">
            <p style="margin: 0 0 8px 0;">
                <strong><?php esc_html_e('Status:', 'woocommerce-cloudxm-nfe'); ?></strong>
                <span class="status-<?php echo esc_attr((string) ($meta['status'] ?? '')); ?>" style="margin-left: 8px;">
                    <?php echo esc_html((string) ($meta['status_label'] ?? '')); ?>
                </span>
            </p>

            <?php if (!empty($meta['issuance_date_formatted'])): ?>
                <p style="margin: 0 0 12px 0;">
                    <strong><?php esc_html_e('Data de Emissão:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <?php echo esc_html((string) $meta['issuance_date_formatted']); ?>
                </p>
            <?php endif; ?>

            <?php // NFe details ?>
            <?php if (!empty($meta['nfse_series'])): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('NFSe:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <code><?php echo esc_html((string) $meta['nfse_series'] . '-' . (!empty($meta['dps_number']) ? $meta['dps_number'] : $meta['nfe_number'])); ?></code>
                </p>
            <?php elseif (!empty($meta['nfe_number'])): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('NFSe:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <code><?php echo esc_html((string) $meta['nfe_number']); ?></code>
                </p>
            <?php endif; ?>

            <?php if (!empty($meta['protocol_number'])): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('Protocolo:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <code><?php echo esc_html((string) $meta['protocol_number']); ?></code>
                </p>
            <?php endif; ?>

            <?php if (!empty($meta['access_key'])): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('Chave de Acesso:', 'woocommerce-cloudxm-nfe'); ?></strong><br>
                    <code class="cloudxm-nfe-code-break" style="font-size: 11px; color: #666;"><?php echo esc_html((string) $meta['access_key']); ?></code>
                </p>
            <?php endif; ?>

            <?php if (!empty($meta['dps_number'])): ?>
                <p style="margin: 0 0 8px 0;">
                    <strong><?php esc_html_e('DPS:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <code><?php echo esc_html((string) $meta['dps_number']); ?></code>
                </p>
            <?php endif; ?>

            <?php // Actions for issued invoices ?>
            <div class="cloudxm-nfe-actions">
                <?php
                $pdfUrl = rest_url('cloudxm/v1/invoice/' . $meta['invoice_id'] . '/pdf');
                $xmlUrl = rest_url('cloudxm/v1/invoice/' . $meta['invoice_id'] . '/xml');
                ?>
                <a href="<?php echo esc_url($pdfUrl); ?>" class="button button-small cloudxm-nfe-download-pdf" target="_blank">
                    <?php esc_html_e('Baixar PDF', 'woocommerce-cloudxm-nfe'); ?>
                </a>
                <a href="<?php echo esc_url($xmlUrl); ?>" class="button button-small cloudxm-nfe-download-xml" target="_blank">
                    <?php esc_html_e('Baixar XML', 'woocommerce-cloudxm-nfe'); ?>
                </a>
                <button type="button" class="button button-small cloudxm-nfe-query-status" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                    <?php esc_html_e('Atualizar Status SEFIN', 'woocommerce-cloudxm-nfe'); ?>
                </button>
                <?php
                $allowedActions = isset($meta['allowed_actions']) ? (array) $meta['allowed_actions'] : [];
                $canCancel = !empty($meta['can_cancel']) && in_array('cancel', $allowedActions, true);
                $cancelTooltip = '';
                if (!$canCancel) {
                    if (in_array($meta['status'], ['cancelled', 'failed'], true)) {
                        $cancelTooltip = __('This NFe cannot be cancelled.', 'woocommerce-cloudxm-nfe');
                    } elseif ($meta['status'] === 'processing') {
                        $cancelTooltip = __('NFe is still being processed.', 'woocommerce-cloudxm-nfe');
                    } else {
                        $daysLimit = (int) get_option('cloudxm_nfe_cancel_days_limit', '5');
                        $cancelTooltip = sprintf(
                            __('Cannot cancel: More than %d days have passed since issuance.', 'woocommerce-cloudxm-nfe'),
                            $daysLimit
                        );
                    }
                }
                ?>
                <?php if ($canCancel): ?>
                <button type="button" class="button button-small button-small-danger cloudxm-nfe-cancel" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                    <?php esc_html_e('Cancelar NFe', 'woocommerce-cloudxm-nfe'); ?>
                </button>
                <?php else: ?>
                <span class="cloudxm-nfe-btn-tooltip" data-tooltip="<?php echo esc_attr($cancelTooltip); ?>">
                    <button type="button" class="button button-small button-small-danger cloudxm-nfe-cancel" disabled data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                        <?php esc_html_e('Cancelar NFe', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                </span>
                <?php endif; ?>
                <?php if (!empty($meta['can_force_unlock'])): ?>
                    <button type="button" class="button button-small button-small-danger cloudxm-nfe-force-unlock" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>" title="<?php esc_attr_e('Clear NFe data without cancelling on server (use only if server lost the record)', 'woocommerce-cloudxm-nfe'); ?>">
                        <?php esc_html_e('Forçar Desbloqueio', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                <?php endif; ?>
            </div>
        </div>

    <?php else: ?>
        <?php /* ========== NO INVOICE STATE ========== */ ?>
        <div class="cloudxm-nfe-no-invoice">
            <p data-testid="cloudxm-nfe-no-invoice"><?php esc_html_e('No NFe issued for this order yet.', 'woocommerce-cloudxm-nfe'); ?></p>
            <?php if (!empty($meta['can_issue'])): ?>
                <?php if ($scheduleFieldConfigured): ?>
                    <div class="cloudxm-nfe-issuance-options" style="display: flex; flex-wrap: wrap; gap: 8px; align-items: center;">
                        <button type="button" class="button button-primary cloudxm-nfe-schedule" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>" data-has-cancelled-history="<?php echo !empty($meta['cancelled_invoice_history']) ? '1' : '0'; ?>">
                            <?php esc_html_e('Agendar NFe', 'woocommerce-cloudxm-nfe'); ?>
                        </button>
                        <button type="button" class="button button-primary cloudxm-nfe-issue-now" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                            <?php esc_html_e('Emitir Agora', 'woocommerce-cloudxm-nfe'); ?>
                        </button>
                    </div>
                    <p class="description" style="margin-top: 8px;">
                        <?php esc_html_e('Use o campo "Data de Agendamento" abaixo para definir a data. Agendar emitirá a NFe automaticamente. Emitir Agora processará imediatamente.', 'woocommerce-cloudxm-nfe'); ?>
                    </p>
                <?php else: ?>
                    <button type="button" class="button button-primary cloudxm-nfe-issue" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                        <?php esc_html_e('Issue NFe', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                <?php endif; ?>
                <?php else: ?>
                    <p class="description"><?php esc_html_e('NFe cannot be issued for cancelled, refunded, or failed orders.', 'woocommerce-cloudxm-nfe'); ?></p>
                <?php endif; ?>
                <div style="margin-top: 10px;">
                    <button type="button" class="button button-small cloudxm-nfe-recover-dps" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                    <?php esc_html_e('Recuperar NFSe', 'woocommerce-cloudxm-nfe'); ?>
                </button>
                <p class="description" style="margin: 4px 0 0 0;">
                    <?php esc_html_e('Recupera uma NFSe já emitida na SEFIN usando o número DPS ou chave de acesso.', 'woocommerce-cloudxm-nfe'); ?>
                    </p>
                </div>

            <?php /* ----- Auto-issue state machine (CLO-11) ----- */ ?>
            <hr style="margin: 12px 0;">
            <p style="margin: 0 0 8px 0;">
                <strong><?php esc_html_e('Auto-Issue Status', 'woocommerce-cloudxm-nfe'); ?></strong>
            </p>
            <?php
            $autoStatus = $meta['auto_status'] ?? '';
            $statusLabels = [
                'pending' => __('Pending', 'woocommerce-cloudxm-nfe'),
                'ready_now' => __('Ready to Issue', 'woocommerce-cloudxm-nfe'),
                'schedule' => __('Scheduled', 'woocommerce-cloudxm-nfe'),
                'issued' => __('Issued', 'woocommerce-cloudxm-nfe'),
                'error' => __('Error', 'woocommerce-cloudxm-nfe'),
            ];
            $statusColors = [
                'pending' => '#888',
                'ready_now' => '#f0ad4e',
                'schedule' => '#5bc0de',
                'issued' => '#46b450',
                'error' => '#d9534f',
            ];
            $label = $statusLabels[$autoStatus] ?? ucfirst($autoStatus);
            $color = $statusColors[$autoStatus] ?? '#888';
            ?>
            <p style="margin: 0 0 8px 0;">
                <span data-testid="cloudxm-nfe-auto-status" data-status="<?php echo esc_attr($autoStatus); ?>" style="color: <?php echo esc_attr($color); ?>; font-weight: bold;">&#9679;</span>
                <?php echo esc_html($label); ?>
                <?php if ($autoStatus === 'schedule'): ?>
                    — <?php esc_html_e('Waiting for scheduled emission.', 'woocommerce-cloudxm-nfe'); ?>
                <?php elseif ($autoStatus === 'issued'): ?>
                    &#10003;
                <?php endif; ?>
            </p>
            <?php if ($autoStatus !== 'issued' && $autoStatus !== 'schedule'): ?>
            <button type="button" class="button button-small cloudxm-nfe-set-ready-now" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                <?php esc_html_e('Marcar Pronto para Emitir', 'woocommerce-cloudxm-nfe'); ?>
            </button>
            <p class="description" style="margin: 4px 0 0 0;">
                <?php esc_html_e('Define o status como ready_now no pedido. A emissão será processada automaticamente.', 'woocommerce-cloudxm-nfe'); ?>
            </p>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <?php
    // Determine if description should be read-only based on invoice status
    $emissionStatus = $meta['emission_status'] ?? '';
    $isDescriptionReadonly = in_array($emissionStatus, ['issued', 'processing', 'async_pending', 'scheduled'], true);
    $descriptionNotice = '';

    if ($isDescriptionReadonly) {
        if ($emissionStatus === 'issued') {
            $descriptionNotice = __('Description is locked because the NFe has already been issued.', 'woocommerce-cloudxm-nfe');
        } elseif ($emissionStatus === 'scheduled') {
            $descriptionNotice = __('Description is locked because the NFe is already scheduled. Cancel the schedule to edit.', 'woocommerce-cloudxm-nfe');
        } elseif ($emissionStatus === 'processing' || $emissionStatus === 'async_pending') {
            $descriptionNotice = __('Description is locked while the NFe is being processed.', 'woocommerce-cloudxm-nfe');
        }
    }
    ?>

    <?php
    // Show editable schedule date field if configured
    $scheduleFieldKey = $meta['schedule_field_key'] ?? '';
    $scheduleFieldValue = $meta['schedule_field_value'] ?? '';
    $scheduleFieldValueFormatted = $meta['schedule_field_value_formatted'] ?? '';
    $scheduledAtRaw = $meta['scheduled_at_raw'] ?? '';

    // Convert to datetime-local format (YYYY-MM-DDTHH:MM) for input
    $scheduleInputValue = '';
    // First try the external field value
    if (!empty($scheduleFieldValue)) {
        try {
            $date = new \DateTime($scheduleFieldValue, new \DateTimeZone($scheduledTimezone));
            $scheduleInputValue = wp_date('Y-m-d\TH:i', $date->getTimestamp());
        } catch (\Exception $e) {
            $scheduleInputValue = '';
        }
    }
    // If empty and invoice is scheduled, use the raw scheduled date
    if (empty($scheduleInputValue) && !empty($scheduledAtRaw)) {
        try {
            $date = new \DateTime($scheduledAtRaw, new \DateTimeZone($scheduledTimezone));
            $scheduleInputValue = wp_date('Y-m-d\TH:i', $date->getTimestamp());
        } catch (\Exception $e) {
            $scheduleInputValue = '';
        }
    }

    ?>
    <?php if (!empty($scheduleFieldKey)): ?>
    <div class="cloudxm-nfe-schedule-date-section">
        <p style="margin: 0 0 8px 0;">
            <strong><?php esc_html_e('Data de Agendamento', 'woocommerce-cloudxm-nfe'); ?></strong>
        </p>
        <input type="datetime-local"
               id="cloudxm_nfe_schedule_date"
               class="cloudxm-nfe-datetime-input regular-text"
               value="<?php echo esc_attr($scheduleInputValue); ?>"
               <?php if ($isDescriptionReadonly && $displayState !== 'scheduled'): ?> readonly<?php endif; ?>>
        <p class="description" style="margin: 4px 0 0 0; color: #646970;">
            <?php
            // Resolve display timezone label.
            // Priority: server timezone from emission record → WP timezone name → WP UTC offset.
            // wp_timezone()->getName() returns either an IANA name (e.g. "America/Sao_Paulo")
            // or a UTC offset string (e.g. "+00:00") depending on WP General Settings.
            if (!empty($scheduledTimezone)) {
                $scheduleTz = $scheduledTimezone;
            } else {
                $scheduleTz = wp_timezone_string(); // e.g. "America/Sao_Paulo" or "+00:00"
                if (empty($scheduleTz)) {
                    $scheduleTz = wp_timezone()->getName();
                }
            }
            // Format bare offset strings (e.g. +00:00, -03:00) as "UTC±H:MM"
            if (preg_match('/^([+-])(\d{2}):(\d{2})$/', $scheduleTz, $m)) {
                $hours = (int) $m[2];
                $mins  = $m[3];
                $scheduleTz = 'UTC' . $m[1] . $hours . ($mins !== '00' ? ':' . $mins : '');
            }
            if (!empty($scheduleFieldValueFormatted)) {
                printf(
                    /* translators: %1$s: formatted date, %2$s: timezone */
                    __('Valor atual: %1$s (%2$s). Clique em "Agendar NFe" para usar esta data.', 'woocommerce-cloudxm-nfe'),
                    '<strong>' . esc_html($scheduleFieldValueFormatted) . '</strong>',
                    esc_html($scheduleTz)
                );
            } else {
                printf(
                    /* translators: %s: timezone */
                    __('Defina a data e hora aqui (%s), depois clique em "Agendar NFe" acima. Deixe em branco para abrir o modal de agendamento.', 'woocommerce-cloudxm-nfe'),
                    esc_html($scheduleTz)
                );
            }
            ?>
        </p>
    </div>
    <?php endif; ?>

    <?php // Only show cancelled schedule notice if there's a cancelled history AND no active schedule AND not issued ?>
    <?php if ($meta['schedule_was_cancelled'] && !empty($meta['schedule_cancelled_date_formatted']) && $displayState !== 'scheduled' && $displayState !== 'issued'): ?>
    <div class="notice notice-info inline" style="margin: 12px 0 0 0;">
        <p>
            <strong><?php esc_html_e('Agendamento cancelado:', 'woocommerce-cloudxm-nfe'); ?></strong>
        </p>
        <p style="margin: 4px 0;">
            <?php esc_html_e('Este invoice foi agendado anteriormente para:', 'woocommerce-cloudxm-nfe'); ?> <?php echo esc_html($meta['schedule_cancelled_date_formatted']); ?>
        </p>
    </div>
    <?php endif; ?>

    <?php if ($enable_custom_description): ?>
    <div class="cloudxm-nfe-description-section">
        <p>
            <strong><?php esc_html_e('Descrição da Nota Fiscal', 'woocommerce-cloudxm-nfe'); ?></strong>
        </p>
        <textarea id="cloudxm_nfe_description" class="cloudxm-nfe-textarea" rows="9" maxlength="1000" data-max-columns="165" data-max-lines="9" placeholder="<?php esc_attr_e('Digite a descrição personalizada do serviço para a nota fiscal...', 'woocommerce-cloudxm-nfe'); ?>"<?php if ($isDescriptionReadonly): ?> readonly<?php endif; ?>><?php echo esc_textarea(!empty($custom_description) ? $custom_description : $auto_description); ?></textarea>
        <?php if ($descriptionNotice): ?>
        <p class="description" style="margin: 4px 0 8px 0; color: #646970;">
            <?php echo esc_html($descriptionNotice); ?>
        </p>
        <?php endif; ?>
        <p class="description" style="margin: 4px 0 8px 0; color: #646970;">
            <?php esc_html_e('Máximo: 165 caracteres por linha, 9 linhas.', 'woocommerce-cloudxm-nfe'); ?>
        </p>
        <div class="cloudxm-nfe-description-footer">
            <span class="cloudxm-nfe-line-column-count">
                <span id="cloudxm-nfe-desc-line-count">1</span> / 9 <?php esc_html_e('linhas', 'woocommerce-cloudxm-nfe'); ?> |
                <span id="cloudxm-nfe-desc-col-count">0</span> / 165 <?php esc_html_e('colunas', 'woocommerce-cloudxm-nfe'); ?>
            </span>
            <span class="cloudxm-nfe-character-count" style="margin-left: 10px;">
                <span id="cloudxm-nfe-desc-char-count"><?php echo esc_html((string) strlen(!empty($custom_description) ? $custom_description : $auto_description)); ?></span> / 1000 <?php esc_html_e('caracteres', 'woocommerce-cloudxm-nfe'); ?>
            </span>
            <?php if (!$isDescriptionReadonly): ?>
            <button type="button" class="button button-small cloudxm-nfe-save-description" data-order-id="<?php echo esc_attr((string) $meta['order_id']); ?>">
                <?php esc_html_e('Salvar', 'woocommerce-cloudxm-nfe'); ?>
            </button>
            <?php endif; ?>
        </div>
        <div id="cloudxm-nfe-desc-validation-error" class="notice notice-error inline" style="display:none; margin-top:8px;">
            <p></p>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($meta['error_message'])): ?>
        <div class="notice notice-error inline" style="word-wrap:break-word;overflow-wrap:break-word;">
            <p><strong><?php esc_html_e('Last Error:', 'woocommerce-cloudxm-nfe'); ?></strong></p>
            <p style="font-size:13px;"><?php echo esc_html((string) $meta['error_message']); ?></p>
        </div>
    <?php endif; ?>

    <?php if (!empty($meta['fallback_notice'])): ?>
        <div class="notice notice-success inline">
            <p><?php echo esc_html((string) $meta['fallback_notice']); ?></p>
        </div>
    <?php endif; ?>
    </div>
