<?php

if (!defined('ABSPATH')) { exit; }
?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Complementary products', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php esc_html_e('For each source product, define up to 3 complementary products that will be shown to the shopper on the product page with checkboxes and a single "Add selected to cart" CTA.', 'ai-eshop-optimizer'); ?>
    </p>

    <form id="aieo-dmm-complementary-form" class="aieo-dmm-form">
        <input type="hidden" name="id" value="0">
        <div class="aieo-dmm-grid">
            <p>
                <label><?php esc_html_e('Label (internal)', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="label" class="regular-text">
            </p>
            <p>
                <label class="aieo-dmm-choice" style="margin-top:24px;">
                    <input type="checkbox" name="enabled" value="1" checked>
                    <?php esc_html_e('Enabled', 'ai-eshop-optimizer'); ?>
                </label>
            </p>
            <p style="grid-column:1 / -1;">
                <label><?php esc_html_e('Source product', 'ai-eshop-optimizer'); ?></label>
                <select name="source_product_id" class="aieo-dmm-product-select regular-text" style="width:100%;"></select>
                <span class="description"><?php esc_html_e('The product whose page will display the complementary picker.', 'ai-eshop-optimizer'); ?></span>
            </p>
            <p style="grid-column:1 / -1;">
                <label><?php esc_html_e('Complementary products (up to 3)', 'ai-eshop-optimizer'); ?></label>
                <select name="product_ids[]" multiple class="aieo-dmm-product-select regular-text" style="width:100%;"></select>
            </p>
            <p>
                <label><?php esc_html_e('Picker title (shown above the list)', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="offer_title" class="regular-text" placeholder="<?php echo esc_attr($module->default_offer_title()); ?>">
            </p>
            <p>
                <label><?php esc_html_e('Button text', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="button_text" class="regular-text" placeholder="<?php echo esc_attr($module->default_button_text()); ?>">
            </p>
            <p>
                <label><?php esc_html_e('Placement', 'ai-eshop-optimizer'); ?></label>
                <select name="placement">
                    <option value="before_add_to_cart"><?php esc_html_e('Before Add to cart button', 'ai-eshop-optimizer'); ?></option>
                    <option value="after_add_to_cart"><?php esc_html_e('After Add to cart button', 'ai-eshop-optimizer'); ?></option>
                    <option value="after_summary"><?php esc_html_e('After product summary', 'ai-eshop-optimizer'); ?></option>
                </select>
                <span class="description"><?php esc_html_e('NB — this affects future installs of the picker globally; today the renderer only honours the global default.', 'ai-eshop-optimizer'); ?></span>
            </p>
            <p>
                <label><?php esc_html_e('Default checkbox state', 'ai-eshop-optimizer'); ?></label>
                <select name="checkboxes_state">
                    <option value="unchecked"><?php esc_html_e('Unchecked', 'ai-eshop-optimizer'); ?></option>
                    <option value="checked"><?php esc_html_e('Pre-checked', 'ai-eshop-optimizer'); ?></option>
                </select>
            </p>
        </div>
        <p class="submit">
            <button type="submit" class="button button-primary aieo-dmm-complementary-save-btn" data-action="aieo_dmm_complementary_save">
                <?php esc_html_e('Save', 'ai-eshop-optimizer'); ?>
            </button>
            <button type="button" class="button aieo-dmm-complementary-cancel-btn" style="display:none;margin-left:6px;">
                <?php esc_html_e('Cancel edit', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </form>
</div>

<div class="aieo-dmm-section">
    <h3 style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
        <?php esc_html_e('Current sets', 'ai-eshop-optimizer'); ?>
        <span style="margin-left:auto;display:inline-flex;gap:8px;">
            <button type="button" class="button aieo-dmm-complementary-export-btn">
                <?php esc_html_e('Export CSV', 'ai-eshop-optimizer'); ?>
            </button>
            <button type="button" class="button aieo-dmm-complementary-import-btn">
                <?php esc_html_e('Import CSV', 'ai-eshop-optimizer'); ?>
            </button>
            <input type="file" id="aieo-dmm-complementary-csv-file" accept=".csv,text/csv" style="display:none;">
            <?php if (!empty($has_legacy_pods_data)) : ?>
            <button type="button" class="button aieo-dmm-complementary-migrate-btn">
                <?php esc_html_e('Migrate from Pods', 'ai-eshop-optimizer'); ?>
            </button>
            <?php endif; ?>
        </span>
    </h3>
    <p class="description" style="margin-bottom:8px;">
        <?php
        printf(
            
            esc_html__('CSV columns (header required): %s', 'ai-eshop-optimizer'),
            '<code>source_sku, product_1_sku, product_2_sku, product_3_sku, label, enabled, offer_title, button_text</code>'
        );
        ?>
    </p>

    <div id="aieo-dmm-complementary-empty" style="<?php echo empty($rows) ? '' : 'display:none;'; ?>">
        <p><?php esc_html_e('No complementary sets defined yet.', 'ai-eshop-optimizer'); ?></p>
    </div>
    <table id="aieo-dmm-complementary-table" class="widefat striped aieo-table" style="<?php echo empty($rows) ? 'display:none;' : ''; ?>">
        <thead>
            <tr>
                <th><?php esc_html_e('Label', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Source product', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Complementary 1', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Complementary 2', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Complementary 3', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Enabled', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Actions', 'ai-eshop-optimizer'); ?></th>
            </tr>
        </thead>
        <tbody id="aieo-dmm-complementary-tbody">
            <?php foreach ($rows as $row) {
                echo $module->render_row($row); 
            } ?>
        </tbody>
    </table>
</div>

<script>
jQuery(function($) {
    var $form    = $('#aieo-dmm-complementary-form');
    var $tbody   = $('#aieo-dmm-complementary-tbody');
    var $empty   = $('#aieo-dmm-complementary-empty');
    var $table   = $('#aieo-dmm-complementary-table');
    var $cancel  = $form.find('.aieo-dmm-complementary-cancel-btn');

    function resetForm() {
        $form[0].reset();
        $form.find('input[name="id"]').val(0);
        // Clear Select2 selections
        $form.find('select.aieo-dmm-product-select').each(function () {
            var $s = $(this);
            $s.find('option').remove();
            $s.trigger('change');
        });
        $cancel.hide();
    }

    // Load row into form on Edit click
    $tbody.on('click', '.aieo-dmm-edit-complementary', function () {
        var $tr  = $(this).closest('tr');
        var data = $tr.attr('data-row');
        if (!data) { return; }
        var row;
        try { row = JSON.parse(data); } catch (e) { return; }

        $form.find('input[name="id"]').val(row.id);
        $form.find('input[name="label"]').val(row.label || '');
        $form.find('input[name="enabled"]').prop('checked', !!row.enabled);
        $form.find('input[name="offer_title"]').val(row.offer_title || '');
        $form.find('input[name="button_text"]').val(row.button_text || '');
        $form.find('select[name="placement"]').val(row.placement || 'before_add_to_cart');
        $form.find('select[name="checkboxes_state"]').val(row.checkboxes_state || 'unchecked');

        // Pre-populate Select2s with the resolved names so chips show
        // the actual product titles, not just IDs.
        var $src = $form.find('select[name="source_product_id"]');
        $src.find('option').remove();
        if (row.source_product_id) {
            $src.append(new Option(row.source_product_name || ('#' + row.source_product_id), row.source_product_id, true, true)).trigger('change');
        }

        var $compl = $form.find('select[name="product_ids[]"]');
        $compl.find('option').remove();
        var pids   = row.product_ids || [];
        var pnames = row.product_names || [];
        for (var i = 0; i < pids.length; i++) {
            $compl.append(new Option(pnames[i] || ('#' + pids[i]), pids[i], true, true));
        }
        $compl.trigger('change');

        $cancel.show();
        $('html,body').animate({scrollTop: $form.offset().top - 80}, 200);
    });

    $cancel.on('click', resetForm);

    // Save
    $form.on('submit', function (e) {
        e.preventDefault();
        var $btn = $form.find('.aieo-dmm-complementary-save-btn');
        var data = $form.serializeArray();
        data.push({name: 'action', value: 'aieo_dmm_complementary_save'});
        data.push({name: 'nonce',  value: window.aieoDmm && aieoDmm.nonce});
        $btn.prop('disabled', true);
        $.post(window.ajaxurl, data, function (resp) {
            $btn.prop('disabled', false);
            if (!resp || !resp.success) {
                alert((resp && resp.data && resp.data.message) || 'Save failed.');
                return;
            }
            var html = resp.data.row_html;
            var $existing = $tbody.find('tr[data-id="' + resp.data.id + '"]');
            if ($existing.length) {
                $existing.replaceWith(html);
            } else {
                $tbody.prepend(html);
            }
            $empty.hide(); $table.show();
            resetForm();
        }).fail(function () {
            $btn.prop('disabled', false);
            alert('Save failed (network).');
        });
    });

    // Delete handled by dmm.js's generic .aieo-dmm-delete-row delegate.

    // Export CSV
    $('.aieo-dmm-complementary-export-btn').on('click', function () {
        $.post(window.ajaxurl, {
            action: 'aieo_dmm_complementary_export',
            nonce:  window.aieoDmm && aieoDmm.nonce,
        }, function (resp) {
            if (!resp || !resp.success) { alert('Export failed.'); return; }
            var a = document.createElement('a');
            a.href     = 'data:' + resp.data.mime + ';base64,' + resp.data.b64;
            a.download = resp.data.filename;
            document.body.appendChild(a); a.click(); a.remove();
        });
    });

    // Import CSV
    $('.aieo-dmm-complementary-import-btn').on('click', function () {
        $('#aieo-dmm-complementary-csv-file').trigger('click');
    });
    $('#aieo-dmm-complementary-csv-file').on('change', function () {
        var file = this.files && this.files[0];
        if (!file) { return; }
        var fd = new FormData();
        fd.append('action', 'aieo_dmm_complementary_import');
        fd.append('nonce',  window.aieoDmm && aieoDmm.nonce);
        fd.append('csv',    file);
        $.ajax({
            url: window.ajaxurl, method: 'POST', data: fd,
            contentType: false, processData: false,
            success: function (resp) {
                if (!resp || !resp.success) {
                    alert((resp && resp.data && resp.data.message) || 'Import failed.');
                    return;
                }
                alert(resp.data.message);
                window.location.reload();
            },
            error: function () { alert('Import failed (network).'); }
        });
        this.value = '';
    });

    // Migrate from Pods
    $('.aieo-dmm-complementary-migrate-btn').on('click', function () {
        if (!window.confirm('Migrate complementary data from the legacy Pods promo_campaign rows? Existing AIEO rows for the same source product will be updated.')) {
            return;
        }
        var $btn = $(this).prop('disabled', true);
        $.post(window.ajaxurl, {
            action: 'aieo_dmm_complementary_migrate',
            nonce:  window.aieoDmm && aieoDmm.nonce,
        }, function (resp) {
            $btn.prop('disabled', false);
            if (!resp || !resp.success) {
                alert((resp && resp.data && resp.data.message) || 'Migration failed.');
                return;
            }
            alert(resp.data.message);
            window.location.reload();
        }).fail(function () {
            $btn.prop('disabled', false);
            alert('Migration failed (network).');
        });
    });
});
</script>
