<?php
/**
 * MyParcel Actions Meta Box
 * Shows export buttons and track & trace info in the order sidebar
 */

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

$listingActions = WCMYPA_Admin::getListingActions($order);
$pluginUrl = WCMYPA()->plugin_url();
$addShipments = WCMP_Export::EXPORT_ORDER;
$getLabels = WCMP_Export::GET_LABELS;
$addReturn = WCMP_Export::EXPORT_RETURN;
?>

<style>
.wcmp-actions-box {
    padding: 12px;
}

.wcmp-actions-box .wcmp-action-buttons {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 15px;
}

.wcmp-actions-box .wcmp-action-btn {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 14px;
    background: #f0f0f1;
    border: 1px solid #dcdcde;
    border-radius: 6px;
    text-decoration: none;
    color: #2c3338;
    font-weight: 500;
    transition: all 0.2s ease;
    cursor: pointer;
    position: relative;
}

.wcmp-actions-box .wcmp-action-btn:hover {
    background: #e5e5e5;
    border-color: #999;
    color: #000;
}

.wcmp-actions-box .wcmp-action-btn.primary {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    border-color: #3b82f6;
    color: #ffffff;
}

.wcmp-actions-box .wcmp-action-btn.primary:hover {
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    border-color: #2563eb;
    color: #ffffff;
    transform: translateY(-1px);
}

.wcmp-actions-box .wcmp-action-btn.success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    border-color: #10b981;
    color: #ffffff;
}

.wcmp-actions-box .wcmp-action-btn img {
    width: 18px;
    height: 18px;
    filter: brightness(0) saturate(100%);
}

.wcmp-actions-box .wcmp-action-btn.primary img,
.wcmp-actions-box .wcmp-action-btn.success img {
    filter: brightness(0) invert(1);
}

.wcmp-actions-box .wcmp-success-check {
    position: absolute;
    right: 10px;
    width: 20px;
    height: 20px;
    background: #10b981;
    border-radius: 50%;
    display: none;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 12px;
}

.wcmp-actions-box .wcmp-action-btn.success .wcmp-success-check {
    display: flex;
    animation: checkmark 0.3s ease;
}

@keyframes checkmark {
    0% { transform: scale(0); }
    50% { transform: scale(1.2); }
    100% { transform: scale(1); }
}

.wcmp-actions-box .wcmp-spinner {
    position: absolute;
    right: 10px;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255,255,255,0.3);
    border-top-color: #fff;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
    display: none;
}

.wcmp-actions-box .wcmp-action-btn.loading .wcmp-spinner {
    display: block;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.wcmp-actions-box .wcmp-tracktrace-section {
    border-top: 1px solid #dcdcde;
    padding-top: 12px;
}

.wcmp-actions-box .wcmp-tracktrace-section h4 {
    margin: 0 0 10px 0;
    font-size: 13px;
    font-weight: 600;
    color: #2c3338;
    display: flex;
    align-items: center;
    gap: 6px;
}

.wcmp-actions-box .wcmp-tracktrace-item {
    background: #f9f9f9;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    padding: 10px;
    margin-bottom: 8px;
}

.wcmp-actions-box .wcmp-tracktrace-item:last-child {
    margin-bottom: 0;
}

.wcmp-actions-box .wcmp-tracktrace-code {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
}

.wcmp-actions-box .wcmp-tracktrace-code a {
    color: #3b82f6;
    text-decoration: none;
    font-weight: 600;
    font-size: 13px;
}

.wcmp-actions-box .wcmp-tracktrace-code a:hover {
    text-decoration: underline;
}

.wcmp-actions-box .wcmp-tracktrace-code .dashicons {
    color: #3b82f6;
    font-size: 16px;
    width: 16px;
    height: 16px;
}

.wcmp-actions-box .wcmp-tracktrace-status {
    font-size: 12px;
    color: #666;
    padding-left: 24px;
}

.wcmp-actions-box .wcmp-no-shipment {
    color: #666;
    font-size: 13px;
    font-style: italic;
    padding: 8px 0;
}

.wcmp-actions-box .wcmp-info-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    background: #e7f3ff;
    color: #0066cc;
    padding: 6px 10px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    margin-top: 10px;
}

.wcmp-actions-box .wcmp-info-badge .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}
</style>

