<?php

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

$upload    = wp_upload_dir();
$orders_dir = trailingslashit($upload['basedir']) . 'exports/';
$orders_url = trailingslashit($upload['baseurl']) . 'exports/';
?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Orders export', 'ai-eshop-optimizer'); ?></h2>

    <div class="aieo-dmm-card">
        <h3><?php esc_html_e('Where the file will be saved', 'ai-eshop-optimizer'); ?></h3>
        <p class="description" style="margin:0;">
            <?php esc_html_e('Stable canonical path under uploads/exports/. Downstream partners (ERPs, reconciliation scripts, etc.) get the same URL every run; the file is overwritten in place. Cache-busting on the LINK below uses ?v=<etag> so a refreshed link always serves fresh content even though the filename never changes.', 'ai-eshop-optimizer'); ?>
        </p>
        <p style="margin:6px 0 0;">
            <strong><?php esc_html_e('File path:', 'ai-eshop-optimizer'); ?></strong>
            <code id="aieo-dmm-orders-path-preview"><?php echo esc_html($orders_dir); ?>exported_orders.csv</code><br>
            <strong><?php esc_html_e('Public URL:', 'ai-eshop-optimizer'); ?></strong>
            <code id="aieo-dmm-orders-url-preview"><?php echo esc_html($orders_url); ?>exported_orders.csv</code>
        </p>
    </div>

    <?php if (!empty($last_result['public_url'])) : ?>
        <div class="aieo-dmm-card" style="background:#ecfdf5;border-left:3px solid #15803d;">
            <h3><?php esc_html_e('Last export', 'ai-eshop-optimizer'); ?></h3>
            <p style="margin:0 0 6px;font-size:13px;">
                <a id="aieo-dmm-orders-last-link"
                   href="<?php echo esc_url($last_result['public_url']); ?>"
                   target="_blank" rel="noopener">
                    <strong><?php echo esc_html(isset($last_result['filename']) ? $last_result['filename'] : 'exported_orders.csv'); ?></strong>
                    <span style="color:#6b7280;">— <?php esc_html_e('open file', 'ai-eshop-optimizer'); ?> ↗</span>
                </a>
            </p>
            <p style="margin:0;font-size:12px;color:#374151;">
                <?php
                $bits = array();
                if (!empty($last_result['rows_processed'])) {
                    $bits[] = sprintf(
                        
                        esc_html__('%d orders processed', 'ai-eshop-optimizer'),
                        (int) $last_result['rows_processed']
                    );
                }
                if (!empty($last_result['first_id'])) {
                    $bits[] = sprintf(
                        
                        esc_html__('range #%1$d → %2$s', 'ai-eshop-optimizer'),
                        (int) $last_result['first_id'],
                        !empty($last_result['last_id']) ? '#' . (int) $last_result['last_id'] : esc_html__('end', 'ai-eshop-optimizer')
                    );
                }
                if (!empty($last_result['completed_at'])) {
                    $bits[] = sprintf(
                        
                        esc_html__('completed %s ago', 'ai-eshop-optimizer'),
                        esc_html(human_time_diff(strtotime($last_result['completed_at'] . ' UTC')))
                    );
                }
                if (!empty($last_result['etag'])) {
                    $bits[] = 'etag <code>' . esc_html($last_result['etag']) . '</code>';
                }
                echo wp_kses_post(implode(' · ', $bits));
                ?>
            </p>
            <p style="margin:6px 0 0;font-size:11px;color:#9ca3af;">
                <?php esc_html_e('The file path is stable — only the link below carries a ?v=<etag> token so cached browsers and CDNs always fetch the latest content on refresh.', 'ai-eshop-optimizer'); ?>
            </p>
        </div>
    <?php endif; ?>

    <form id="aieo-dmm-orders-start-form" class="aieo-dmm-form">
        <div class="aieo-dmm-grid">
            <p>
                <label><?php esc_html_e('Starting order ID', 'ai-eshop-optimizer'); ?></label>
                <input type="number" min="1" name="first_order_id"
                       value="<?php echo esc_attr((int) (isset($last_first_id) ? $last_first_id : 1)); ?>" required>
                <?php if (!empty($last_first_id) && (int) $last_first_id > 1) : ?>
                    <span class="description" style="margin-left:8px;color:#6b7280;font-size:12px;">
                        <?php esc_html_e('Pre-filled from your last export.', 'ai-eshop-optimizer'); ?>
                    </span>
                <?php endif; ?>
            </p>
            <p>
                <label><?php esc_html_e('Ending order ID (optional)', 'ai-eshop-optimizer'); ?></label>
                <input type="number" min="0" name="last_order_id"
                       value="<?php echo esc_attr((int) (isset($last_last_id) ? $last_last_id : 0)); ?>">
            </p>
            <p>
                <label><?php esc_html_e('Format', 'ai-eshop-optimizer'); ?></label>
                <select name="format" id="aieo-dmm-orders-format">
                    <option value="csv">CSV</option>
                    <option value="xml">XML</option>
                </select>
            </p>
            <p>
                <label><?php esc_html_e('Cache-busting strategy', 'ai-eshop-optimizer'); ?></label>
                <select name="cache_mode" id="aieo-dmm-orders-cache-mode">
                    <option value="stable_url" selected><?php esc_html_e('Stable URL (recommended — matches meta-connector)', 'ai-eshop-optimizer'); ?></option>
                    <option value="version_query"><?php esc_html_e('Stable URL + ?v=<etag> for CDNs', 'ai-eshop-optimizer'); ?></option>
                    <option value="unique_filename"><?php esc_html_e('Unique filename per run', 'ai-eshop-optimizer'); ?></option>
                </select>
            </p>
        </div>

        <fieldset class="aieo-dmm-statuses" style="margin:6px 0 0;padding:10px 12px;border:1px solid #dcdcde;border-radius:4px;">
            <legend style="padding:0 4px;font-weight:600;"><?php esc_html_e('Order statuses to export', 'ai-eshop-optimizer'); ?></legend>
            <?php if (empty($selectable_statuses)) : ?>
                <p class="description" style="margin:0;"><?php esc_html_e('No order statuses available.', 'ai-eshop-optimizer'); ?></p>
            <?php else : ?>
                <?php foreach ($selectable_statuses as $slug => $label) : ?>
                    <label style="display:inline-block;margin:0 16px 6px 0;white-space:nowrap;">
                        <input type="checkbox" name="statuses[]" value="<?php echo esc_attr($slug); ?>"
                               <?php checked(in_array($slug, (array) $selected_statuses, true)); ?>>
                        <?php echo esc_html($label); ?>
                    </label>
                <?php endforeach; ?>
                <p class="description" style="margin:4px 0 0;">
                    <?php esc_html_e('Only orders with a ticked status are exported. Default is Completed only — so abandoned/draft carts (and other in-flight orders) are kept out of the ERP file. Tick more statuses if your ERP needs them.', 'ai-eshop-optimizer'); ?>
                </p>
            <?php endif; ?>
        </fieldset>

        <p class="description">
            <?php esc_html_e('“Stable URL” overwrites the same file on every run at exported_orders.csv / .xml so existing ERP consumers keep working. If your CDN caches aggressively, switch to “+ ?v=<etag>” which appends a content-hash token without changing the filename. “Unique filename” produces orders-export-<id>.csv each run — use only if downstream explicitly expects a fresh URL.', 'ai-eshop-optimizer'); ?>
        </p>
        <p class="submit">
            <button type="submit" class="button button-primary aieo-dmm-btn-fixed" data-action="aieo_dmm_orders_export_start">
                <?php esc_html_e('Start export', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </form>

    <div class="aieo-dmm-progress" id="aieo-dmm-orders-progress" style="display:none;">
        <div class="aieo-dmm-progress-bar"><span style="width:0%"></span></div>
        <p class="aieo-dmm-progress-text"></p>
    </div>

    <!-- Populated on completion by dmm.js via the aieo-dmm:export-complete event. -->
    <div class="aieo-dmm-card" id="aieo-dmm-orders-complete" style="display:none; background:#e9f7ef; border-color:#b3dfc3;">
        <h3 style="color:#0f5132;"><?php esc_html_e('Export complete', 'ai-eshop-optimizer'); ?></h3>
        <p style="margin:0;">
            <strong><?php esc_html_e('Public URL:', 'ai-eshop-optimizer'); ?></strong>
            <a href="#" id="aieo-dmm-orders-complete-url" target="_blank"></a>
            <button type="button" class="button button-small aieo-dmm-copy" id="aieo-dmm-orders-complete-copy-url" data-value="">
                <?php esc_html_e('Copy URL', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
        <p style="margin:6px 0 0;">
            <strong><?php esc_html_e('File path:', 'ai-eshop-optimizer'); ?></strong>
            <code id="aieo-dmm-orders-complete-path"></code>
            <button type="button" class="button button-small aieo-dmm-copy" id="aieo-dmm-orders-complete-copy-path" data-value="">
                <?php esc_html_e('Copy path', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </div>
</div>

<div class="aieo-dmm-section">
    <h3><?php esc_html_e('Field map', 'ai-eshop-optimizer'); ?></h3>
    <p class="description">
        <?php esc_html_e('Set once, then hide. Tick to include a field and edit the CSV header name. Reorder by dragging rows.', 'ai-eshop-optimizer'); ?>
        <button type="button" class="button button-small" id="aieo-dmm-orders-fields-toggle" style="margin-left:8px;">
            <?php esc_html_e('Show / hide field map', 'ai-eshop-optimizer'); ?>
        </button>
    </p>

    <form id="aieo-dmm-orders-fields-form" class="aieo-dmm-form" style="display:none;">
        <table class="widefat aieo-table aieo-dmm-field-map">
            <thead>
                <tr>
                    <th></th>
                    <th><?php esc_html_e('Include', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('Field', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('CSV header', 'ai-eshop-optimizer'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($field_map as $i => $entry) :
                    $key  = $entry['key'];
                    $info = $available_fields[$key] ?? array('label' => $key, 'default_header' => $key);
                ?>
                    <tr data-key="<?php echo esc_attr($key); ?>">
                        <td class="drag-handle">☰</td>
                        <td><input type="checkbox" name="fields[<?php echo (int) $i; ?>][enabled]" value="1" <?php checked(!empty($entry['enabled'])); ?>></td>
                        <td>
                            <?php echo esc_html($info['label']); ?>
                            <input type="hidden" name="fields[<?php echo (int) $i; ?>][key]" value="<?php echo esc_attr($key); ?>">
                        </td>
                        <td><input type="text" name="fields[<?php echo (int) $i; ?>][header]" value="<?php echo esc_attr((string) $entry['header']); ?>"></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <p class="submit">
            <button type="submit" class="button button-primary" data-action="aieo_dmm_orders_export_save_fields">
                <?php esc_html_e('Save field map', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </form>
</div>

<div class="aieo-dmm-section">
    <h3><?php esc_html_e('Recent exports', 'ai-eshop-optimizer'); ?></h3>
    <?php if (empty($recent_jobs)) : ?>
        <p class="description"><?php esc_html_e('No exports yet.', 'ai-eshop-optimizer'); ?></p>
    <?php else : ?>
        <table class="widefat striped aieo-table">
            <thead>
                <tr>
                    <th><?php esc_html_e('Created', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('Status', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('Rows', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('File', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('Path', 'ai-eshop-optimizer'); ?></th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recent_jobs as $job) :
                    $params = json_decode((string) ($job['params'] ?? '{}'), true);
                    $url    = is_array($params) && isset($params['public_url']) ? (string) $params['public_url']
                            : (is_array($params) && isset($params['url']) ? (string) $params['url'] : '');
                    $path   = is_array($params) && isset($params['path']) ? (string) $params['path'] : '';
                ?>
                    <tr data-job-id="<?php echo esc_attr($job['job_id']); ?>">
                        <td><?php echo esc_html((string) $job['created_at']); ?></td>
                        <td><?php echo esc_html((string) $job['status']); ?></td>
                        <td><?php echo (int) $job['processed']; ?> / <?php echo (int) $job['total']; ?></td>
                        <td>
                            <?php if ($url) : ?>
                                <a href="<?php echo esc_url($url); ?>" target="_blank"><?php echo esc_html((string) $job['filename']); ?></a>
                            <?php else : ?>
                                <?php echo esc_html((string) $job['filename']); ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($path) : ?>
                                <code style="font-size:11px;"><?php echo esc_html($path); ?></code>
                            <?php else : ?>
                                <span class="description">—</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <button type="button" class="button button-small aieo-dmm-delete-export-job">
                                <?php esc_html_e('Delete', 'ai-eshop-optimizer'); ?>
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<script>
(function () {
    // Path preview reflects format choice.
    var $fmt  = document.getElementById('aieo-dmm-orders-format');
    var $cm   = document.getElementById('aieo-dmm-orders-cache-mode');
    var $path = document.getElementById('aieo-dmm-orders-path-preview');
    var $url  = document.getElementById('aieo-dmm-orders-url-preview');
    if ($fmt && $path && $url) {
        var baseDir = <?php echo wp_json_encode($orders_dir); ?>;
        var baseUrl = <?php echo wp_json_encode($orders_url); ?>;
        function update() {
            var ext = $fmt.value === 'xml' ? 'xml' : 'csv';
            var name = ($cm && $cm.value === 'unique_filename') ? 'orders-export-<jobid>.' + ext : 'exported_orders.' + ext;
            $path.textContent = baseDir + name;
            $url.textContent  = baseUrl + name;
        }
        $fmt.addEventListener('change', update);
        if ($cm) $cm.addEventListener('change', update);
    }

    // Toggle the field-map panel — configured once, can stay hidden after.
    var $toggle = document.getElementById('aieo-dmm-orders-fields-toggle');
    var $panel  = document.getElementById('aieo-dmm-orders-fields-form');
    if ($toggle && $panel) {
        $toggle.addEventListener('click', function () {
            $panel.style.display = ($panel.style.display === 'none' || !$panel.style.display) ? 'block' : 'none';
        });
    }
})();
</script>
