<?php
/**
 * Automation Tab
 *
 * @var array $settings
 * @var array|null $tenant_defaults
 */

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

$tenantGracePeriod = $tenant_defaults['grace_period'] ?? 'N/A';
?>

<h3><?php esc_html_e('Automation Rules', 'woocommerce-cloudxm-nfe'); ?></h3>
<p class="description"><?php esc_html_e('Configure when NFe invoices are automatically issued or cancelled.', 'woocommerce-cloudxm-nfe'); ?></p>
<table class="form-table">
    <tr>
        <th scope="row"><label for="cloudxm_nfe_auto_issue_status"><?php esc_html_e('Auto Issue NFe', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <select id="cloudxm_nfe_auto_issue_status" name="cloudxm_nfe_auto_issue_status">
                <option value="manual" <?php selected($settings['auto_issue_status'] ?? 'manual', 'manual'); ?>><?php esc_html_e('Manual (do not auto-issue)', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="wc-processing" <?php selected($settings['auto_issue_status'] ?? 'manual', 'wc-processing'); ?>><?php esc_html_e('Processing', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="wc-completed" <?php selected($settings['auto_issue_status'] ?? 'manual', 'wc-completed'); ?>><?php esc_html_e('Completed', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="wc-on-hold" <?php selected($settings['auto_issue_status'] ?? 'manual', 'wc-on-hold'); ?>><?php esc_html_e('On Hold', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="any-paid" <?php selected($settings['auto_issue_status'] ?? 'manual', 'any-paid'); ?>><?php esc_html_e('Any Paid Status', 'woocommerce-cloudxm-nfe'); ?></option>
            </select>
            <p class="description">
                <?php
                printf(
                    esc_html__('Selecione o status do pedido que aciona a emissão automática de NFe. "Manual" desabilita a emissão automática. Quando acionado, o comportamento depende do campo de meta do pedido %s:', 'woocommerce-cloudxm-nfe'),
                    '<code>_nfe_cloudxm_scheduled_at</code>'
                );
                ?>
            </p>
            <ul style="list-style: disc; margin-left: 20px; margin-top: 4px;">
                <li><?php echo wp_kses_post(sprintf(__('Se %s estiver preenchido com uma data futura → a NFe é <strong>agendada</strong> para essa data (não emitida imediatamente).', 'woocommerce-cloudxm-nfe'), '<code>_nfe_cloudxm_scheduled_at</code>')); ?></li>
                <li><?php echo wp_kses_post(sprintf(__('Se %s estiver vazio ou não definido → a NFe é <strong>emitida imediatamente</strong>.', 'woocommerce-cloudxm-nfe'), '<code>_nfe_cloudxm_scheduled_at</code>')); ?></li>
            </ul>
            <p class="description" style="margin-top: 8px;">
                <?php esc_html_e('Cada pedido também possui um campo de auto-status por pedido que pode substituir o fluxo global:', 'woocommerce-cloudxm-nfe'); ?>
            </p>
            <ul style="list-style: disc; margin-left: 20px; margin-top: 4px;">
                <li><?php echo wp_kses_post(__('<code>pending</code> — Padrão. O pedido segue a regra global de emissão automática acima.', 'woocommerce-cloudxm-nfe')); ?></li>
                <li><?php echo wp_kses_post(__('<code>ready_now</code> — O pedido é marcado para processamento imediato, ignorando o gatilho baseado em status.', 'woocommerce-cloudxm-nfe')); ?></li>
                <li><?php echo wp_kses_post(__('<code>schedule</code> — O pedido possui uma emissão agendada no servidor, aguardando para ser emitido.', 'woocommerce-cloudxm-nfe')); ?></li>
                <li><?php echo wp_kses_post(__('<code>issued</code> — NFe foi emitida com sucesso para este pedido.', 'woocommerce-cloudxm-nfe')); ?></li>
                <li><?php echo wp_kses_post(__('<code>error</code> — O processamento automático falhou para este pedido.', 'woocommerce-cloudxm-nfe')); ?></li>
            </ul>
            <p class="description" style="margin-top: 4px;">
                <?php printf(
                    esc_html__('O campo %s é definido através do botão "Marcar Pronto para Emitir" no meta box administrativo de cada pedido. Um selo colorido no meta box mostra o status atual.', 'woocommerce-cloudxm-nfe'),
                    '<code>_cloudxm_nfe_auto_status</code>'
                ); ?>
            </p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_auto_cancel_status"><?php esc_html_e('Auto Cancel NFe', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <select id="cloudxm_nfe_auto_cancel_status" name="cloudxm_nfe_auto_cancel_status">
                <option value="disabled" <?php selected($settings['auto_cancel_status'] ?? 'disabled', 'disabled'); ?>><?php esc_html_e('Disabled', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="wc-cancelled" <?php selected($settings['auto_cancel_status'] ?? 'disabled', 'wc-cancelled'); ?>><?php esc_html_e('Cancelled', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="wc-refunded" <?php selected($settings['auto_cancel_status'] ?? 'disabled', 'wc-refunded'); ?>><?php esc_html_e('Refunded', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="wc-failed" <?php selected($settings['auto_cancel_status'] ?? 'disabled', 'wc-failed'); ?>><?php esc_html_e('Failed', 'woocommerce-cloudxm-nfe'); ?></option>
            </select>
            <p class="description"><?php esc_html_e('Select the order status that triggers automatic NFe cancellation. Subject to the cancellation days limit.', 'woocommerce-cloudxm-nfe'); ?></p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_enable_custom_description"><?php esc_html_e('Custom Invoice Description', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <label>
                <input type="checkbox" id="cloudxm_nfe_enable_custom_description" name="cloudxm_nfe_enable_custom_description" value="1" <?php checked($settings['enable_custom_description'] ?? '0', '1'); ?>>
                <?php esc_html_e('Enable custom description per order', 'woocommerce-cloudxm-nfe'); ?>
            </label>
            <p class="description">
                <?php esc_html_e('When enabled, a text field appears in each order\'s meta box showing the auto-generated description (e.g. "Product A x2, Product B x1") as a preview. Nothing is saved until you explicitly click Save — only then is that text stored and used on the invoice. If you clear and save, the auto-generated description is used again. When disabled, the auto-generated description is always used and no field is shown.', 'woocommerce-cloudxm-nfe'); ?>
            </p>
        </td>
    </tr>
</table>

<h3><?php esc_html_e('Scheduling', 'woocommerce-cloudxm-nfe'); ?></h3>
<p class="description"><?php esc_html_e('Configure invoice scheduling settings. When a scheduled_at date is set on an order, auto-issue will schedule the invoice for that date; otherwise it will issue immediately.', 'woocommerce-cloudxm-nfe'); ?></p>
<table class="form-table">
    
    <tr>
        <th scope="row"><label for="cloudxm_nfe_schedule_timezone"><?php esc_html_e('Schedule Timezone', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <?php
            $currentTz = $settings['schedule_timezone'] ?? 'America/Sao_Paulo';
            $brazilTimezones = [
                'America/Sao_Paulo'      => 'São Paulo (SP, RJ, MG, PR, SC, RS, GO, DF, MS, MT, TO, BA, ES, etc.)',
                'America/Manaus'         => 'Manaus (AM)',
                'America/Belem'          => 'Belém (PA, AP, MA, PI)',
                'America/Fortaleza'      => 'Fortaleza (CE)',
                'America/Recife'         => 'Recife (PE, PB, RN, AL)',
                'America/Cuiaba'         => 'Cuiabá (MT)',
                'America/Porto_Velho'    => 'Porto Velho (RO)',
                'America/Rio_Branco'     => 'Rio Branco (AC)',
                'America/Araguaina'      => 'Araguaína (TO)',
                'America/Maceio'         => 'Maceió (AL)',
                'America/Noronha'        => 'Fernando de Noronha',
            ];
            ?>
            <select id="cloudxm_nfe_schedule_timezone" name="cloudxm_nfe_schedule_timezone" class="regular-text">
                <?php foreach ($brazilTimezones as $tzId => $tzLabel): ?>
                    <option value="<?php echo esc_attr($tzId); ?>" <?php selected($currentTz, $tzId); ?>>
                        <?php echo esc_html($tzId); ?> — <?php echo esc_html($tzLabel); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <p class="description"><?php esc_html_e('Timezone used for scheduled dates. Affects date display and server communication.', 'woocommerce-cloudxm-nfe'); ?></p>
        </td>
    </tr>
    
    <tr>
        <th scope="row"><label for="cloudxm_nfe_webhook_secret"><?php esc_html_e('Webhook Secret', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="text" id="cloudxm_nfe_webhook_secret" name="cloudxm_nfe_webhook_secret" value="<?php echo esc_attr($settings['webhook_secret'] ?? ''); ?>" class="regular-text" autocomplete="off">
            <button type="button" id="cloudxm-nfe-generate-secret" class="button button-secondary" style="margin-left:6px;">
                <?php esc_html_e('Generate', 'woocommerce-cloudxm-nfe'); ?>
            </button>
            <p class="description"><?php esc_html_e('HMAC-SHA256 secret used to sign webhook payloads. Minimum 32 characters.', 'woocommerce-cloudxm-nfe'); ?></p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_schedule_retry_on_failure"><?php esc_html_e('Retry on Failure', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <label>
                <input type="checkbox" id="cloudxm_nfe_schedule_retry_on_failure" name="cloudxm_nfe_schedule_retry_on_failure" value="1" <?php checked($settings['schedule_retry_on_failure'] ?? '0', '1'); ?>>
                <?php esc_html_e('Automatically retry scheduled invoice emission on failure.', 'woocommerce-cloudxm-nfe'); ?>
            </label>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_schedule_max_retries"><?php esc_html_e('Max Retries', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="number" id="cloudxm_nfe_schedule_max_retries" name="cloudxm_nfe_schedule_max_retries" value="<?php echo esc_attr($settings['schedule_max_retries'] ?? '3'); ?>" class="small-text" min="1" max="10">
            <p class="description"><?php esc_html_e('Number of retry attempts (1-10).', 'woocommerce-cloudxm-nfe'); ?></p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_schedule_retry_interval_minutes"><?php esc_html_e('Retry Interval (minutes)', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="number" id="cloudxm_nfe_schedule_retry_interval_minutes" name="cloudxm_nfe_schedule_retry_interval_minutes" value="<?php echo esc_attr($settings['schedule_retry_interval_minutes'] ?? '10'); ?>" class="small-text" min="1" max="1440">
            <p class="description"><?php esc_html_e('Minutes between retry attempts (1-1440).', 'woocommerce-cloudxm-nfe'); ?></p>
        </td>
    </tr>
</table>