<script>
jQuery(document).ready(function($) {
    $('.wcmp-action-btn[data-ajax="true"]').on('click', function(e) {
        e.preventDefault();
        
        var $btn = $(this);
        var url = $btn.data('url');
        var action = $btn.data('action');
        
        // Don't allow clicking while loading
        if ($btn.hasClass('loading')) {
            return false;
        }
        
        // Add loading state
        $btn.addClass('loading');
        
        if (action === 'export' || action === 'return') {
            // AJAX request for export and return
            $.ajax({
                url: url,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    $btn.removeClass('loading').addClass('success');
                    
                    // Show success for 2 seconds
                    setTimeout(function() {
                        $btn.removeClass('success');
                        // Reload page to update track & trace
                        location.reload();
                    }, 1500);
                },
                error: function(xhr, status, error) {
                    $btn.removeClass('loading');
                    
                    // Try to parse response
                    try {
                        var response = JSON.parse(xhr.responseText);
                        if (response.success || response.success_ids) {
                            // Still successful even if error status
                            $btn.addClass('success');
                            setTimeout(function() {
                                $btn.removeClass('success');
                                location.reload();
                            }, 1500);
                            return;
                        }
                    } catch(e) {
                        // Check if response contains success message
                        if (xhr.responseText && xhr.responseText.indexOf('success') !== -1) {
                            $btn.addClass('success');
                            setTimeout(function() {
                                $btn.removeClass('success');
                                location.reload();
                            }, 1500);
                            return;
                        }
                    }
                    
                    alert('Actie mislukt: ' + error);
                }
            });
        } else if (action === 'print') {
            // Open in new tab for print
            window.open(url, '_blank');
            
            // Show success feedback
            setTimeout(function() {
                $btn.removeClass('loading').addClass('success');
                setTimeout(function() {
                    $btn.removeClass('success');
                }, 2000);
            }, 500);
        }
        
        return false;
    });
    
    // Delete timestamp handler
    $('.wcmp-delete-timestamp').on('click', function(e) {
        e.preventDefault();
        
        if (!confirm('Weet je zeker dat je de export timestamp wilt verwijderen?')) {
            return false;
        }
        
        var $btn = $(this);
        var url = $btn.data('url');
        
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Reload page to show updated info
                    location.reload();
                } else {
                    alert('Fout: ' + (response.data.message || 'Onbekende fout'));
                }
            },
            error: function(xhr, status, error) {
                alert('Fout bij verwijderen timestamp: ' + error);
            }
        });
        
        return false;
    });
});
</script>

