<?php

if (!defined('ABSPATH')) { exit; }
?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Price export', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php esc_html_e('Generate a price file (CSV or XML) of your catalogue, optionally including role prices.', 'ai-eshop-optimizer'); ?>
    </p>

    <form id="aieo-dmm-price-export-form" class="aieo-dmm-form">
        <p>
            <label><?php esc_html_e('Format', 'ai-eshop-optimizer'); ?></label>
            <label><input type="radio" name="format" value="csv" checked> CSV</label>
            <label><input type="radio" name="format" value="xml"> XML</label>
        </p>

        <p>
            <label><?php esc_html_e('Source', 'ai-eshop-optimizer'); ?></label>
            <label>
                <input type="radio" name="source" value="live" checked>
                <?php esc_html_e('Live (WooCommerce — freshest, slower)', 'ai-eshop-optimizer'); ?>
            </label>
            <label>
                <input type="radio" name="source" value="vitals">
                <?php esc_html_e('Vitals cache (fast — reflects last vitals rebuild)', 'ai-eshop-optimizer'); ?>
            </label>
            <br>
            <span class="description">
                <?php esc_html_e('Vitals reads all fields (except role prices) from the precomputed aieo_core_product_vitals table — dramatically faster on large catalogues, but reflects the last vitals rebuild rather than in-flight WC changes. Role prices always come from their own table.', 'ai-eshop-optimizer'); ?>
            </span>
        </p>

        <p><label><?php esc_html_e('Fields to include', 'ai-eshop-optimizer'); ?></label></p>
        <ul class="aieo-dmm-checkboxes">
            <?php foreach ($available_fields as $key => $info) : ?>
                <li>
                    <label>
                        <input type="checkbox" name="fields[]" value="<?php echo esc_attr($key); ?>" checked>
                        <?php echo esc_html($info['label']); ?> <code><?php echo esc_html($info['default_header']); ?></code>
                    </label>
                </li>
            <?php endforeach; ?>
        </ul>

        <p class="submit">
            <button type="submit" class="button button-primary" data-action="aieo_dmm_price_export_start">
                <?php esc_html_e('Start export', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </form>

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

<script>
(function () {
    // Vitals source path doesn't support role-prices export — the
    // LEFT JOIN to wp_aieo_dmm_role_prices would defeat the whole
    // reason for using vitals (which is speed). Keep the checkbox
    // visible so the operator sees it exists, but disable + uncheck
    // it when Vitals is selected. Server-side enforces the same
    // restriction as a safety net for direct POSTs.
    var form = document.getElementById('aieo-dmm-price-export-form');
    if (!form) { return; }
    var roleCb = form.querySelector('input[name="fields[]"][value="role_prices"]');
    if (!roleCb) { return; }
    var roleLabel = roleCb.closest('label') || roleCb.parentElement;

    function syncSourceUI() {
        var src = (form.querySelector('input[name="source"]:checked') || {}).value || 'live';
        if (src === 'vitals') {
            roleCb.checked = false;
            roleCb.disabled = true;
            if (roleLabel) {
                roleLabel.style.opacity = '0.5';
                roleLabel.title = '<?php echo esc_js(__('Role prices are not available from the Vitals cache — switch to Live source to include them.', 'ai-eshop-optimizer')); ?>';
            }
        } else {
            roleCb.disabled = false;
            if (roleLabel) {
                roleLabel.style.opacity = '';
                roleLabel.title = '';
            }
        }
    }

    form.querySelectorAll('input[name="source"]').forEach(function (el) {
        el.addEventListener('change', syncSourceUI);
    });
    // Run once on page load in case the browser restored a Vitals selection.
    syncSourceUI();
})();
</script>

<div class="aieo-dmm-section">
    <h3><?php esc_html_e('Recent exports', 'ai-eshop-optimizer'); ?></h3>
    <?php if (empty($recent_jobs)) : ?>
        <p><?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('Processed', '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['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>