<div class="wcmp-actions-box">
    <!-- Insurance Settings (for new exports) -->
    <?php if (empty($consignments)): 
        $insuranceType = $order->get_meta('_myparcel_insurance_type') ?: 'default';
        $insurancePercentage = $order->get_meta('_myparcel_insurance_percentage') ?: 100;
    ?>
    <div class="wcmp-insurance-settings" style="margin-bottom: 15px; padding: 12px; background: #f0f6ff; border: 1px solid #3b82f6; border-radius: 6px;">
        <h4 style="margin: 0 0 10px 0; font-size: 13px; color: #2563eb;">
            <span class="dashicons dashicons-shield" style="font-size: 16px; vertical-align: middle;"></span>
            Verzekering instellingen
        </h4>
        
        <div style="margin-bottom: 10px;">
            <label for="insurance_type_<?php echo esc_attr($order_id); ?>" style="display: block; margin-bottom: 4px; font-weight: 600; font-size: 12px;">
                Verzekering type:
            </label>
            <select id="insurance_type_<?php echo esc_attr($order_id); ?>" name="_myparcel_insurance_type" style="width: 100%;">
                <option value="default" <?php selected($insuranceType, 'default'); ?>>Standaard (gebruik carrier instelling)</option>
                <option value="fixed" <?php selected($insuranceType, 'fixed'); ?>>Vast bedrag</option>
                <option value="percentage" <?php selected($insuranceType, 'percentage'); ?>>Percentage van orderbedrag</option>
            </select>
        </div>
        
        <div id="insurance_fixed_field_<?php echo esc_attr($order_id); ?>" style="<?php echo ($insuranceType !== 'fixed') ? 'display:none;' : ''; ?>">
            <label for="insurance_fixed_amount_<?php echo esc_attr($order_id); ?>" style="display: block; margin-bottom: 4px; font-weight: 600; font-size: 12px;">
                Verzekerd bedrag:
            </label>
            <?php
            $shipping_country = $order->get_shipping_country();
            $insuranceAmounts = WCMP_Data::getInsuranceAmounts($shipping_country, 'postnl');
            $currentAmount = $order->get_meta('_myparcel_insurance_fixed_amount') ?: 100;
            ?>
            <select id="insurance_fixed_amount_<?php echo esc_attr($order_id); ?>" 
                    name="_myparcel_insurance_fixed_amount" 
                    style="width: 100%;">
                <?php foreach ($insuranceAmounts as $value => $label): ?>
                    <option value="<?php echo esc_attr($value); ?>" <?php selected($currentAmount, $value); ?>>
                        € <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <p style="margin: 4px 0 0 0; font-size: 11px; color: #666;">
                Kies een vast verzekerd bedrag voor deze order
            </p>
        </div>
        
        <div id="insurance_percentage_field_<?php echo esc_attr($order_id); ?>" style="<?php echo ($insuranceType !== 'percentage') ? 'display:none;' : ''; ?>">
            <label for="insurance_percentage_<?php echo esc_attr($order_id); ?>" style="display: block; margin-bottom: 4px; font-weight: 600; font-size: 12px;">
                Percentage:
            </label>
            <input type="number" 
                   id="insurance_percentage_<?php echo esc_attr($order_id); ?>" 
                   name="_myparcel_insurance_percentage" 
                   value="<?php echo esc_attr($insurancePercentage); ?>" 
                   min="1" 
                   max="100" 
                   style="width: 100%;">
            <p style="margin: 4px 0 0 0; font-size: 11px; color: #666;">
                Percentage van orderbedrag (excl. BTW). Bijv: 100 voor volledige waarde
            </p>
        </div>
        
        <button type="button" class="button button-small" onclick="saveInsuranceSettings<?php echo esc_attr($order_id); ?>()" style="margin-top: 8px;">
            Opslaan
        </button>
        <span id="insurance_save_status_<?php echo esc_attr($order_id); ?>" style="margin-left: 8px; font-size: 12px;"></span>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        // Show/hide fixed amount or percentage field based on type
        $('#insurance_type_<?php echo esc_js($order_id); ?>').on('change', function() {
            var type = $(this).val();
            if (type === 'percentage') {
                $('#insurance_fixed_field_<?php echo esc_js($order_id); ?>').slideUp();
                $('#insurance_percentage_field_<?php echo esc_js($order_id); ?>').slideDown();
            } else if (type === 'fixed') {
                $('#insurance_percentage_field_<?php echo esc_js($order_id); ?>').slideUp();
                $('#insurance_fixed_field_<?php echo esc_js($order_id); ?>').slideDown();
            } else {
                $('#insurance_fixed_field_<?php echo esc_js($order_id); ?>').slideUp();
                $('#insurance_percentage_field_<?php echo esc_js($order_id); ?>').slideUp();
            }
        });
    });
    
    function saveInsuranceSettings<?php echo esc_js($order_id); ?>() {
        var $ = jQuery;
        var $status = $('#insurance_save_status_<?php echo esc_js($order_id); ?>');
        var type = $('#insurance_type_<?php echo esc_js($order_id); ?>').val();
        var percentage = $('#insurance_percentage_<?php echo esc_js($order_id); ?>').val();
        var fixedAmount = $('#insurance_fixed_amount_<?php echo esc_js($order_id); ?>').val();
        
        $status.html('<span style="color: #666;">Opslaan...</span>');
        
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'wcmp_save_insurance_settings',
                order_id: <?php echo (int) $order_id; ?>,
                insurance_type: type,
                insurance_percentage: percentage,
                insurance_fixed_amount: fixedAmount,
                security: '<?php echo wp_create_nonce('wcmp_save_insurance'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    $status.html('<span style="color: #059669;">✓ Opgeslagen</span>');
                    setTimeout(function() {
                        $status.html('');
                    }, 2000);
                } else {
                    $status.html('<span style="color: #dc2626;">Fout</span>');
                }
            },
            error: function() {
                $status.html('<span style="color: #dc2626;">Fout</span>');
            }
        });
    }
    </script>
    <?php endif; ?>
    
    <!-- Export Actions -->
    <div class="wcmp-action-buttons">
        <?php if (isset($listingActions[$addShipments])): ?>
            <a href="<?php echo esc_url(wp_nonce_url($listingActions[$addShipments]['url'], WCMYPA::NONCE_ACTION)); ?>" 
               class="wcmp-action-btn primary"
               data-ajax="true"
               data-action="export"
               data-url="<?php echo esc_url(wp_nonce_url($listingActions[$addShipments]['url'], WCMYPA::NONCE_ACTION)); ?>"
               title="<?php echo esc_attr($listingActions[$addShipments]['alt']); ?>">
                <img src="<?php echo esc_url($listingActions[$addShipments]['img']); ?>" 
                     alt="<?php echo esc_attr($listingActions[$addShipments]['alt']); ?>">
                <span><?php esc_html_e('Exporteer naar MyParcel', 'woocommerce-myparcel'); ?></span>
                <span class="wcmp-spinner"></span>
                <span class="wcmp-success-check">✓</span>
            </a>
        <?php endif; ?>
        
        <?php if (isset($listingActions[$getLabels])): ?>
            <a href="<?php echo esc_url(wp_nonce_url($listingActions[$getLabels]['url'], WCMYPA::NONCE_ACTION)); ?>" 
               class="wcmp-action-btn"
               data-ajax="true"
               data-action="print"
               data-url="<?php echo esc_url(wp_nonce_url($listingActions[$getLabels]['url'], WCMYPA::NONCE_ACTION)); ?>"
               title="<?php echo esc_attr($listingActions[$getLabels]['alt']); ?>">
                <img src="<?php echo esc_url($listingActions[$getLabels]['img']); ?>" 
                     alt="<?php echo esc_attr($listingActions[$getLabels]['alt']); ?>">
                <span><?php esc_html_e('Print label', 'woocommerce-myparcel'); ?></span>
                <span class="wcmp-spinner"></span>
                <span class="wcmp-success-check">✓</span>
            </a>
        <?php endif; ?>
        
        <?php if (isset($listingActions[$addReturn])): ?>
            <a href="<?php echo esc_url(wp_nonce_url($listingActions[$addReturn]['url'], WCMYPA::NONCE_ACTION)); ?>" 
               class="wcmp-action-btn"
               data-ajax="true"
               data-action="return"
               data-url="<?php echo esc_url(wp_nonce_url($listingActions[$addReturn]['url'], WCMYPA::NONCE_ACTION)); ?>"
               title="<?php echo esc_attr($listingActions[$addReturn]['alt']); ?>">
                <img src="<?php echo esc_url($listingActions[$addReturn]['img']); ?>" 
                     alt="<?php echo esc_attr($listingActions[$addReturn]['alt']); ?>">
                <span><?php esc_html_e('Verstuur retourlabel', 'woocommerce-myparcel'); ?></span>
                <span class="wcmp-spinner"></span>
                <span class="wcmp-success-check">✓</span>
            </a>
        <?php endif; ?>
    </div>
    
    <!-- Track & Trace Section -->
    <?php if (!empty($trackTraceInfo)): ?>
        <div class="wcmp-tracktrace-section">
            <h4>
                <span class="dashicons dashicons-location-alt"></span>
                <?php esc_html_e('Track & Trace', 'woocommerce-myparcel'); ?>
            </h4>
    <?php elseif (!empty($hasShipmentIdsButNoBarcode)): ?>
        <div class="wcmp-tracktrace-section">
            <h4>
                <span class="dashicons dashicons-location-alt"></span>
                <?php esc_html_e('Track & Trace', 'woocommerce-myparcel'); ?>
            </h4>
            
            <!-- Missing barcode data notification -->
            <div style="background: #fff3cd; padding: 10px; border-radius: 4px; margin-bottom: 10px; border-left: 4px solid #ffc107;">
                <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
                    <span class="dashicons dashicons-info" style="color: #856404;"></span>
                    <span style="color: #856404; font-weight: 500;">Barcode data ontbreekt</span>
                </div>
                <p style="margin: 0 0 10px 0; color: #856404; font-size: 13px;">
                    Deze bestelling heeft MyParcel zendingen, maar de barcode data is nog niet opgehaald.
                </p>
                <a href="#" 
                   class="wcmp-refresh-barcode" 
                   data-url="<?php echo esc_url($refreshBarcodeUrl); ?>"
                   style="display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; background: #007cba; color: white; text-decoration: none; border-radius: 4px; font-size: 12px; border: none; cursor: pointer;"
                   title="<?php esc_attr_e('Haal barcode data op van MyParcel API', 'woocommerce-myparcel'); ?>">
                    <span class="dashicons dashicons-update" style="font-size: 16px; width: 16px; height: 16px;"></span>
                    Barcode ophalen
                    <span class="wcmp-spinner" style="display: none;"></span>
                </a>
            </div>
        </div>
    <?php endif; ?>
    
    <?php if (!empty($trackTraceInfo)): ?>
            
            <?php if (!empty($lastExportTime)): ?>
                <div style="background: #f0f6ff; padding: 8px 10px; border-radius: 4px; margin-bottom: 10px; font-size: 12px; color: #0066cc; display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <span class="dashicons dashicons-clock" style="font-size: 14px; margin-top: 1px;"></span>
                        <strong>Laatste export:</strong> <?php echo esc_html(date_i18n('d-m-Y H:i', strtotime($lastExportTime))); ?>
                    </div>
                    <div style="display: flex; gap: 8px; align-items: center;">
                        <a href="#" 
                           class="wcmp-refresh-barcode" 
                           data-url="<?php echo esc_url($refreshBarcodeUrl); ?>"
                           title="<?php esc_attr_e('Ververs barcode data', 'woocommerce-myparcel'); ?>"
                           style="color: #007cba; text-decoration: none; font-size: 16px; line-height: 1;">
                            <span class="dashicons dashicons-update"></span>
                        </a>
                        <a href="#" 
                           class="wcmp-delete-timestamp" 
                           data-url="<?php echo esc_url($deleteTimestampUrl); ?>"
                           title="<?php esc_attr_e('Verwijder export timestamp', 'woocommerce-myparcel'); ?>"
                           style="color: #dc3545; text-decoration: none; font-size: 16px; line-height: 1;">
                            <span class="dashicons dashicons-trash"></span>
                        </a>
                    </div>
                </div>
            <?php endif; ?>
            
            <?php foreach ($trackTraceInfo as $info): ?>
                <div class="wcmp-tracktrace-item">
                    <?php if (!empty($info['code'])): ?>
                        <div class="wcmp-tracktrace-code">
                            <span class="dashicons dashicons-admin-links"></span>
                            <a href="<?php echo esc_url($info['url']); ?>" 
                               target="_blank"
                               title="<?php esc_attr_e('Bekijk zending', 'woocommerce-myparcel'); ?>">
                                <?php echo esc_html($info['code']); ?>
                            </a>
                        </div>
                        <?php if (!empty($info['status'])): ?>
                            <div class="wcmp-tracktrace-status">
                                Status: <?php echo esc_html($info['status']); ?>
                            </div>
                        <?php endif; ?>
                        <?php if (!empty($info['exported_at'])): ?>
                            <div class="wcmp-tracktrace-status" style="color: #999;">
                                <span class="dashicons dashicons-calendar-alt" style="font-size: 14px; width: 14px; height: 14px;"></span>
                                Geëxporteerd: <?php echo esc_html(date_i18n('d-m-Y H:i', strtotime($info['exported_at']))); ?>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <!-- Shipment zonder track & trace code (concept/draft) -->
                        <div class="wcmp-tracktrace-code" style="color: #999;">
                            <span class="dashicons dashicons-info"></span>
                            <span style="font-style: italic;">Zending aangemaakt - Track & Trace wordt gegenereerd</span>
                        </div>
                        <?php if (!empty($info['status'])): ?>
                            <div class="wcmp-tracktrace-status">
                                Status: <?php echo esc_html($info['status']); ?>
                            </div>
                        <?php endif; ?>
                        <?php if (!empty($info['exported_at'])): ?>
                            <div class="wcmp-tracktrace-status" style="color: #999;">
                                <span class="dashicons dashicons-calendar-alt" style="font-size: 14px; width: 14px; height: 14px;"></span>
                                Aangemaakt: <?php echo esc_html(date_i18n('d-m-Y H:i', strtotime($info['exported_at']))); ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    <?php elseif ($hasShipments): ?>
        <div class="wcmp-tracktrace-section">
            <h4>
                <span class="dashicons dashicons-location-alt"></span>
                <?php esc_html_e('Track & Trace', 'woocommerce-myparcel'); ?>
            </h4>
            
            <?php if (!empty($lastExportTime)): ?>
                <div style="background: #f0f6ff; padding: 8px 10px; border-radius: 4px; margin-bottom: 10px; font-size: 12px; color: #0066cc; display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <span class="dashicons dashicons-clock" style="font-size: 14px; margin-top: 1px;"></span>
                        <strong>Laatste export:</strong> <?php echo esc_html(date_i18n('d-m-Y H:i', strtotime($lastExportTime))); ?>
                    </div>
                    <a href="#" 
                       class="wcmp-delete-timestamp" 
                       data-url="<?php echo esc_url($deleteTimestampUrl); ?>"
                       title="<?php esc_attr_e('Verwijder export timestamp', 'woocommerce-myparcel'); ?>"
                       style="color: #dc3545; text-decoration: none; font-size: 16px; line-height: 1;">
                        <span class="dashicons dashicons-trash"></span>
                    </a>
                </div>
            <?php endif; ?>
            
            <p class="wcmp-no-shipment">
                <?php esc_html_e('Zending aangemaakt, track & trace wordt binnenkort gegenereerd', 'woocommerce-myparcel'); ?>
            </p>
        </div>
    <?php else: ?>
        <div class="wcmp-info-badge">
            <span class="dashicons dashicons-info"></span>
            <span><?php esc_html_e('Nog geen zending aangemaakt', 'woocommerce-myparcel'); ?></span>
        </div>
    <?php endif; ?>
</div>

<script>
jQuery(document).ready(function($) {
    // Handle refresh barcode button click
    $('.wcmp-refresh-barcode').on('click', function(e) {
        e.preventDefault();
        
        var button = $(this);
        var url = button.data('url');
        var spinner = button.find('.wcmp-spinner');
        var orderId = url.match(/order_id=(\d+)/);
        var nonce = url.match(/_wpnonce=([a-zA-Z0-9]+)/);
        orderId = orderId ? orderId[1] : null;
        nonce = nonce ? nonce[1] : null;
        
        console.log('Refresh Barcode Debug:', {
            url: url,
            orderId: orderId,
            nonce: nonce,
            ajaxUrl: '<?php echo admin_url('admin-ajax.php'); ?>'
        });
        
        if (!orderId || !nonce) {
            console.error('Missing orderId or nonce:', {orderId: orderId, nonce: nonce});
            alert('Error: Order ID or security token not found');
            return;
        }
        
        // Show loading state
        button.prop('disabled', true);
        if (spinner.length > 0) {
            spinner.show();
        } else {
            button.append('<span class="wcmp-spinner" style="display: inline-block; margin-left: 5px;">⟳</span>');
        }
        
        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            method: 'POST',
            data: {
                action: 'wcmp_refresh_barcode',
                order_id: orderId,
                _wpnonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    // Show success message with shipment info
                    var successMessage = '<div class="notice notice-success is-dismissible" style="margin: 10px 0; padding: 10px;"><p>' + 
                        response.data.message + ' (' + response.data.count + ' shipment(s))';
                    
                    // Add barcode info if available
                    if (response.data.shipment_data && response.data.shipment_data.length > 0) {
                        successMessage += '<br><strong>Barcodes:</strong> ';
                        var barcodes = response.data.shipment_data.map(function(s) {
                            return s.track_trace;
                        }).join(', ');
                        successMessage += barcodes;
                    }
                    
                    successMessage += '</p></div>';
                    
                    button.closest('.wcmp-actions-box').prepend(successMessage);
                    
                    // Auto-dismiss the notice after 3 seconds
                    setTimeout(function() {
                        $('.notice-success').fadeOut();
                    }, 3000);
                    
                    // Reload the page after 1.5 seconds to show updated barcode data in list
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    alert('Error: ' + response.data);
                }
            },
            error: function(xhr, status, error) {
                console.log('AJAX Error Details:', {
                    status: status,
                    error: error,
                    responseText: xhr.responseText,
                    orderId: orderId,
                    nonce: nonce
                });
                alert('AJAX request failed. Check browser console for details. Status: ' + status + ', Error: ' + error);
            },
            complete: function() {
                // Hide loading state
                button.prop('disabled', false);
                button.find('.wcmp-spinner').hide();
            }
        });
    });
    
    // Handle delete timestamp button (existing functionality) 
    $('.wcmp-delete-timestamp').on('click', function(e) {
        e.preventDefault();
        
        var button = $(this);
        var url = button.data('url');
        var orderId = url.match(/order_id=(\d+)/);
        orderId = orderId ? orderId[1] : null;
        
        if (!orderId) {
            alert('Error: Order ID not found');
            return;
        }
        
        if (!confirm('Are you sure you want to delete the export timestamp?')) {
            return;
        }
        
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'wcmp_delete_export_timestamp',
                order_id: orderId
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Error: ' + response.data);
                }
            },
            error: function() {
                alert('AJAX request failed');
            }
        });
    });
});
</script>
